babylon.no-module.max.js 5.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771
  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. BABYLON.ToGammaSpace = 1 / 2.2;
  1397. BABYLON.ToLinearSpace = 2.2;
  1398. BABYLON.Epsilon = 0.001;
  1399. /**
  1400. * Class used to hold a RBG color
  1401. */
  1402. var Color3 = /** @class */ (function () {
  1403. /**
  1404. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1405. * @param r defines the red component (between 0 and 1, default is 0)
  1406. * @param g defines the green component (between 0 and 1, default is 0)
  1407. * @param b defines the blue component (between 0 and 1, default is 0)
  1408. */
  1409. function Color3(
  1410. /**
  1411. * Defines the red component (between 0 and 1, default is 0)
  1412. */
  1413. r,
  1414. /**
  1415. * Defines the green component (between 0 and 1, default is 0)
  1416. */
  1417. g,
  1418. /**
  1419. * Defines the blue component (between 0 and 1, default is 0)
  1420. */
  1421. b) {
  1422. if (r === void 0) { r = 0; }
  1423. if (g === void 0) { g = 0; }
  1424. if (b === void 0) { b = 0; }
  1425. this.r = r;
  1426. this.g = g;
  1427. this.b = b;
  1428. }
  1429. /**
  1430. * Creates a string with the Color3 current values
  1431. * @returns the string representation of the Color3 object
  1432. */
  1433. Color3.prototype.toString = function () {
  1434. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1435. };
  1436. /**
  1437. * Returns the string "Color3"
  1438. * @returns "Color3"
  1439. */
  1440. Color3.prototype.getClassName = function () {
  1441. return "Color3";
  1442. };
  1443. /**
  1444. * Compute the Color3 hash code
  1445. * @returns an unique number that can be used to hash Color3 objects
  1446. */
  1447. Color3.prototype.getHashCode = function () {
  1448. var hash = this.r || 0;
  1449. hash = (hash * 397) ^ (this.g || 0);
  1450. hash = (hash * 397) ^ (this.b || 0);
  1451. return hash;
  1452. };
  1453. // Operators
  1454. /**
  1455. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1456. * @param array defines the array where to store the r,g,b components
  1457. * @param index defines an optional index in the target array to define where to start storing values
  1458. * @returns the current Color3 object
  1459. */
  1460. Color3.prototype.toArray = function (array, index) {
  1461. if (index === undefined) {
  1462. index = 0;
  1463. }
  1464. array[index] = this.r;
  1465. array[index + 1] = this.g;
  1466. array[index + 2] = this.b;
  1467. return this;
  1468. };
  1469. /**
  1470. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1471. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1472. * @returns a new {BABYLON.Color4} object
  1473. */
  1474. Color3.prototype.toColor4 = function (alpha) {
  1475. if (alpha === void 0) { alpha = 1; }
  1476. return new Color4(this.r, this.g, this.b, alpha);
  1477. };
  1478. /**
  1479. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1480. * @returns the new array
  1481. */
  1482. Color3.prototype.asArray = function () {
  1483. var result = new Array();
  1484. this.toArray(result, 0);
  1485. return result;
  1486. };
  1487. /**
  1488. * Returns the luminance value
  1489. * @returns a float value
  1490. */
  1491. Color3.prototype.toLuminance = function () {
  1492. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1493. };
  1494. /**
  1495. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1496. * @param otherColor defines the second operand
  1497. * @returns the new Color3 object
  1498. */
  1499. Color3.prototype.multiply = function (otherColor) {
  1500. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1501. };
  1502. /**
  1503. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1504. * @param otherColor defines the second operand
  1505. * @param result defines the Color3 object where to store the result
  1506. * @returns the current Color3
  1507. */
  1508. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1509. result.r = this.r * otherColor.r;
  1510. result.g = this.g * otherColor.g;
  1511. result.b = this.b * otherColor.b;
  1512. return this;
  1513. };
  1514. /**
  1515. * Determines equality between Color3 objects
  1516. * @param otherColor defines the second operand
  1517. * @returns true if the rgb values are equal to the given ones
  1518. */
  1519. Color3.prototype.equals = function (otherColor) {
  1520. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1521. };
  1522. /**
  1523. * Determines equality between the current Color3 object and a set of r,b,g values
  1524. * @param r defines the red component to check
  1525. * @param g defines the green component to check
  1526. * @param b defines the blue component to check
  1527. * @returns true if the rgb values are equal to the given ones
  1528. */
  1529. Color3.prototype.equalsFloats = function (r, g, b) {
  1530. return this.r === r && this.g === g && this.b === b;
  1531. };
  1532. /**
  1533. * Multiplies in place each rgb value by scale
  1534. * @param scale defines the scaling factor
  1535. * @returns the updated Color3
  1536. */
  1537. Color3.prototype.scale = function (scale) {
  1538. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1539. };
  1540. /**
  1541. * Multiplies the rgb values by scale and stores the result into "result"
  1542. * @param scale defines the scaling factor
  1543. * @param result defines the Color3 object where to store the result
  1544. * @returns the unmodified current Color3
  1545. */
  1546. Color3.prototype.scaleToRef = function (scale, result) {
  1547. result.r = this.r * scale;
  1548. result.g = this.g * scale;
  1549. result.b = this.b * scale;
  1550. return this;
  1551. };
  1552. /**
  1553. * Scale the current Color3 values by a factor and add the result to a given Color3
  1554. * @param scale defines the scale factor
  1555. * @param result defines color to store the result into
  1556. * @returns the unmodified current Color3
  1557. */
  1558. Color3.prototype.scaleAndAddToRef = 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. * Clamps the rgb values by the min and max values and stores the result into "result"
  1566. * @param min defines minimum clamping value (default is 0)
  1567. * @param max defines maximum clamping value (default is 1)
  1568. * @param result defines color to store the result into
  1569. * @returns the original Color3
  1570. */
  1571. Color3.prototype.clampToRef = function (min, max, result) {
  1572. if (min === void 0) { min = 0; }
  1573. if (max === void 0) { max = 1; }
  1574. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1575. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1576. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1577. return this;
  1578. };
  1579. /**
  1580. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1581. * @param otherColor defines the second operand
  1582. * @returns the new Color3
  1583. */
  1584. Color3.prototype.add = function (otherColor) {
  1585. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1586. };
  1587. /**
  1588. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1589. * @param otherColor defines the second operand
  1590. * @param result defines Color3 object to store the result into
  1591. * @returns the unmodified current Color3
  1592. */
  1593. Color3.prototype.addToRef = function (otherColor, result) {
  1594. result.r = this.r + otherColor.r;
  1595. result.g = this.g + otherColor.g;
  1596. result.b = this.b + otherColor.b;
  1597. return this;
  1598. };
  1599. /**
  1600. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1601. * @param otherColor defines the second operand
  1602. * @returns the new Color3
  1603. */
  1604. Color3.prototype.subtract = function (otherColor) {
  1605. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1606. };
  1607. /**
  1608. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1609. * @param otherColor defines the second operand
  1610. * @param result defines Color3 object to store the result into
  1611. * @returns the unmodified current Color3
  1612. */
  1613. Color3.prototype.subtractToRef = function (otherColor, result) {
  1614. result.r = this.r - otherColor.r;
  1615. result.g = this.g - otherColor.g;
  1616. result.b = this.b - otherColor.b;
  1617. return this;
  1618. };
  1619. /**
  1620. * Copy the current object
  1621. * @returns a new Color3 copied the current one
  1622. */
  1623. Color3.prototype.clone = function () {
  1624. return new Color3(this.r, this.g, this.b);
  1625. };
  1626. /**
  1627. * Copies the rgb values from the source in the current Color3
  1628. * @param source defines the source Color3 object
  1629. * @returns the updated Color3 object
  1630. */
  1631. Color3.prototype.copyFrom = function (source) {
  1632. this.r = source.r;
  1633. this.g = source.g;
  1634. this.b = source.b;
  1635. return this;
  1636. };
  1637. /**
  1638. * Updates the Color3 rgb values from the given floats
  1639. * @param r defines the red component to read from
  1640. * @param g defines the green component to read from
  1641. * @param b defines the blue component to read from
  1642. * @returns the current Color3 object
  1643. */
  1644. Color3.prototype.copyFromFloats = function (r, g, b) {
  1645. this.r = r;
  1646. this.g = g;
  1647. this.b = b;
  1648. return this;
  1649. };
  1650. /**
  1651. * Updates the Color3 rgb values from the given floats
  1652. * @param r defines the red component to read from
  1653. * @param g defines the green component to read from
  1654. * @param b defines the blue component to read from
  1655. * @returns the current Color3 object
  1656. */
  1657. Color3.prototype.set = function (r, g, b) {
  1658. return this.copyFromFloats(r, g, b);
  1659. };
  1660. /**
  1661. * Compute the Color3 hexadecimal code as a string
  1662. * @returns a string containing the hexadecimal representation of the Color3 object
  1663. */
  1664. Color3.prototype.toHexString = function () {
  1665. var intR = (this.r * 255) | 0;
  1666. var intG = (this.g * 255) | 0;
  1667. var intB = (this.b * 255) | 0;
  1668. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1669. };
  1670. /**
  1671. * Computes a new Color3 converted from the current one to linear space
  1672. * @returns a new Color3 object
  1673. */
  1674. Color3.prototype.toLinearSpace = function () {
  1675. var convertedColor = new Color3();
  1676. this.toLinearSpaceToRef(convertedColor);
  1677. return convertedColor;
  1678. };
  1679. /**
  1680. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1681. * @param convertedColor defines the Color3 object where to store the linear space version
  1682. * @returns the unmodified Color3
  1683. */
  1684. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1685. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1686. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1687. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1688. return this;
  1689. };
  1690. /**
  1691. * Computes a new Color3 converted from the current one to gamma space
  1692. * @returns a new Color3 object
  1693. */
  1694. Color3.prototype.toGammaSpace = function () {
  1695. var convertedColor = new Color3();
  1696. this.toGammaSpaceToRef(convertedColor);
  1697. return convertedColor;
  1698. };
  1699. /**
  1700. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1701. * @param convertedColor defines the Color3 object where to store the gamma space version
  1702. * @returns the unmodified Color3
  1703. */
  1704. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1705. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1706. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1707. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1708. return this;
  1709. };
  1710. // Statics
  1711. /**
  1712. * Creates a new Color3 from the string containing valid hexadecimal values
  1713. * @param hex defines a string containing valid hexadecimal values
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromHexString = function (hex) {
  1717. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1718. return new Color3(0, 0, 0);
  1719. }
  1720. var r = parseInt(hex.substring(1, 3), 16);
  1721. var g = parseInt(hex.substring(3, 5), 16);
  1722. var b = parseInt(hex.substring(5, 7), 16);
  1723. return Color3.FromInts(r, g, b);
  1724. };
  1725. /**
  1726. * Creates a new Vector3 from the starting index of the given array
  1727. * @param array defines the source array
  1728. * @param offset defines an offset in the source array
  1729. * @returns a new Color3 object
  1730. */
  1731. Color3.FromArray = function (array, offset) {
  1732. if (offset === void 0) { offset = 0; }
  1733. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1734. };
  1735. /**
  1736. * Creates a new Color3 from integer values (< 256)
  1737. * @param r defines the red component to read from (value between 0 and 255)
  1738. * @param g defines the green component to read from (value between 0 and 255)
  1739. * @param b defines the blue component to read from (value between 0 and 255)
  1740. * @returns a new Color3 object
  1741. */
  1742. Color3.FromInts = function (r, g, b) {
  1743. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1744. };
  1745. /**
  1746. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1747. * @param start defines the start Color3 value
  1748. * @param end defines the end Color3 value
  1749. * @param amount defines the gradient value between start and end
  1750. * @returns a new Color3 object
  1751. */
  1752. Color3.Lerp = function (start, end, amount) {
  1753. var result = new Color3(0.0, 0.0, 0.0);
  1754. Color3.LerpToRef(start, end, amount, result);
  1755. return result;
  1756. };
  1757. /**
  1758. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1759. * @param left defines the start value
  1760. * @param right defines the end value
  1761. * @param amount defines the gradient factor
  1762. * @param result defines the Color3 object where to store the result
  1763. */
  1764. Color3.LerpToRef = function (left, right, amount, result) {
  1765. result.r = left.r + ((right.r - left.r) * amount);
  1766. result.g = left.g + ((right.g - left.g) * amount);
  1767. result.b = left.b + ((right.b - left.b) * amount);
  1768. };
  1769. /**
  1770. * Returns a Color3 value containing a red color
  1771. * @returns a new Color3 object
  1772. */
  1773. Color3.Red = function () { return new Color3(1, 0, 0); };
  1774. /**
  1775. * Returns a Color3 value containing a green color
  1776. * @returns a new Color3 object
  1777. */
  1778. Color3.Green = function () { return new Color3(0, 1, 0); };
  1779. /**
  1780. * Returns a Color3 value containing a blue color
  1781. * @returns a new Color3 object
  1782. */
  1783. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1784. /**
  1785. * Returns a Color3 value containing a black color
  1786. * @returns a new Color3 object
  1787. */
  1788. Color3.Black = function () { return new Color3(0, 0, 0); };
  1789. /**
  1790. * Returns a Color3 value containing a white color
  1791. * @returns a new Color3 object
  1792. */
  1793. Color3.White = function () { return new Color3(1, 1, 1); };
  1794. /**
  1795. * Returns a Color3 value containing a purple color
  1796. * @returns a new Color3 object
  1797. */
  1798. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1799. /**
  1800. * Returns a Color3 value containing a magenta color
  1801. * @returns a new Color3 object
  1802. */
  1803. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1804. /**
  1805. * Returns a Color3 value containing a yellow color
  1806. * @returns a new Color3 object
  1807. */
  1808. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1809. /**
  1810. * Returns a Color3 value containing a gray color
  1811. * @returns a new Color3 object
  1812. */
  1813. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1814. /**
  1815. * Returns a Color3 value containing a teal color
  1816. * @returns a new Color3 object
  1817. */
  1818. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1819. /**
  1820. * Returns a Color3 value containing a random color
  1821. * @returns a new Color3 object
  1822. */
  1823. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1824. return Color3;
  1825. }());
  1826. BABYLON.Color3 = Color3;
  1827. /**
  1828. * Class used to hold a RBGA color
  1829. */
  1830. var Color4 = /** @class */ (function () {
  1831. /**
  1832. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1833. * @param r defines the red component (between 0 and 1, default is 0)
  1834. * @param g defines the green component (between 0 and 1, default is 0)
  1835. * @param b defines the blue component (between 0 and 1, default is 0)
  1836. * @param a defines the alpha component (between 0 and 1, default is 1)
  1837. */
  1838. function Color4(
  1839. /**
  1840. * Defines the red component (between 0 and 1, default is 0)
  1841. */
  1842. r,
  1843. /**
  1844. * Defines the green component (between 0 and 1, default is 0)
  1845. */
  1846. g,
  1847. /**
  1848. * Defines the blue component (between 0 and 1, default is 0)
  1849. */
  1850. b,
  1851. /**
  1852. * Defines the alpha component (between 0 and 1, default is 1)
  1853. */
  1854. a) {
  1855. if (r === void 0) { r = 0; }
  1856. if (g === void 0) { g = 0; }
  1857. if (b === void 0) { b = 0; }
  1858. if (a === void 0) { a = 1; }
  1859. this.r = r;
  1860. this.g = g;
  1861. this.b = b;
  1862. this.a = a;
  1863. }
  1864. // Operators
  1865. /**
  1866. * Adds in place the given Color4 values to the current Color4 object
  1867. * @param right defines the second operand
  1868. * @returns the current updated Color4 object
  1869. */
  1870. Color4.prototype.addInPlace = function (right) {
  1871. this.r += right.r;
  1872. this.g += right.g;
  1873. this.b += right.b;
  1874. this.a += right.a;
  1875. return this;
  1876. };
  1877. /**
  1878. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1879. * @returns the new array
  1880. */
  1881. Color4.prototype.asArray = function () {
  1882. var result = new Array();
  1883. this.toArray(result, 0);
  1884. return result;
  1885. };
  1886. /**
  1887. * Stores from the starting index in the given array the Color4 successive values
  1888. * @param array defines the array where to store the r,g,b components
  1889. * @param index defines an optional index in the target array to define where to start storing values
  1890. * @returns the current Color4 object
  1891. */
  1892. Color4.prototype.toArray = function (array, index) {
  1893. if (index === undefined) {
  1894. index = 0;
  1895. }
  1896. array[index] = this.r;
  1897. array[index + 1] = this.g;
  1898. array[index + 2] = this.b;
  1899. array[index + 3] = this.a;
  1900. return this;
  1901. };
  1902. /**
  1903. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1904. * @param right defines the second operand
  1905. * @returns a new Color4 object
  1906. */
  1907. Color4.prototype.add = function (right) {
  1908. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1909. };
  1910. /**
  1911. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1912. * @param right defines the second operand
  1913. * @returns a new Color4 object
  1914. */
  1915. Color4.prototype.subtract = function (right) {
  1916. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1917. };
  1918. /**
  1919. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1920. * @param right defines the second operand
  1921. * @param result defines the Color4 object where to store the result
  1922. * @returns the current Color4 object
  1923. */
  1924. Color4.prototype.subtractToRef = function (right, result) {
  1925. result.r = this.r - right.r;
  1926. result.g = this.g - right.g;
  1927. result.b = this.b - right.b;
  1928. result.a = this.a - right.a;
  1929. return this;
  1930. };
  1931. /**
  1932. * Creates a new Color4 with the current Color4 values multiplied by scale
  1933. * @param scale defines the scaling factor to apply
  1934. * @returns a new Color4 object
  1935. */
  1936. Color4.prototype.scale = function (scale) {
  1937. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1938. };
  1939. /**
  1940. * Multiplies the current Color4 values by scale and stores the result in "result"
  1941. * @param scale defines the scaling factor to apply
  1942. * @param result defines the Color4 object where to store the result
  1943. * @returns the current unmodified Color4
  1944. */
  1945. Color4.prototype.scaleToRef = function (scale, result) {
  1946. result.r = this.r * scale;
  1947. result.g = this.g * scale;
  1948. result.b = this.b * scale;
  1949. result.a = this.a * scale;
  1950. return this;
  1951. };
  1952. /**
  1953. * Scale the current Color4 values by a factor and add the result to a given Color4
  1954. * @param scale defines the scale factor
  1955. * @param result defines the Color4 object where to store the result
  1956. * @returns the unmodified current Color4
  1957. */
  1958. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1959. result.r += this.r * scale;
  1960. result.g += this.g * scale;
  1961. result.b += this.b * scale;
  1962. result.a += this.a * scale;
  1963. return this;
  1964. };
  1965. /**
  1966. * Clamps the rgb values by the min and max values and stores the result into "result"
  1967. * @param min defines minimum clamping value (default is 0)
  1968. * @param max defines maximum clamping value (default is 1)
  1969. * @param result defines color to store the result into.
  1970. * @returns the cuurent Color4
  1971. */
  1972. Color4.prototype.clampToRef = function (min, max, result) {
  1973. if (min === void 0) { min = 0; }
  1974. if (max === void 0) { max = 1; }
  1975. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1976. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1977. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1978. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1979. return this;
  1980. };
  1981. /**
  1982. * Multipy an Color4 value by another and return a new Color4 object
  1983. * @param color defines the Color4 value to multiply by
  1984. * @returns a new Color4 object
  1985. */
  1986. Color4.prototype.multiply = function (color) {
  1987. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1988. };
  1989. /**
  1990. * Multipy a Color4 value by another and push the result in a reference value
  1991. * @param color defines the Color4 value to multiply by
  1992. * @param result defines the Color4 to fill the result in
  1993. * @returns the result Color4
  1994. */
  1995. Color4.prototype.multiplyToRef = function (color, result) {
  1996. result.r = this.r * color.r;
  1997. result.g = this.g * color.g;
  1998. result.b = this.b * color.b;
  1999. result.a = this.a * color.a;
  2000. return result;
  2001. };
  2002. /**
  2003. * Creates a string with the Color4 current values
  2004. * @returns the string representation of the Color4 object
  2005. */
  2006. Color4.prototype.toString = function () {
  2007. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2008. };
  2009. /**
  2010. * Returns the string "Color4"
  2011. * @returns "Color4"
  2012. */
  2013. Color4.prototype.getClassName = function () {
  2014. return "Color4";
  2015. };
  2016. /**
  2017. * Compute the Color4 hash code
  2018. * @returns an unique number that can be used to hash Color4 objects
  2019. */
  2020. Color4.prototype.getHashCode = function () {
  2021. var hash = this.r || 0;
  2022. hash = (hash * 397) ^ (this.g || 0);
  2023. hash = (hash * 397) ^ (this.b || 0);
  2024. hash = (hash * 397) ^ (this.a || 0);
  2025. return hash;
  2026. };
  2027. /**
  2028. * Creates a new Color4 copied from the current one
  2029. * @returns a new Color4 object
  2030. */
  2031. Color4.prototype.clone = function () {
  2032. return new Color4(this.r, this.g, this.b, this.a);
  2033. };
  2034. /**
  2035. * Copies the given Color4 values into the current one
  2036. * @param source defines the source Color4 object
  2037. * @returns the current updated Color4 object
  2038. */
  2039. Color4.prototype.copyFrom = function (source) {
  2040. this.r = source.r;
  2041. this.g = source.g;
  2042. this.b = source.b;
  2043. this.a = source.a;
  2044. return this;
  2045. };
  2046. /**
  2047. * Copies the given float values into the current one
  2048. * @param r defines the red component to read from
  2049. * @param g defines the green component to read from
  2050. * @param b defines the blue component to read from
  2051. * @param a defines the alpha component to read from
  2052. * @returns the current updated Color4 object
  2053. */
  2054. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2055. this.r = r;
  2056. this.g = g;
  2057. this.b = b;
  2058. this.a = a;
  2059. return this;
  2060. };
  2061. /**
  2062. * Copies the given float values into the current one
  2063. * @param r defines the red component to read from
  2064. * @param g defines the green component to read from
  2065. * @param b defines the blue component to read from
  2066. * @param a defines the alpha component to read from
  2067. * @returns the current updated Color4 object
  2068. */
  2069. Color4.prototype.set = function (r, g, b, a) {
  2070. return this.copyFromFloats(r, g, b, a);
  2071. };
  2072. /**
  2073. * Compute the Color4 hexadecimal code as a string
  2074. * @returns a string containing the hexadecimal representation of the Color4 object
  2075. */
  2076. Color4.prototype.toHexString = function () {
  2077. var intR = (this.r * 255) | 0;
  2078. var intG = (this.g * 255) | 0;
  2079. var intB = (this.b * 255) | 0;
  2080. var intA = (this.a * 255) | 0;
  2081. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2082. };
  2083. /**
  2084. * Computes a new Color4 converted from the current one to linear space
  2085. * @returns a new Color4 object
  2086. */
  2087. Color4.prototype.toLinearSpace = function () {
  2088. var convertedColor = new Color4();
  2089. this.toLinearSpaceToRef(convertedColor);
  2090. return convertedColor;
  2091. };
  2092. /**
  2093. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2094. * @param convertedColor defines the Color4 object where to store the linear space version
  2095. * @returns the unmodified Color4
  2096. */
  2097. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2098. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2099. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2100. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2101. convertedColor.a = this.a;
  2102. return this;
  2103. };
  2104. /**
  2105. * Computes a new Color4 converted from the current one to gamma space
  2106. * @returns a new Color4 object
  2107. */
  2108. Color4.prototype.toGammaSpace = function () {
  2109. var convertedColor = new Color4();
  2110. this.toGammaSpaceToRef(convertedColor);
  2111. return convertedColor;
  2112. };
  2113. /**
  2114. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2115. * @param convertedColor defines the Color4 object where to store the gamma space version
  2116. * @returns the unmodified Color4
  2117. */
  2118. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2119. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2120. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2121. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2122. convertedColor.a = this.a;
  2123. return this;
  2124. };
  2125. // Statics
  2126. /**
  2127. * Creates a new Color4 from the string containing valid hexadecimal values
  2128. * @param hex defines a string containing valid hexadecimal values
  2129. * @returns a new Color4 object
  2130. */
  2131. Color4.FromHexString = function (hex) {
  2132. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2133. return new Color4(0.0, 0.0, 0.0, 0.0);
  2134. }
  2135. var r = parseInt(hex.substring(1, 3), 16);
  2136. var g = parseInt(hex.substring(3, 5), 16);
  2137. var b = parseInt(hex.substring(5, 7), 16);
  2138. var a = parseInt(hex.substring(7, 9), 16);
  2139. return Color4.FromInts(r, g, b, a);
  2140. };
  2141. /**
  2142. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2143. * @param left defines the start value
  2144. * @param right defines the end value
  2145. * @param amount defines the gradient factor
  2146. * @returns a new Color4 object
  2147. */
  2148. Color4.Lerp = function (left, right, amount) {
  2149. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2150. Color4.LerpToRef(left, right, amount, result);
  2151. return result;
  2152. };
  2153. /**
  2154. * Set the given "result" 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. * @param result defines the Color4 object where to store data
  2159. */
  2160. Color4.LerpToRef = function (left, right, amount, result) {
  2161. result.r = left.r + (right.r - left.r) * amount;
  2162. result.g = left.g + (right.g - left.g) * amount;
  2163. result.b = left.b + (right.b - left.b) * amount;
  2164. result.a = left.a + (right.a - left.a) * amount;
  2165. };
  2166. /**
  2167. * Creates a new Color4 from a Color3 and an alpha value
  2168. * @param color3 defines the source Color3 to read from
  2169. * @param alpha defines the alpha component (1.0 by default)
  2170. * @returns a new Color4 object
  2171. */
  2172. Color4.FromColor3 = function (color3, alpha) {
  2173. if (alpha === void 0) { alpha = 1.0; }
  2174. return new Color4(color3.r, color3.g, color3.b, alpha);
  2175. };
  2176. /**
  2177. * Creates a new Color4 from the starting index element of the given array
  2178. * @param array defines the source array to read from
  2179. * @param offset defines the offset in the source array
  2180. * @returns a new Color4 object
  2181. */
  2182. Color4.FromArray = function (array, offset) {
  2183. if (offset === void 0) { offset = 0; }
  2184. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2185. };
  2186. /**
  2187. * Creates a new Color3 from integer values (< 256)
  2188. * @param r defines the red component to read from (value between 0 and 255)
  2189. * @param g defines the green component to read from (value between 0 and 255)
  2190. * @param b defines the blue component to read from (value between 0 and 255)
  2191. * @param a defines the alpha component to read from (value between 0 and 255)
  2192. * @returns a new Color3 object
  2193. */
  2194. Color4.FromInts = function (r, g, b, a) {
  2195. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2196. };
  2197. /**
  2198. * Check the content of a given array and convert it to an array containing RGBA data
  2199. * If the original array was already containing count * 4 values then it is returned directly
  2200. * @param colors defines the array to check
  2201. * @param count defines the number of RGBA data to expect
  2202. * @returns an array containing count * 4 values (RGBA)
  2203. */
  2204. Color4.CheckColors4 = function (colors, count) {
  2205. // Check if color3 was used
  2206. if (colors.length === count * 3) {
  2207. var colors4 = [];
  2208. for (var index = 0; index < colors.length; index += 3) {
  2209. var newIndex = (index / 3) * 4;
  2210. colors4[newIndex] = colors[index];
  2211. colors4[newIndex + 1] = colors[index + 1];
  2212. colors4[newIndex + 2] = colors[index + 2];
  2213. colors4[newIndex + 3] = 1.0;
  2214. }
  2215. return colors4;
  2216. }
  2217. return colors;
  2218. };
  2219. return Color4;
  2220. }());
  2221. BABYLON.Color4 = Color4;
  2222. /**
  2223. * Class representing a vector containing 2 coordinates
  2224. */
  2225. var Vector2 = /** @class */ (function () {
  2226. /**
  2227. * Creates a new Vector2 from the given x and y coordinates
  2228. * @param x defines the first coordinate
  2229. * @param y defines the second coordinate
  2230. */
  2231. function Vector2(
  2232. /** defines the first coordinate */
  2233. x,
  2234. /** defines the second coordinate */
  2235. y) {
  2236. if (x === void 0) { x = 0; }
  2237. if (y === void 0) { y = 0; }
  2238. this.x = x;
  2239. this.y = y;
  2240. }
  2241. /**
  2242. * Gets a string with the Vector2 coordinates
  2243. * @returns a string with the Vector2 coordinates
  2244. */
  2245. Vector2.prototype.toString = function () {
  2246. return "{X: " + this.x + " Y:" + this.y + "}";
  2247. };
  2248. /**
  2249. * Gets class name
  2250. * @returns the string "Vector2"
  2251. */
  2252. Vector2.prototype.getClassName = function () {
  2253. return "Vector2";
  2254. };
  2255. /**
  2256. * Gets current vector hash code
  2257. * @returns the Vector2 hash code as a number
  2258. */
  2259. Vector2.prototype.getHashCode = function () {
  2260. var hash = this.x || 0;
  2261. hash = (hash * 397) ^ (this.y || 0);
  2262. return hash;
  2263. };
  2264. // Operators
  2265. /**
  2266. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2267. * @param array defines the source array
  2268. * @param index defines the offset in source array
  2269. * @returns the current Vector2
  2270. */
  2271. Vector2.prototype.toArray = function (array, index) {
  2272. if (index === void 0) { index = 0; }
  2273. array[index] = this.x;
  2274. array[index + 1] = this.y;
  2275. return this;
  2276. };
  2277. /**
  2278. * Copy the current vector to an array
  2279. * @returns a new array with 2 elements: the Vector2 coordinates.
  2280. */
  2281. Vector2.prototype.asArray = function () {
  2282. var result = new Array();
  2283. this.toArray(result, 0);
  2284. return result;
  2285. };
  2286. /**
  2287. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2288. * @param source defines the source Vector2
  2289. * @returns the current updated Vector2
  2290. */
  2291. Vector2.prototype.copyFrom = function (source) {
  2292. this.x = source.x;
  2293. this.y = source.y;
  2294. return this;
  2295. };
  2296. /**
  2297. * Sets the Vector2 coordinates with the given floats
  2298. * @param x defines the first coordinate
  2299. * @param y defines the second coordinate
  2300. * @returns the current updated Vector2
  2301. */
  2302. Vector2.prototype.copyFromFloats = function (x, y) {
  2303. this.x = x;
  2304. this.y = y;
  2305. return this;
  2306. };
  2307. /**
  2308. * Sets the Vector2 coordinates with the given floats
  2309. * @param x defines the first coordinate
  2310. * @param y defines the second coordinate
  2311. * @returns the current updated Vector2
  2312. */
  2313. Vector2.prototype.set = function (x, y) {
  2314. return this.copyFromFloats(x, y);
  2315. };
  2316. /**
  2317. * Add another vector with the current one
  2318. * @param otherVector defines the other vector
  2319. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2320. */
  2321. Vector2.prototype.add = function (otherVector) {
  2322. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2323. };
  2324. /**
  2325. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2326. * @param otherVector defines the other vector
  2327. * @param result defines the target vector
  2328. * @returns the unmodified current Vector2
  2329. */
  2330. Vector2.prototype.addToRef = function (otherVector, result) {
  2331. result.x = this.x + otherVector.x;
  2332. result.y = this.y + otherVector.y;
  2333. return this;
  2334. };
  2335. /**
  2336. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2337. * @param otherVector defines the other vector
  2338. * @returns the current updated Vector2
  2339. */
  2340. Vector2.prototype.addInPlace = function (otherVector) {
  2341. this.x += otherVector.x;
  2342. this.y += otherVector.y;
  2343. return this;
  2344. };
  2345. /**
  2346. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2347. * @param otherVector defines the other vector
  2348. * @returns a new Vector2
  2349. */
  2350. Vector2.prototype.addVector3 = function (otherVector) {
  2351. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2352. };
  2353. /**
  2354. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2355. * @param otherVector defines the other vector
  2356. * @returns a new Vector2
  2357. */
  2358. Vector2.prototype.subtract = function (otherVector) {
  2359. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2360. };
  2361. /**
  2362. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2363. * @param otherVector defines the other vector
  2364. * @param result defines the target vector
  2365. * @returns the unmodified current Vector2
  2366. */
  2367. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2368. result.x = this.x - otherVector.x;
  2369. result.y = this.y - otherVector.y;
  2370. return this;
  2371. };
  2372. /**
  2373. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2374. * @param otherVector defines the other vector
  2375. * @returns the current updated Vector2
  2376. */
  2377. Vector2.prototype.subtractInPlace = function (otherVector) {
  2378. this.x -= otherVector.x;
  2379. this.y -= otherVector.y;
  2380. return this;
  2381. };
  2382. /**
  2383. * Multiplies in place the current Vector2 coordinates by the given ones
  2384. * @param otherVector defines the other vector
  2385. * @returns the current updated Vector2
  2386. */
  2387. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2388. this.x *= otherVector.x;
  2389. this.y *= otherVector.y;
  2390. return this;
  2391. };
  2392. /**
  2393. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2394. * @param otherVector defines the other vector
  2395. * @returns a new Vector2
  2396. */
  2397. Vector2.prototype.multiply = function (otherVector) {
  2398. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2399. };
  2400. /**
  2401. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2402. * @param otherVector defines the other vector
  2403. * @param result defines the target vector
  2404. * @returns the unmodified current Vector2
  2405. */
  2406. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2407. result.x = this.x * otherVector.x;
  2408. result.y = this.y * otherVector.y;
  2409. return this;
  2410. };
  2411. /**
  2412. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2413. * @param x defines the first coordinate
  2414. * @param y defines the second coordinate
  2415. * @returns a new Vector2
  2416. */
  2417. Vector2.prototype.multiplyByFloats = function (x, y) {
  2418. return new Vector2(this.x * x, this.y * y);
  2419. };
  2420. /**
  2421. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2422. * @param otherVector defines the other vector
  2423. * @returns a new Vector2
  2424. */
  2425. Vector2.prototype.divide = function (otherVector) {
  2426. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2427. };
  2428. /**
  2429. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2430. * @param otherVector defines the other vector
  2431. * @param result defines the target vector
  2432. * @returns the unmodified current Vector2
  2433. */
  2434. Vector2.prototype.divideToRef = function (otherVector, result) {
  2435. result.x = this.x / otherVector.x;
  2436. result.y = this.y / otherVector.y;
  2437. return this;
  2438. };
  2439. /**
  2440. * Divides the current Vector2 coordinates by the given ones
  2441. * @param otherVector defines the other vector
  2442. * @returns the current updated Vector2
  2443. */
  2444. Vector2.prototype.divideInPlace = function (otherVector) {
  2445. return this.divideToRef(otherVector, this);
  2446. };
  2447. /**
  2448. * Gets a new Vector2 with current Vector2 negated coordinates
  2449. * @returns a new Vector2
  2450. */
  2451. Vector2.prototype.negate = function () {
  2452. return new Vector2(-this.x, -this.y);
  2453. };
  2454. /**
  2455. * Multiply the Vector2 coordinates by scale
  2456. * @param scale defines the scaling factor
  2457. * @returns the current updated Vector2
  2458. */
  2459. Vector2.prototype.scaleInPlace = function (scale) {
  2460. this.x *= scale;
  2461. this.y *= scale;
  2462. return this;
  2463. };
  2464. /**
  2465. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2466. * @param scale defines the scaling factor
  2467. * @returns a new Vector2
  2468. */
  2469. Vector2.prototype.scale = function (scale) {
  2470. var result = new Vector2(0, 0);
  2471. this.scaleToRef(scale, result);
  2472. return result;
  2473. };
  2474. /**
  2475. * Scale the current Vector2 values by a factor to a given Vector2
  2476. * @param scale defines the scale factor
  2477. * @param result defines the Vector2 object where to store the result
  2478. * @returns the unmodified current Vector2
  2479. */
  2480. Vector2.prototype.scaleToRef = function (scale, result) {
  2481. result.x = this.x * scale;
  2482. result.y = this.y * scale;
  2483. return this;
  2484. };
  2485. /**
  2486. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2487. * @param scale defines the scale factor
  2488. * @param result defines the Vector2 object where to store the result
  2489. * @returns the unmodified current Vector2
  2490. */
  2491. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2492. result.x += this.x * scale;
  2493. result.y += this.y * scale;
  2494. return this;
  2495. };
  2496. /**
  2497. * Gets a boolean if two vectors are equals
  2498. * @param otherVector defines the other vector
  2499. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2500. */
  2501. Vector2.prototype.equals = function (otherVector) {
  2502. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2503. };
  2504. /**
  2505. * Gets a boolean if two vectors are equals (using an epsilon value)
  2506. * @param otherVector defines the other vector
  2507. * @param epsilon defines the minimal distance to consider equality
  2508. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2509. */
  2510. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2511. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2512. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2513. };
  2514. /**
  2515. * Gets a new Vector2 from current Vector2 floored values
  2516. * @returns a new Vector2
  2517. */
  2518. Vector2.prototype.floor = function () {
  2519. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2520. };
  2521. /**
  2522. * Gets a new Vector2 from current Vector2 floored values
  2523. * @returns a new Vector2
  2524. */
  2525. Vector2.prototype.fract = function () {
  2526. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2527. };
  2528. // Properties
  2529. /**
  2530. * Gets the length of the vector
  2531. * @returns the vector length (float)
  2532. */
  2533. Vector2.prototype.length = function () {
  2534. return Math.sqrt(this.x * this.x + this.y * this.y);
  2535. };
  2536. /**
  2537. * Gets the vector squared length
  2538. * @returns the vector squared length (float)
  2539. */
  2540. Vector2.prototype.lengthSquared = function () {
  2541. return (this.x * this.x + this.y * this.y);
  2542. };
  2543. // Methods
  2544. /**
  2545. * Normalize the vector
  2546. * @returns the current updated Vector2
  2547. */
  2548. Vector2.prototype.normalize = function () {
  2549. var len = this.length();
  2550. if (len === 0)
  2551. return this;
  2552. var num = 1.0 / len;
  2553. this.x *= num;
  2554. this.y *= num;
  2555. return this;
  2556. };
  2557. /**
  2558. * Gets a new Vector2 copied from the Vector2
  2559. * @returns a new Vector2
  2560. */
  2561. Vector2.prototype.clone = function () {
  2562. return new Vector2(this.x, this.y);
  2563. };
  2564. // Statics
  2565. /**
  2566. * Gets a new Vector2(0, 0)
  2567. * @returns a new Vector2
  2568. */
  2569. Vector2.Zero = function () {
  2570. return new Vector2(0, 0);
  2571. };
  2572. /**
  2573. * Gets a new Vector2(1, 1)
  2574. * @returns a new Vector2
  2575. */
  2576. Vector2.One = function () {
  2577. return new Vector2(1, 1);
  2578. };
  2579. /**
  2580. * Gets a new Vector2 set from the given index element of the given array
  2581. * @param array defines the data source
  2582. * @param offset defines the offset in the data source
  2583. * @returns a new Vector2
  2584. */
  2585. Vector2.FromArray = function (array, offset) {
  2586. if (offset === void 0) { offset = 0; }
  2587. return new Vector2(array[offset], array[offset + 1]);
  2588. };
  2589. /**
  2590. * Sets "result" from the given index element of the given array
  2591. * @param array defines the data source
  2592. * @param offset defines the offset in the data source
  2593. * @param result defines the target vector
  2594. */
  2595. Vector2.FromArrayToRef = function (array, offset, result) {
  2596. result.x = array[offset];
  2597. result.y = array[offset + 1];
  2598. };
  2599. /**
  2600. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2601. * @param value1 defines 1st point of control
  2602. * @param value2 defines 2nd point of control
  2603. * @param value3 defines 3rd point of control
  2604. * @param value4 defines 4th point of control
  2605. * @param amount defines the interpolation factor
  2606. * @returns a new Vector2
  2607. */
  2608. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2609. var squared = amount * amount;
  2610. var cubed = amount * squared;
  2611. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2612. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2613. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2614. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2615. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2616. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2617. return new Vector2(x, y);
  2618. };
  2619. /**
  2620. * 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".
  2621. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2622. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2623. * @param value defines the value to clamp
  2624. * @param min defines the lower limit
  2625. * @param max defines the upper limit
  2626. * @returns a new Vector2
  2627. */
  2628. Vector2.Clamp = function (value, min, max) {
  2629. var x = value.x;
  2630. x = (x > max.x) ? max.x : x;
  2631. x = (x < min.x) ? min.x : x;
  2632. var y = value.y;
  2633. y = (y > max.y) ? max.y : y;
  2634. y = (y < min.y) ? min.y : y;
  2635. return new Vector2(x, y);
  2636. };
  2637. /**
  2638. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2639. * @param value1 defines the 1st control point
  2640. * @param tangent1 defines the outgoing tangent
  2641. * @param value2 defines the 2nd control point
  2642. * @param tangent2 defines the incoming tangent
  2643. * @param amount defines the interpolation factor
  2644. * @returns a new Vector2
  2645. */
  2646. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2647. var squared = amount * amount;
  2648. var cubed = amount * squared;
  2649. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2650. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2651. var part3 = (cubed - (2.0 * squared)) + amount;
  2652. var part4 = cubed - squared;
  2653. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2654. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2655. return new Vector2(x, y);
  2656. };
  2657. /**
  2658. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2659. * @param start defines the start vector
  2660. * @param end defines the end vector
  2661. * @param amount defines the interpolation factor
  2662. * @returns a new Vector2
  2663. */
  2664. Vector2.Lerp = function (start, end, amount) {
  2665. var x = start.x + ((end.x - start.x) * amount);
  2666. var y = start.y + ((end.y - start.y) * amount);
  2667. return new Vector2(x, y);
  2668. };
  2669. /**
  2670. * Gets the dot product of the vector "left" and the vector "right"
  2671. * @param left defines first vector
  2672. * @param right defines second vector
  2673. * @returns the dot product (float)
  2674. */
  2675. Vector2.Dot = function (left, right) {
  2676. return left.x * right.x + left.y * right.y;
  2677. };
  2678. /**
  2679. * Returns a new Vector2 equal to the normalized given vector
  2680. * @param vector defines the vector to normalize
  2681. * @returns a new Vector2
  2682. */
  2683. Vector2.Normalize = function (vector) {
  2684. var newVector = vector.clone();
  2685. newVector.normalize();
  2686. return newVector;
  2687. };
  2688. /**
  2689. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2690. * @param left defines 1st vector
  2691. * @param right defines 2nd vector
  2692. * @returns a new Vector2
  2693. */
  2694. Vector2.Minimize = function (left, right) {
  2695. var x = (left.x < right.x) ? left.x : right.x;
  2696. var y = (left.y < right.y) ? left.y : right.y;
  2697. return new Vector2(x, y);
  2698. };
  2699. /**
  2700. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2701. * @param left defines 1st vector
  2702. * @param right defines 2nd vector
  2703. * @returns a new Vector2
  2704. */
  2705. Vector2.Maximize = function (left, right) {
  2706. var x = (left.x > right.x) ? left.x : right.x;
  2707. var y = (left.y > right.y) ? left.y : right.y;
  2708. return new Vector2(x, y);
  2709. };
  2710. /**
  2711. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2712. * @param vector defines the vector to transform
  2713. * @param transformation defines the matrix to apply
  2714. * @returns a new Vector2
  2715. */
  2716. Vector2.Transform = function (vector, transformation) {
  2717. var r = Vector2.Zero();
  2718. Vector2.TransformToRef(vector, transformation, r);
  2719. return r;
  2720. };
  2721. /**
  2722. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2723. * @param vector defines the vector to transform
  2724. * @param transformation defines the matrix to apply
  2725. * @param result defines the target vector
  2726. */
  2727. Vector2.TransformToRef = function (vector, transformation, result) {
  2728. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2729. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2730. result.x = x;
  2731. result.y = y;
  2732. };
  2733. /**
  2734. * Determines if a given vector is included in a triangle
  2735. * @param p defines the vector to test
  2736. * @param p0 defines 1st triangle point
  2737. * @param p1 defines 2nd triangle point
  2738. * @param p2 defines 3rd triangle point
  2739. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2740. */
  2741. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2742. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2743. var sign = a < 0 ? -1 : 1;
  2744. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2745. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2746. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2747. };
  2748. /**
  2749. * Gets the distance between the vectors "value1" and "value2"
  2750. * @param value1 defines first vector
  2751. * @param value2 defines second vector
  2752. * @returns the distance between vectors
  2753. */
  2754. Vector2.Distance = function (value1, value2) {
  2755. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2756. };
  2757. /**
  2758. * Returns the squared distance between the vectors "value1" and "value2"
  2759. * @param value1 defines first vector
  2760. * @param value2 defines second vector
  2761. * @returns the squared distance between vectors
  2762. */
  2763. Vector2.DistanceSquared = function (value1, value2) {
  2764. var x = value1.x - value2.x;
  2765. var y = value1.y - value2.y;
  2766. return (x * x) + (y * y);
  2767. };
  2768. /**
  2769. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2770. * @param value1 defines first vector
  2771. * @param value2 defines second vector
  2772. * @returns a new Vector2
  2773. */
  2774. Vector2.Center = function (value1, value2) {
  2775. var center = value1.add(value2);
  2776. center.scaleInPlace(0.5);
  2777. return center;
  2778. };
  2779. /**
  2780. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2781. * @param p defines the middle point
  2782. * @param segA defines one point of the segment
  2783. * @param segB defines the other point of the segment
  2784. * @returns the shortest distance
  2785. */
  2786. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2787. var l2 = Vector2.DistanceSquared(segA, segB);
  2788. if (l2 === 0.0) {
  2789. return Vector2.Distance(p, segA);
  2790. }
  2791. var v = segB.subtract(segA);
  2792. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2793. var proj = segA.add(v.multiplyByFloats(t, t));
  2794. return Vector2.Distance(p, proj);
  2795. };
  2796. return Vector2;
  2797. }());
  2798. BABYLON.Vector2 = Vector2;
  2799. /**
  2800. * Classed used to store (x,y,z) vector representation
  2801. * A Vector3 is the main object used in 3D geometry
  2802. * It can represent etiher the coordinates of a point the space, either a direction
  2803. * Reminder: Babylon.js uses a left handed forward facing system
  2804. */
  2805. var Vector3 = /** @class */ (function () {
  2806. /**
  2807. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2808. * @param x defines the first coordinates (on X axis)
  2809. * @param y defines the second coordinates (on Y axis)
  2810. * @param z defines the third coordinates (on Z axis)
  2811. */
  2812. function Vector3(
  2813. /**
  2814. * Defines the first coordinates (on X axis)
  2815. */
  2816. x,
  2817. /**
  2818. * Defines the second coordinates (on Y axis)
  2819. */
  2820. y,
  2821. /**
  2822. * Defines the third coordinates (on Z axis)
  2823. */
  2824. z) {
  2825. if (x === void 0) { x = 0; }
  2826. if (y === void 0) { y = 0; }
  2827. if (z === void 0) { z = 0; }
  2828. this.x = x;
  2829. this.y = y;
  2830. this.z = z;
  2831. }
  2832. /**
  2833. * Creates a string representation of the Vector3
  2834. * @returns a string with the Vector3 coordinates.
  2835. */
  2836. Vector3.prototype.toString = function () {
  2837. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2838. };
  2839. /**
  2840. * Gets the class name
  2841. * @returns the string "Vector3"
  2842. */
  2843. Vector3.prototype.getClassName = function () {
  2844. return "Vector3";
  2845. };
  2846. /**
  2847. * Creates the Vector3 hash code
  2848. * @returns a number which tends to be unique between Vector3 instances
  2849. */
  2850. Vector3.prototype.getHashCode = function () {
  2851. var hash = this.x || 0;
  2852. hash = (hash * 397) ^ (this.y || 0);
  2853. hash = (hash * 397) ^ (this.z || 0);
  2854. return hash;
  2855. };
  2856. // Operators
  2857. /**
  2858. * Creates an array containing three elements : the coordinates of the Vector3
  2859. * @returns a new array of numbers
  2860. */
  2861. Vector3.prototype.asArray = function () {
  2862. var result = [];
  2863. this.toArray(result, 0);
  2864. return result;
  2865. };
  2866. /**
  2867. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2868. * @param array defines the destination array
  2869. * @param index defines the offset in the destination array
  2870. * @returns the current Vector3
  2871. */
  2872. Vector3.prototype.toArray = function (array, index) {
  2873. if (index === void 0) { index = 0; }
  2874. array[index] = this.x;
  2875. array[index + 1] = this.y;
  2876. array[index + 2] = this.z;
  2877. return this;
  2878. };
  2879. /**
  2880. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2881. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2882. */
  2883. Vector3.prototype.toQuaternion = function () {
  2884. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2885. };
  2886. /**
  2887. * Adds the given vector to the current Vector3
  2888. * @param otherVector defines the second operand
  2889. * @returns the current updated Vector3
  2890. */
  2891. Vector3.prototype.addInPlace = function (otherVector) {
  2892. this.x += otherVector.x;
  2893. this.y += otherVector.y;
  2894. this.z += otherVector.z;
  2895. return this;
  2896. };
  2897. /**
  2898. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2899. * @param otherVector defines the second operand
  2900. * @returns the resulting Vector3
  2901. */
  2902. Vector3.prototype.add = function (otherVector) {
  2903. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2904. };
  2905. /**
  2906. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2907. * @param otherVector defines the second operand
  2908. * @param result defines the Vector3 object where to store the result
  2909. * @returns the current Vector3
  2910. */
  2911. Vector3.prototype.addToRef = function (otherVector, result) {
  2912. result.x = this.x + otherVector.x;
  2913. result.y = this.y + otherVector.y;
  2914. result.z = this.z + otherVector.z;
  2915. return this;
  2916. };
  2917. /**
  2918. * Subtract the given vector from the current Vector3
  2919. * @param otherVector defines the second operand
  2920. * @returns the current updated Vector3
  2921. */
  2922. Vector3.prototype.subtractInPlace = function (otherVector) {
  2923. this.x -= otherVector.x;
  2924. this.y -= otherVector.y;
  2925. this.z -= otherVector.z;
  2926. return this;
  2927. };
  2928. /**
  2929. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2930. * @param otherVector defines the second operand
  2931. * @returns the resulting Vector3
  2932. */
  2933. Vector3.prototype.subtract = function (otherVector) {
  2934. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2935. };
  2936. /**
  2937. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2938. * @param otherVector defines the second operand
  2939. * @param result defines the Vector3 object where to store the result
  2940. * @returns the current Vector3
  2941. */
  2942. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2943. result.x = this.x - otherVector.x;
  2944. result.y = this.y - otherVector.y;
  2945. result.z = this.z - otherVector.z;
  2946. return this;
  2947. };
  2948. /**
  2949. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2950. * @param x defines the x coordinate of the operand
  2951. * @param y defines the y coordinate of the operand
  2952. * @param z defines the z coordinate of the operand
  2953. * @returns the resulting Vector3
  2954. */
  2955. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2956. return new Vector3(this.x - x, this.y - y, this.z - z);
  2957. };
  2958. /**
  2959. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2960. * @param x defines the x coordinate of the operand
  2961. * @param y defines the y coordinate of the operand
  2962. * @param z defines the z coordinate of the operand
  2963. * @param result defines the Vector3 object where to store the result
  2964. * @returns the current Vector3
  2965. */
  2966. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2967. result.x = this.x - x;
  2968. result.y = this.y - y;
  2969. result.z = this.z - z;
  2970. return this;
  2971. };
  2972. /**
  2973. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2974. * @returns a new Vector3
  2975. */
  2976. Vector3.prototype.negate = function () {
  2977. return new Vector3(-this.x, -this.y, -this.z);
  2978. };
  2979. /**
  2980. * Multiplies the Vector3 coordinates by the float "scale"
  2981. * @param scale defines the multiplier factor
  2982. * @returns the current updated Vector3
  2983. */
  2984. Vector3.prototype.scaleInPlace = function (scale) {
  2985. this.x *= scale;
  2986. this.y *= scale;
  2987. this.z *= scale;
  2988. return this;
  2989. };
  2990. /**
  2991. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2992. * @param scale defines the multiplier factor
  2993. * @returns a new Vector3
  2994. */
  2995. Vector3.prototype.scale = function (scale) {
  2996. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2997. };
  2998. /**
  2999. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3000. * @param scale defines the multiplier factor
  3001. * @param result defines the Vector3 object where to store the result
  3002. * @returns the current Vector3
  3003. */
  3004. Vector3.prototype.scaleToRef = function (scale, result) {
  3005. result.x = this.x * scale;
  3006. result.y = this.y * scale;
  3007. result.z = this.z * scale;
  3008. return this;
  3009. };
  3010. /**
  3011. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3012. * @param scale defines the scale factor
  3013. * @param result defines the Vector3 object where to store the result
  3014. * @returns the unmodified current Vector3
  3015. */
  3016. Vector3.prototype.scaleAndAddToRef = 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. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3024. * @param otherVector defines the second operand
  3025. * @returns true if both vectors are equals
  3026. */
  3027. Vector3.prototype.equals = function (otherVector) {
  3028. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3029. };
  3030. /**
  3031. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3032. * @param otherVector defines the second operand
  3033. * @param epsilon defines the minimal distance to define values as equals
  3034. * @returns true if both vectors are distant less than epsilon
  3035. */
  3036. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3037. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3038. 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);
  3039. };
  3040. /**
  3041. * Returns true if the current Vector3 coordinates equals the given floats
  3042. * @param x defines the x coordinate of the operand
  3043. * @param y defines the y coordinate of the operand
  3044. * @param z defines the z coordinate of the operand
  3045. * @returns true if both vectors are equals
  3046. */
  3047. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3048. return this.x === x && this.y === y && this.z === z;
  3049. };
  3050. /**
  3051. * Multiplies the current Vector3 coordinates by the given ones
  3052. * @param otherVector defines the second operand
  3053. * @returns the current updated Vector3
  3054. */
  3055. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3056. this.x *= otherVector.x;
  3057. this.y *= otherVector.y;
  3058. this.z *= otherVector.z;
  3059. return this;
  3060. };
  3061. /**
  3062. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3063. * @param otherVector defines the second operand
  3064. * @returns the new Vector3
  3065. */
  3066. Vector3.prototype.multiply = function (otherVector) {
  3067. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3068. };
  3069. /**
  3070. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3071. * @param otherVector defines the second operand
  3072. * @param result defines the Vector3 object where to store the result
  3073. * @returns the current Vector3
  3074. */
  3075. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3076. result.x = this.x * otherVector.x;
  3077. result.y = this.y * otherVector.y;
  3078. result.z = this.z * otherVector.z;
  3079. return this;
  3080. };
  3081. /**
  3082. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3083. * @param x defines the x coordinate of the operand
  3084. * @param y defines the y coordinate of the operand
  3085. * @param z defines the z coordinate of the operand
  3086. * @returns the new Vector3
  3087. */
  3088. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3089. return new Vector3(this.x * x, this.y * y, this.z * z);
  3090. };
  3091. /**
  3092. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3093. * @param otherVector defines the second operand
  3094. * @returns the new Vector3
  3095. */
  3096. Vector3.prototype.divide = function (otherVector) {
  3097. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3098. };
  3099. /**
  3100. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3101. * @param otherVector defines the second operand
  3102. * @param result defines the Vector3 object where to store the result
  3103. * @returns the current Vector3
  3104. */
  3105. Vector3.prototype.divideToRef = function (otherVector, result) {
  3106. result.x = this.x / otherVector.x;
  3107. result.y = this.y / otherVector.y;
  3108. result.z = this.z / otherVector.z;
  3109. return this;
  3110. };
  3111. /**
  3112. * Divides the current Vector3 coordinates by the given ones.
  3113. * @param otherVector defines the second operand
  3114. * @returns the current updated Vector3
  3115. */
  3116. Vector3.prototype.divideInPlace = function (otherVector) {
  3117. return this.divideToRef(otherVector, this);
  3118. };
  3119. /**
  3120. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3121. * @param other defines the second operand
  3122. * @returns the current updated Vector3
  3123. */
  3124. Vector3.prototype.minimizeInPlace = function (other) {
  3125. if (other.x < this.x)
  3126. this.x = other.x;
  3127. if (other.y < this.y)
  3128. this.y = other.y;
  3129. if (other.z < this.z)
  3130. this.z = other.z;
  3131. return this;
  3132. };
  3133. /**
  3134. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3135. * @param other defines the second operand
  3136. * @returns the current updated Vector3
  3137. */
  3138. Vector3.prototype.maximizeInPlace = function (other) {
  3139. if (other.x > this.x)
  3140. this.x = other.x;
  3141. if (other.y > this.y)
  3142. this.y = other.y;
  3143. if (other.z > this.z)
  3144. this.z = other.z;
  3145. return this;
  3146. };
  3147. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3148. /**
  3149. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3150. */
  3151. get: function () {
  3152. var absX = Math.abs(this.x);
  3153. var absY = Math.abs(this.y);
  3154. if (absX !== absY) {
  3155. return true;
  3156. }
  3157. var absZ = Math.abs(this.z);
  3158. if (absX !== absZ) {
  3159. return true;
  3160. }
  3161. if (absY !== absZ) {
  3162. return true;
  3163. }
  3164. return false;
  3165. },
  3166. enumerable: true,
  3167. configurable: true
  3168. });
  3169. /**
  3170. * Gets a new Vector3 from current Vector3 floored values
  3171. * @returns a new Vector3
  3172. */
  3173. Vector3.prototype.floor = function () {
  3174. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3175. };
  3176. /**
  3177. * Gets a new Vector3 from current Vector3 floored values
  3178. * @returns a new Vector3
  3179. */
  3180. Vector3.prototype.fract = function () {
  3181. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3182. };
  3183. // Properties
  3184. /**
  3185. * Gets the length of the Vector3
  3186. * @returns the length of the Vecto3
  3187. */
  3188. Vector3.prototype.length = function () {
  3189. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3190. };
  3191. /**
  3192. * Gets the squared length of the Vector3
  3193. * @returns squared length of the Vector3
  3194. */
  3195. Vector3.prototype.lengthSquared = function () {
  3196. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3197. };
  3198. /**
  3199. * Normalize the current Vector3.
  3200. * Please note that this is an in place operation.
  3201. * @returns the current updated Vector3
  3202. */
  3203. Vector3.prototype.normalize = function () {
  3204. var len = this.length();
  3205. if (len === 0 || len === 1.0)
  3206. return this;
  3207. var num = 1.0 / len;
  3208. this.x *= num;
  3209. this.y *= num;
  3210. this.z *= num;
  3211. return this;
  3212. };
  3213. /**
  3214. * Normalize the current Vector3 to a new vector
  3215. * @returns the new Vector3
  3216. */
  3217. Vector3.prototype.normalizeToNew = function () {
  3218. var normalized = new Vector3(0, 0, 0);
  3219. this.normalizeToRef(normalized);
  3220. return normalized;
  3221. };
  3222. /**
  3223. * Normalize the current Vector3 to the reference
  3224. * @param reference define the Vector3 to update
  3225. * @returns the updated Vector3
  3226. */
  3227. Vector3.prototype.normalizeToRef = function (reference) {
  3228. var len = this.length();
  3229. if (len === 0 || len === 1.0) {
  3230. reference.set(this.x, this.y, this.z);
  3231. return reference;
  3232. }
  3233. var scale = 1.0 / len;
  3234. this.scaleToRef(scale, reference);
  3235. return reference;
  3236. };
  3237. /**
  3238. * Creates a new Vector3 copied from the current Vector3
  3239. * @returns the new Vector3
  3240. */
  3241. Vector3.prototype.clone = function () {
  3242. return new Vector3(this.x, this.y, this.z);
  3243. };
  3244. /**
  3245. * Copies the given vector coordinates to the current Vector3 ones
  3246. * @param source defines the source Vector3
  3247. * @returns the current updated Vector3
  3248. */
  3249. Vector3.prototype.copyFrom = function (source) {
  3250. this.x = source.x;
  3251. this.y = source.y;
  3252. this.z = source.z;
  3253. return this;
  3254. };
  3255. /**
  3256. * Copies the given floats to the current Vector3 coordinates
  3257. * @param x defines the x coordinate of the operand
  3258. * @param y defines the y coordinate of the operand
  3259. * @param z defines the z coordinate of the operand
  3260. * @returns the current updated Vector3
  3261. */
  3262. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3263. this.x = x;
  3264. this.y = y;
  3265. this.z = z;
  3266. return this;
  3267. };
  3268. /**
  3269. * Copies the given floats to the current Vector3 coordinates
  3270. * @param x defines the x coordinate of the operand
  3271. * @param y defines the y coordinate of the operand
  3272. * @param z defines the z coordinate of the operand
  3273. * @returns the current updated Vector3
  3274. */
  3275. Vector3.prototype.set = function (x, y, z) {
  3276. return this.copyFromFloats(x, y, z);
  3277. };
  3278. // Statics
  3279. /**
  3280. * Get the clip factor between two vectors
  3281. * @param vector0 defines the first operand
  3282. * @param vector1 defines the second operand
  3283. * @param axis defines the axis to use
  3284. * @param size defines the size along the axis
  3285. * @returns the clip factor
  3286. */
  3287. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3288. var d0 = Vector3.Dot(vector0, axis) - size;
  3289. var d1 = Vector3.Dot(vector1, axis) - size;
  3290. var s = d0 / (d0 - d1);
  3291. return s;
  3292. };
  3293. /**
  3294. * Get angle between two vectors
  3295. * @param vector0 angle between vector0 and vector1
  3296. * @param vector1 angle between vector0 and vector1
  3297. * @param normal direction of the normal
  3298. * @return the angle between vector0 and vector1
  3299. */
  3300. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3301. var v0 = vector0.clone().normalize();
  3302. var v1 = vector1.clone().normalize();
  3303. var dot = Vector3.Dot(v0, v1);
  3304. var n = Vector3.Cross(v0, v1);
  3305. if (Vector3.Dot(n, normal) > 0) {
  3306. return Math.acos(dot);
  3307. }
  3308. return -Math.acos(dot);
  3309. };
  3310. /**
  3311. * Returns a new Vector3 set from the index "offset" of the given array
  3312. * @param array defines the source array
  3313. * @param offset defines the offset in the source array
  3314. * @returns the new Vector3
  3315. */
  3316. Vector3.FromArray = function (array, offset) {
  3317. if (!offset) {
  3318. offset = 0;
  3319. }
  3320. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3321. };
  3322. /**
  3323. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3324. * This function is deprecated. Use FromArray instead
  3325. * @param array defines the source array
  3326. * @param offset defines the offset in the source array
  3327. * @returns the new Vector3
  3328. */
  3329. Vector3.FromFloatArray = function (array, offset) {
  3330. return Vector3.FromArray(array, offset);
  3331. };
  3332. /**
  3333. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3334. * @param array defines the source array
  3335. * @param offset defines the offset in the source array
  3336. * @param result defines the Vector3 where to store the result
  3337. */
  3338. Vector3.FromArrayToRef = function (array, offset, result) {
  3339. result.x = array[offset];
  3340. result.y = array[offset + 1];
  3341. result.z = array[offset + 2];
  3342. };
  3343. /**
  3344. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3345. * This function is deprecated. Use FromArrayToRef instead.
  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.FromFloatArrayToRef = function (array, offset, result) {
  3351. return Vector3.FromArrayToRef(array, offset, result);
  3352. };
  3353. /**
  3354. * Sets the given vector "result" with the given floats.
  3355. * @param x defines the x coordinate of the source
  3356. * @param y defines the y coordinate of the source
  3357. * @param z defines the z coordinate of the source
  3358. * @param result defines the Vector3 where to store the result
  3359. */
  3360. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3361. result.x = x;
  3362. result.y = y;
  3363. result.z = z;
  3364. };
  3365. /**
  3366. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3367. * @returns a new empty Vector3
  3368. */
  3369. Vector3.Zero = function () {
  3370. return new Vector3(0.0, 0.0, 0.0);
  3371. };
  3372. /**
  3373. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3374. * @returns a new unit Vector3
  3375. */
  3376. Vector3.One = function () {
  3377. return new Vector3(1.0, 1.0, 1.0);
  3378. };
  3379. /**
  3380. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3381. * @returns a new up Vector3
  3382. */
  3383. Vector3.Up = function () {
  3384. return new Vector3(0.0, 1.0, 0.0);
  3385. };
  3386. /**
  3387. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3388. * @returns a new down Vector3
  3389. */
  3390. Vector3.Down = function () {
  3391. return new Vector3(0.0, -1.0, 0.0);
  3392. };
  3393. /**
  3394. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3395. * @returns a new forward Vector3
  3396. */
  3397. Vector3.Forward = function () {
  3398. return new Vector3(0.0, 0.0, 1.0);
  3399. };
  3400. /**
  3401. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3402. * @returns a new right Vector3
  3403. */
  3404. Vector3.Right = function () {
  3405. return new Vector3(1.0, 0.0, 0.0);
  3406. };
  3407. /**
  3408. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3409. * @returns a new left Vector3
  3410. */
  3411. Vector3.Left = function () {
  3412. return new Vector3(-1.0, 0.0, 0.0);
  3413. };
  3414. /**
  3415. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3416. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3417. * @param vector defines the Vector3 to transform
  3418. * @param transformation defines the transformation matrix
  3419. * @returns the transformed Vector3
  3420. */
  3421. Vector3.TransformCoordinates = function (vector, transformation) {
  3422. var result = Vector3.Zero();
  3423. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3424. return result;
  3425. };
  3426. /**
  3427. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3428. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3429. * @param vector defines the Vector3 to transform
  3430. * @param transformation defines the transformation matrix
  3431. * @param result defines the Vector3 where to store the result
  3432. */
  3433. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3434. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3435. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3436. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3437. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3438. result.x = x / w;
  3439. result.y = y / w;
  3440. result.z = z / w;
  3441. };
  3442. /**
  3443. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3444. * This method computes tranformed coordinates only, not transformed direction vectors
  3445. * @param x define the x coordinate of the source vector
  3446. * @param y define the y coordinate of the source vector
  3447. * @param z define the z coordinate of the source vector
  3448. * @param transformation defines the transformation matrix
  3449. * @param result defines the Vector3 where to store the result
  3450. */
  3451. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3452. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3453. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3454. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3455. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3456. result.x = rx / rw;
  3457. result.y = ry / rw;
  3458. result.z = rz / rw;
  3459. };
  3460. /**
  3461. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3462. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3463. * @param vector defines the Vector3 to transform
  3464. * @param transformation defines the transformation matrix
  3465. * @returns the new Vector3
  3466. */
  3467. Vector3.TransformNormal = function (vector, transformation) {
  3468. var result = Vector3.Zero();
  3469. Vector3.TransformNormalToRef(vector, transformation, result);
  3470. return result;
  3471. };
  3472. /**
  3473. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3474. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3475. * @param vector defines the Vector3 to transform
  3476. * @param transformation defines the transformation matrix
  3477. * @param result defines the Vector3 where to store the result
  3478. */
  3479. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3480. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3481. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3482. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3483. result.x = x;
  3484. result.y = y;
  3485. result.z = z;
  3486. };
  3487. /**
  3488. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3489. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3490. * @param x define the x coordinate of the source vector
  3491. * @param y define the y coordinate of the source vector
  3492. * @param z define the z coordinate of the source vector
  3493. * @param transformation defines the transformation matrix
  3494. * @param result defines the Vector3 where to store the result
  3495. */
  3496. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3497. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3498. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3499. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3500. };
  3501. /**
  3502. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3503. * @param value1 defines the first control point
  3504. * @param value2 defines the second control point
  3505. * @param value3 defines the third control point
  3506. * @param value4 defines the fourth control point
  3507. * @param amount defines the amount on the spline to use
  3508. * @returns the new Vector3
  3509. */
  3510. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3511. var squared = amount * amount;
  3512. var cubed = amount * squared;
  3513. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3514. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3515. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3516. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3517. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3518. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3519. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3520. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3521. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3522. return new Vector3(x, y, z);
  3523. };
  3524. /**
  3525. * 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"
  3526. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3527. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3528. * @param value defines the current value
  3529. * @param min defines the lower range value
  3530. * @param max defines the upper range value
  3531. * @returns the new Vector3
  3532. */
  3533. Vector3.Clamp = function (value, min, max) {
  3534. var x = value.x;
  3535. x = (x > max.x) ? max.x : x;
  3536. x = (x < min.x) ? min.x : x;
  3537. var y = value.y;
  3538. y = (y > max.y) ? max.y : y;
  3539. y = (y < min.y) ? min.y : y;
  3540. var z = value.z;
  3541. z = (z > max.z) ? max.z : z;
  3542. z = (z < min.z) ? min.z : z;
  3543. return new Vector3(x, y, z);
  3544. };
  3545. /**
  3546. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3547. * @param value1 defines the first control point
  3548. * @param tangent1 defines the first tangent vector
  3549. * @param value2 defines the second control point
  3550. * @param tangent2 defines the second tangent vector
  3551. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3552. * @returns the new Vector3
  3553. */
  3554. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3555. var squared = amount * amount;
  3556. var cubed = amount * squared;
  3557. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3558. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3559. var part3 = (cubed - (2.0 * squared)) + amount;
  3560. var part4 = cubed - squared;
  3561. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3562. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3563. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3564. return new Vector3(x, y, z);
  3565. };
  3566. /**
  3567. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3568. * @param start defines the start value
  3569. * @param end defines the end value
  3570. * @param amount max defines amount between both (between 0 and 1)
  3571. * @returns the new Vector3
  3572. */
  3573. Vector3.Lerp = function (start, end, amount) {
  3574. var result = new Vector3(0, 0, 0);
  3575. Vector3.LerpToRef(start, end, amount, result);
  3576. return result;
  3577. };
  3578. /**
  3579. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3580. * @param start defines the start value
  3581. * @param end defines the end value
  3582. * @param amount max defines amount between both (between 0 and 1)
  3583. * @param result defines the Vector3 where to store the result
  3584. */
  3585. Vector3.LerpToRef = function (start, end, amount, result) {
  3586. result.x = start.x + ((end.x - start.x) * amount);
  3587. result.y = start.y + ((end.y - start.y) * amount);
  3588. result.z = start.z + ((end.z - start.z) * amount);
  3589. };
  3590. /**
  3591. * Returns the dot product (float) between the vectors "left" and "right"
  3592. * @param left defines the left operand
  3593. * @param right defines the right operand
  3594. * @returns the dot product
  3595. */
  3596. Vector3.Dot = function (left, right) {
  3597. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3598. };
  3599. /**
  3600. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3601. * The cross product is then orthogonal to both "left" and "right"
  3602. * @param left defines the left operand
  3603. * @param right defines the right operand
  3604. * @returns the cross product
  3605. */
  3606. Vector3.Cross = function (left, right) {
  3607. var result = Vector3.Zero();
  3608. Vector3.CrossToRef(left, right, result);
  3609. return result;
  3610. };
  3611. /**
  3612. * Sets the given vector "result" with the cross product of "left" and "right"
  3613. * The cross product is then orthogonal to both "left" and "right"
  3614. * @param left defines the left operand
  3615. * @param right defines the right operand
  3616. * @param result defines the Vector3 where to store the result
  3617. */
  3618. Vector3.CrossToRef = function (left, right, result) {
  3619. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3620. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3621. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3622. result.copyFrom(MathTmp.Vector3[0]);
  3623. };
  3624. /**
  3625. * Returns a new Vector3 as the normalization of the given vector
  3626. * @param vector defines the Vector3 to normalize
  3627. * @returns the new Vector3
  3628. */
  3629. Vector3.Normalize = function (vector) {
  3630. var result = Vector3.Zero();
  3631. Vector3.NormalizeToRef(vector, result);
  3632. return result;
  3633. };
  3634. /**
  3635. * Sets the given vector "result" with the normalization of the given first vector
  3636. * @param vector defines the Vector3 to normalize
  3637. * @param result defines the Vector3 where to store the result
  3638. */
  3639. Vector3.NormalizeToRef = function (vector, result) {
  3640. result.copyFrom(vector);
  3641. result.normalize();
  3642. };
  3643. /**
  3644. * Project a Vector3 onto screen space
  3645. * @param vector defines the Vector3 to project
  3646. * @param world defines the world matrix to use
  3647. * @param transform defines the transform (view x projection) matrix to use
  3648. * @param viewport defines the screen viewport to use
  3649. * @returns the new Vector3
  3650. */
  3651. Vector3.Project = function (vector, world, transform, viewport) {
  3652. var cw = viewport.width;
  3653. var ch = viewport.height;
  3654. var cx = viewport.x;
  3655. var cy = viewport.y;
  3656. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3657. 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);
  3658. var matrix = MathTmp.Matrix[0];
  3659. world.multiplyToRef(transform, matrix);
  3660. matrix.multiplyToRef(viewportMatrix, matrix);
  3661. return Vector3.TransformCoordinates(vector, matrix);
  3662. };
  3663. /**
  3664. * Unproject from screen space to object space
  3665. * @param source defines the screen space Vector3 to use
  3666. * @param viewportWidth defines the current width of the viewport
  3667. * @param viewportHeight defines the current height of the viewport
  3668. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3669. * @param transform defines the transform (view x projection) matrix to use
  3670. * @returns the new Vector3
  3671. */
  3672. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3673. var matrix = MathTmp.Matrix[0];
  3674. world.multiplyToRef(transform, matrix);
  3675. matrix.invert();
  3676. source.x = source.x / viewportWidth * 2 - 1;
  3677. source.y = -(source.y / viewportHeight * 2 - 1);
  3678. var vector = Vector3.TransformCoordinates(source, matrix);
  3679. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3680. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3681. vector = vector.scale(1.0 / num);
  3682. }
  3683. return vector;
  3684. };
  3685. /**
  3686. * Unproject from screen space to object space
  3687. * @param source defines the screen space Vector3 to use
  3688. * @param viewportWidth defines the current width of the viewport
  3689. * @param viewportHeight defines the current height of the viewport
  3690. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3691. * @param view defines the view matrix to use
  3692. * @param projection defines the projection matrix to use
  3693. * @returns the new Vector3
  3694. */
  3695. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3696. var result = Vector3.Zero();
  3697. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3698. return result;
  3699. };
  3700. /**
  3701. * Unproject from screen space to object space
  3702. * @param source defines the screen space Vector3 to use
  3703. * @param viewportWidth defines the current width of the viewport
  3704. * @param viewportHeight defines the current height of the viewport
  3705. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3706. * @param view defines the view matrix to use
  3707. * @param projection defines the projection matrix to use
  3708. * @param result defines the Vector3 where to store the result
  3709. */
  3710. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3711. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3712. };
  3713. /**
  3714. * Unproject from screen space to object space
  3715. * @param sourceX defines the screen space x coordinate to use
  3716. * @param sourceY defines the screen space y coordinate to use
  3717. * @param sourceZ defines the screen space z coordinate to use
  3718. * @param viewportWidth defines the current width of the viewport
  3719. * @param viewportHeight defines the current height of the viewport
  3720. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3721. * @param view defines the view matrix to use
  3722. * @param projection defines the projection matrix to use
  3723. * @param result defines the Vector3 where to store the result
  3724. */
  3725. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3726. var matrix = MathTmp.Matrix[0];
  3727. world.multiplyToRef(view, matrix);
  3728. matrix.multiplyToRef(projection, matrix);
  3729. matrix.invert();
  3730. var screenSource = MathTmp.Vector3[0];
  3731. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3732. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3733. screenSource.z = 2 * sourceZ - 1.0;
  3734. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3735. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3736. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3737. result.scaleInPlace(1.0 / num);
  3738. }
  3739. };
  3740. /**
  3741. * Gets the minimal coordinate values between two Vector3
  3742. * @param left defines the first operand
  3743. * @param right defines the second operand
  3744. * @returns the new Vector3
  3745. */
  3746. Vector3.Minimize = function (left, right) {
  3747. var min = left.clone();
  3748. min.minimizeInPlace(right);
  3749. return min;
  3750. };
  3751. /**
  3752. * Gets the maximal coordinate values between two Vector3
  3753. * @param left defines the first operand
  3754. * @param right defines the second operand
  3755. * @returns the new Vector3
  3756. */
  3757. Vector3.Maximize = function (left, right) {
  3758. var max = left.clone();
  3759. max.maximizeInPlace(right);
  3760. return max;
  3761. };
  3762. /**
  3763. * Returns the distance between the vectors "value1" and "value2"
  3764. * @param value1 defines the first operand
  3765. * @param value2 defines the second operand
  3766. * @returns the distance
  3767. */
  3768. Vector3.Distance = function (value1, value2) {
  3769. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3770. };
  3771. /**
  3772. * Returns the squared distance between the vectors "value1" and "value2"
  3773. * @param value1 defines the first operand
  3774. * @param value2 defines the second operand
  3775. * @returns the squared distance
  3776. */
  3777. Vector3.DistanceSquared = function (value1, value2) {
  3778. var x = value1.x - value2.x;
  3779. var y = value1.y - value2.y;
  3780. var z = value1.z - value2.z;
  3781. return (x * x) + (y * y) + (z * z);
  3782. };
  3783. /**
  3784. * Returns a new Vector3 located at the center between "value1" and "value2"
  3785. * @param value1 defines the first operand
  3786. * @param value2 defines the second operand
  3787. * @returns the new Vector3
  3788. */
  3789. Vector3.Center = function (value1, value2) {
  3790. var center = value1.add(value2);
  3791. center.scaleInPlace(0.5);
  3792. return center;
  3793. };
  3794. /**
  3795. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3796. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3797. * to something in order to rotate it from its local system to the given target system
  3798. * Note: axis1, axis2 and axis3 are normalized during this operation
  3799. * @param axis1 defines the first axis
  3800. * @param axis2 defines the second axis
  3801. * @param axis3 defines the third axis
  3802. * @returns a new Vector3
  3803. */
  3804. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3805. var rotation = Vector3.Zero();
  3806. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3807. return rotation;
  3808. };
  3809. /**
  3810. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3811. * @param axis1 defines the first axis
  3812. * @param axis2 defines the second axis
  3813. * @param axis3 defines the third axis
  3814. * @param ref defines the Vector3 where to store the result
  3815. */
  3816. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3817. var quat = MathTmp.Quaternion[0];
  3818. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3819. quat.toEulerAnglesToRef(ref);
  3820. };
  3821. return Vector3;
  3822. }());
  3823. BABYLON.Vector3 = Vector3;
  3824. //Vector4 class created for EulerAngle class conversion to Quaternion
  3825. var Vector4 = /** @class */ (function () {
  3826. /**
  3827. * Creates a Vector4 object from the given floats.
  3828. */
  3829. function Vector4(x, y, z, w) {
  3830. this.x = x;
  3831. this.y = y;
  3832. this.z = z;
  3833. this.w = w;
  3834. }
  3835. /**
  3836. * Returns the string with the Vector4 coordinates.
  3837. */
  3838. Vector4.prototype.toString = function () {
  3839. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3840. };
  3841. /**
  3842. * Returns the string "Vector4".
  3843. */
  3844. Vector4.prototype.getClassName = function () {
  3845. return "Vector4";
  3846. };
  3847. /**
  3848. * Returns the Vector4 hash code.
  3849. */
  3850. Vector4.prototype.getHashCode = function () {
  3851. var hash = this.x || 0;
  3852. hash = (hash * 397) ^ (this.y || 0);
  3853. hash = (hash * 397) ^ (this.z || 0);
  3854. hash = (hash * 397) ^ (this.w || 0);
  3855. return hash;
  3856. };
  3857. // Operators
  3858. /**
  3859. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3860. */
  3861. Vector4.prototype.asArray = function () {
  3862. var result = new Array();
  3863. this.toArray(result, 0);
  3864. return result;
  3865. };
  3866. /**
  3867. * Populates the given array from the given index with the Vector4 coordinates.
  3868. * Returns the Vector4.
  3869. */
  3870. Vector4.prototype.toArray = function (array, index) {
  3871. if (index === undefined) {
  3872. index = 0;
  3873. }
  3874. array[index] = this.x;
  3875. array[index + 1] = this.y;
  3876. array[index + 2] = this.z;
  3877. array[index + 3] = this.w;
  3878. return this;
  3879. };
  3880. /**
  3881. * Adds the given vector to the current Vector4.
  3882. * Returns the updated Vector4.
  3883. */
  3884. Vector4.prototype.addInPlace = function (otherVector) {
  3885. this.x += otherVector.x;
  3886. this.y += otherVector.y;
  3887. this.z += otherVector.z;
  3888. this.w += otherVector.w;
  3889. return this;
  3890. };
  3891. /**
  3892. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3893. */
  3894. Vector4.prototype.add = function (otherVector) {
  3895. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3896. };
  3897. /**
  3898. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3899. * Returns the current Vector4.
  3900. */
  3901. Vector4.prototype.addToRef = function (otherVector, result) {
  3902. result.x = this.x + otherVector.x;
  3903. result.y = this.y + otherVector.y;
  3904. result.z = this.z + otherVector.z;
  3905. result.w = this.w + otherVector.w;
  3906. return this;
  3907. };
  3908. /**
  3909. * Subtract in place the given vector from the current Vector4.
  3910. * Returns the updated Vector4.
  3911. */
  3912. Vector4.prototype.subtractInPlace = function (otherVector) {
  3913. this.x -= otherVector.x;
  3914. this.y -= otherVector.y;
  3915. this.z -= otherVector.z;
  3916. this.w -= otherVector.w;
  3917. return this;
  3918. };
  3919. /**
  3920. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3921. */
  3922. Vector4.prototype.subtract = function (otherVector) {
  3923. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3924. };
  3925. /**
  3926. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3927. * Returns the current Vector4.
  3928. */
  3929. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3930. result.x = this.x - otherVector.x;
  3931. result.y = this.y - otherVector.y;
  3932. result.z = this.z - otherVector.z;
  3933. result.w = this.w - otherVector.w;
  3934. return this;
  3935. };
  3936. /**
  3937. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3938. */
  3939. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3940. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3941. };
  3942. /**
  3943. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3944. * Returns the current Vector4.
  3945. */
  3946. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3947. result.x = this.x - x;
  3948. result.y = this.y - y;
  3949. result.z = this.z - z;
  3950. result.w = this.w - w;
  3951. return this;
  3952. };
  3953. /**
  3954. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3955. */
  3956. Vector4.prototype.negate = function () {
  3957. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3958. };
  3959. /**
  3960. * Multiplies the current Vector4 coordinates by scale (float).
  3961. * Returns the updated Vector4.
  3962. */
  3963. Vector4.prototype.scaleInPlace = function (scale) {
  3964. this.x *= scale;
  3965. this.y *= scale;
  3966. this.z *= scale;
  3967. this.w *= scale;
  3968. return this;
  3969. };
  3970. /**
  3971. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3972. */
  3973. Vector4.prototype.scale = function (scale) {
  3974. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3975. };
  3976. /**
  3977. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3978. * Returns the current Vector4.
  3979. */
  3980. Vector4.prototype.scaleToRef = function (scale, result) {
  3981. result.x = this.x * scale;
  3982. result.y = this.y * scale;
  3983. result.z = this.z * scale;
  3984. result.w = this.w * scale;
  3985. return this;
  3986. };
  3987. /**
  3988. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3989. * @param scale defines the scale factor
  3990. * @param result defines the Vector4 object where to store the result
  3991. * @returns the unmodified current Vector4
  3992. */
  3993. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3994. result.x += this.x * scale;
  3995. result.y += this.y * scale;
  3996. result.z += this.z * scale;
  3997. result.w += this.w * scale;
  3998. return this;
  3999. };
  4000. /**
  4001. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4002. */
  4003. Vector4.prototype.equals = function (otherVector) {
  4004. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4005. };
  4006. /**
  4007. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4008. */
  4009. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4010. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4011. return otherVector
  4012. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4013. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4014. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4015. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4016. };
  4017. /**
  4018. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4019. */
  4020. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4021. return this.x === x && this.y === y && this.z === z && this.w === w;
  4022. };
  4023. /**
  4024. * Multiplies in place the current Vector4 by the given one.
  4025. * Returns the updated Vector4.
  4026. */
  4027. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4028. this.x *= otherVector.x;
  4029. this.y *= otherVector.y;
  4030. this.z *= otherVector.z;
  4031. this.w *= otherVector.w;
  4032. return this;
  4033. };
  4034. /**
  4035. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4036. */
  4037. Vector4.prototype.multiply = function (otherVector) {
  4038. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4039. };
  4040. /**
  4041. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4042. * Returns the current Vector4.
  4043. */
  4044. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4045. result.x = this.x * otherVector.x;
  4046. result.y = this.y * otherVector.y;
  4047. result.z = this.z * otherVector.z;
  4048. result.w = this.w * otherVector.w;
  4049. return this;
  4050. };
  4051. /**
  4052. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4053. */
  4054. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4055. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4056. };
  4057. /**
  4058. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4059. */
  4060. Vector4.prototype.divide = function (otherVector) {
  4061. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4062. };
  4063. /**
  4064. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4065. * Returns the current Vector4.
  4066. */
  4067. Vector4.prototype.divideToRef = function (otherVector, result) {
  4068. result.x = this.x / otherVector.x;
  4069. result.y = this.y / otherVector.y;
  4070. result.z = this.z / otherVector.z;
  4071. result.w = this.w / otherVector.w;
  4072. return this;
  4073. };
  4074. /**
  4075. * Divides the current Vector3 coordinates by the given ones.
  4076. * @returns the updated Vector3.
  4077. */
  4078. Vector4.prototype.divideInPlace = function (otherVector) {
  4079. return this.divideToRef(otherVector, this);
  4080. };
  4081. /**
  4082. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4083. * @param other defines the second operand
  4084. * @returns the current updated Vector4
  4085. */
  4086. Vector4.prototype.minimizeInPlace = function (other) {
  4087. if (other.x < this.x)
  4088. this.x = other.x;
  4089. if (other.y < this.y)
  4090. this.y = other.y;
  4091. if (other.z < this.z)
  4092. this.z = other.z;
  4093. if (other.w < this.w)
  4094. this.w = other.w;
  4095. return this;
  4096. };
  4097. /**
  4098. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4099. * @param other defines the second operand
  4100. * @returns the current updated Vector4
  4101. */
  4102. Vector4.prototype.maximizeInPlace = function (other) {
  4103. if (other.x > this.x)
  4104. this.x = other.x;
  4105. if (other.y > this.y)
  4106. this.y = other.y;
  4107. if (other.z > this.z)
  4108. this.z = other.z;
  4109. if (other.w > this.w)
  4110. this.w = other.w;
  4111. return this;
  4112. };
  4113. /**
  4114. * Gets a new Vector4 from current Vector4 floored values
  4115. * @returns a new Vector4
  4116. */
  4117. Vector4.prototype.floor = function () {
  4118. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4119. };
  4120. /**
  4121. * Gets a new Vector4 from current Vector3 floored values
  4122. * @returns a new Vector4
  4123. */
  4124. Vector4.prototype.fract = function () {
  4125. 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));
  4126. };
  4127. // Properties
  4128. /**
  4129. * Returns the Vector4 length (float).
  4130. */
  4131. Vector4.prototype.length = function () {
  4132. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4133. };
  4134. /**
  4135. * Returns the Vector4 squared length (float).
  4136. */
  4137. Vector4.prototype.lengthSquared = function () {
  4138. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4139. };
  4140. // Methods
  4141. /**
  4142. * Normalizes in place the Vector4.
  4143. * Returns the updated Vector4.
  4144. */
  4145. Vector4.prototype.normalize = function () {
  4146. var len = this.length();
  4147. if (len === 0)
  4148. return this;
  4149. var num = 1.0 / len;
  4150. this.x *= num;
  4151. this.y *= num;
  4152. this.z *= num;
  4153. this.w *= num;
  4154. return this;
  4155. };
  4156. /**
  4157. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4158. */
  4159. Vector4.prototype.toVector3 = function () {
  4160. return new Vector3(this.x, this.y, this.z);
  4161. };
  4162. /**
  4163. * Returns a new Vector4 copied from the current one.
  4164. */
  4165. Vector4.prototype.clone = function () {
  4166. return new Vector4(this.x, this.y, this.z, this.w);
  4167. };
  4168. /**
  4169. * Updates the current Vector4 with the given one coordinates.
  4170. * Returns the updated Vector4.
  4171. */
  4172. Vector4.prototype.copyFrom = function (source) {
  4173. this.x = source.x;
  4174. this.y = source.y;
  4175. this.z = source.z;
  4176. this.w = source.w;
  4177. return this;
  4178. };
  4179. /**
  4180. * Updates the current Vector4 coordinates with the given floats.
  4181. * Returns the updated Vector4.
  4182. */
  4183. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4184. this.x = x;
  4185. this.y = y;
  4186. this.z = z;
  4187. this.w = w;
  4188. return this;
  4189. };
  4190. /**
  4191. * Updates the current Vector4 coordinates with the given floats.
  4192. * Returns the updated Vector4.
  4193. */
  4194. Vector4.prototype.set = function (x, y, z, w) {
  4195. return this.copyFromFloats(x, y, z, w);
  4196. };
  4197. // Statics
  4198. /**
  4199. * Returns a new Vector4 set from the starting index of the given array.
  4200. */
  4201. Vector4.FromArray = function (array, offset) {
  4202. if (!offset) {
  4203. offset = 0;
  4204. }
  4205. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4206. };
  4207. /**
  4208. * Updates the given vector "result" from the starting index of the given array.
  4209. */
  4210. Vector4.FromArrayToRef = function (array, offset, result) {
  4211. result.x = array[offset];
  4212. result.y = array[offset + 1];
  4213. result.z = array[offset + 2];
  4214. result.w = array[offset + 3];
  4215. };
  4216. /**
  4217. * Updates the given vector "result" from the starting index of the given Float32Array.
  4218. */
  4219. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4220. Vector4.FromArrayToRef(array, offset, result);
  4221. };
  4222. /**
  4223. * Updates the given vector "result" coordinates from the given floats.
  4224. */
  4225. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4226. result.x = x;
  4227. result.y = y;
  4228. result.z = z;
  4229. result.w = w;
  4230. };
  4231. /**
  4232. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4233. */
  4234. Vector4.Zero = function () {
  4235. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4236. };
  4237. /**
  4238. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4239. */
  4240. Vector4.One = function () {
  4241. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4242. };
  4243. /**
  4244. * Returns a new normalized Vector4 from the given one.
  4245. */
  4246. Vector4.Normalize = function (vector) {
  4247. var result = Vector4.Zero();
  4248. Vector4.NormalizeToRef(vector, result);
  4249. return result;
  4250. };
  4251. /**
  4252. * Updates the given vector "result" from the normalization of the given one.
  4253. */
  4254. Vector4.NormalizeToRef = function (vector, result) {
  4255. result.copyFrom(vector);
  4256. result.normalize();
  4257. };
  4258. Vector4.Minimize = function (left, right) {
  4259. var min = left.clone();
  4260. min.minimizeInPlace(right);
  4261. return min;
  4262. };
  4263. Vector4.Maximize = function (left, right) {
  4264. var max = left.clone();
  4265. max.maximizeInPlace(right);
  4266. return max;
  4267. };
  4268. /**
  4269. * Returns the distance (float) between the vectors "value1" and "value2".
  4270. */
  4271. Vector4.Distance = function (value1, value2) {
  4272. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4273. };
  4274. /**
  4275. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4276. */
  4277. Vector4.DistanceSquared = function (value1, value2) {
  4278. var x = value1.x - value2.x;
  4279. var y = value1.y - value2.y;
  4280. var z = value1.z - value2.z;
  4281. var w = value1.w - value2.w;
  4282. return (x * x) + (y * y) + (z * z) + (w * w);
  4283. };
  4284. /**
  4285. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4286. */
  4287. Vector4.Center = function (value1, value2) {
  4288. var center = value1.add(value2);
  4289. center.scaleInPlace(0.5);
  4290. return center;
  4291. };
  4292. /**
  4293. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4294. * This methods computes transformed normalized direction vectors only.
  4295. */
  4296. Vector4.TransformNormal = function (vector, transformation) {
  4297. var result = Vector4.Zero();
  4298. Vector4.TransformNormalToRef(vector, transformation, result);
  4299. return result;
  4300. };
  4301. /**
  4302. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4303. * This methods computes transformed normalized direction vectors only.
  4304. */
  4305. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4306. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4307. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4308. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4309. result.x = x;
  4310. result.y = y;
  4311. result.z = z;
  4312. result.w = vector.w;
  4313. };
  4314. /**
  4315. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4316. * This methods computes transformed normalized direction vectors only.
  4317. */
  4318. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4319. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4320. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4321. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4322. result.w = w;
  4323. };
  4324. return Vector4;
  4325. }());
  4326. BABYLON.Vector4 = Vector4;
  4327. var Size = /** @class */ (function () {
  4328. /**
  4329. * Creates a Size object from the given width and height (floats).
  4330. */
  4331. function Size(width, height) {
  4332. this.width = width;
  4333. this.height = height;
  4334. }
  4335. // Returns a string with the Size width and height.
  4336. Size.prototype.toString = function () {
  4337. return "{W: " + this.width + ", H: " + this.height + "}";
  4338. };
  4339. /**
  4340. * Returns the string "Size"
  4341. */
  4342. Size.prototype.getClassName = function () {
  4343. return "Size";
  4344. };
  4345. /**
  4346. * Returns the Size hash code.
  4347. */
  4348. Size.prototype.getHashCode = function () {
  4349. var hash = this.width || 0;
  4350. hash = (hash * 397) ^ (this.height || 0);
  4351. return hash;
  4352. };
  4353. /**
  4354. * Updates the current size from the given one.
  4355. * Returns the updated Size.
  4356. */
  4357. Size.prototype.copyFrom = function (src) {
  4358. this.width = src.width;
  4359. this.height = src.height;
  4360. };
  4361. /**
  4362. * Updates in place the current Size from the given floats.
  4363. * Returns the updated Size.
  4364. */
  4365. Size.prototype.copyFromFloats = function (width, height) {
  4366. this.width = width;
  4367. this.height = height;
  4368. return this;
  4369. };
  4370. /**
  4371. * Updates in place the current Size from the given floats.
  4372. * Returns the updated Size.
  4373. */
  4374. Size.prototype.set = function (width, height) {
  4375. return this.copyFromFloats(width, height);
  4376. };
  4377. /**
  4378. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4379. */
  4380. Size.prototype.multiplyByFloats = function (w, h) {
  4381. return new Size(this.width * w, this.height * h);
  4382. };
  4383. /**
  4384. * Returns a new Size copied from the given one.
  4385. */
  4386. Size.prototype.clone = function () {
  4387. return new Size(this.width, this.height);
  4388. };
  4389. /**
  4390. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4391. */
  4392. Size.prototype.equals = function (other) {
  4393. if (!other) {
  4394. return false;
  4395. }
  4396. return (this.width === other.width) && (this.height === other.height);
  4397. };
  4398. Object.defineProperty(Size.prototype, "surface", {
  4399. /**
  4400. * Returns the surface of the Size : width * height (float).
  4401. */
  4402. get: function () {
  4403. return this.width * this.height;
  4404. },
  4405. enumerable: true,
  4406. configurable: true
  4407. });
  4408. /**
  4409. * Returns a new Size set to (0.0, 0.0)
  4410. */
  4411. Size.Zero = function () {
  4412. return new Size(0.0, 0.0);
  4413. };
  4414. /**
  4415. * Returns a new Size set as the addition result of the current Size and the given one.
  4416. */
  4417. Size.prototype.add = function (otherSize) {
  4418. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4419. return r;
  4420. };
  4421. /**
  4422. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4423. */
  4424. Size.prototype.subtract = function (otherSize) {
  4425. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4426. return r;
  4427. };
  4428. /**
  4429. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4430. */
  4431. Size.Lerp = function (start, end, amount) {
  4432. var w = start.width + ((end.width - start.width) * amount);
  4433. var h = start.height + ((end.height - start.height) * amount);
  4434. return new Size(w, h);
  4435. };
  4436. return Size;
  4437. }());
  4438. BABYLON.Size = Size;
  4439. /**
  4440. * Class used to store quaternion data
  4441. * @see https://en.wikipedia.org/wiki/Quaternion
  4442. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4443. */
  4444. var Quaternion = /** @class */ (function () {
  4445. /**
  4446. * Creates a new Quaternion from the given floats
  4447. * @param x defines the first component (0 by default)
  4448. * @param y defines the second component (0 by default)
  4449. * @param z defines the third component (0 by default)
  4450. * @param w defines the fourth component (1.0 by default)
  4451. */
  4452. function Quaternion(
  4453. /** defines the first component (0 by default) */
  4454. x,
  4455. /** defines the second component (0 by default) */
  4456. y,
  4457. /** defines the third component (0 by default) */
  4458. z,
  4459. /** defines the fourth component (1.0 by default) */
  4460. w) {
  4461. if (x === void 0) { x = 0.0; }
  4462. if (y === void 0) { y = 0.0; }
  4463. if (z === void 0) { z = 0.0; }
  4464. if (w === void 0) { w = 1.0; }
  4465. this.x = x;
  4466. this.y = y;
  4467. this.z = z;
  4468. this.w = w;
  4469. }
  4470. /**
  4471. * Gets a string representation for the current quaternion
  4472. * @returns a string with the Quaternion coordinates
  4473. */
  4474. Quaternion.prototype.toString = function () {
  4475. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4476. };
  4477. /**
  4478. * Gets the class name of the quaternion
  4479. * @returns the string "Quaternion"
  4480. */
  4481. Quaternion.prototype.getClassName = function () {
  4482. return "Quaternion";
  4483. };
  4484. /**
  4485. * Gets a hash code for this quaternion
  4486. * @returns the quaternion hash code
  4487. */
  4488. Quaternion.prototype.getHashCode = function () {
  4489. var hash = this.x || 0;
  4490. hash = (hash * 397) ^ (this.y || 0);
  4491. hash = (hash * 397) ^ (this.z || 0);
  4492. hash = (hash * 397) ^ (this.w || 0);
  4493. return hash;
  4494. };
  4495. /**
  4496. * Copy the quaternion to an array
  4497. * @returns a new array populated with 4 elements from the quaternion coordinates
  4498. */
  4499. Quaternion.prototype.asArray = function () {
  4500. return [this.x, this.y, this.z, this.w];
  4501. };
  4502. /**
  4503. * Check if two quaternions are equals
  4504. * @param otherQuaternion defines the second operand
  4505. * @return true if the current quaternion and the given one coordinates are strictly equals
  4506. */
  4507. Quaternion.prototype.equals = function (otherQuaternion) {
  4508. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4509. };
  4510. /**
  4511. * Clone the current quaternion
  4512. * @returns a new quaternion copied from the current one
  4513. */
  4514. Quaternion.prototype.clone = function () {
  4515. return new Quaternion(this.x, this.y, this.z, this.w);
  4516. };
  4517. /**
  4518. * Copy a quaternion to the current one
  4519. * @param other defines the other quaternion
  4520. * @returns the updated current quaternion
  4521. */
  4522. Quaternion.prototype.copyFrom = function (other) {
  4523. this.x = other.x;
  4524. this.y = other.y;
  4525. this.z = other.z;
  4526. this.w = other.w;
  4527. return this;
  4528. };
  4529. /**
  4530. * Updates the current quaternion with the given float coordinates
  4531. * @param x defines the x coordinate
  4532. * @param y defines the y coordinate
  4533. * @param z defines the z coordinate
  4534. * @param w defines the w coordinate
  4535. * @returns the updated current quaternion
  4536. */
  4537. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4538. this.x = x;
  4539. this.y = y;
  4540. this.z = z;
  4541. this.w = w;
  4542. return this;
  4543. };
  4544. /**
  4545. * Updates the current quaternion from the given float coordinates
  4546. * @param x defines the x coordinate
  4547. * @param y defines the y coordinate
  4548. * @param z defines the z coordinate
  4549. * @param w defines the w coordinate
  4550. * @returns the updated current quaternion
  4551. */
  4552. Quaternion.prototype.set = function (x, y, z, w) {
  4553. return this.copyFromFloats(x, y, z, w);
  4554. };
  4555. /**
  4556. * Adds two quaternions
  4557. * @param other defines the second operand
  4558. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4559. */
  4560. Quaternion.prototype.add = function (other) {
  4561. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4562. };
  4563. /**
  4564. * Add a quaternion to the current one
  4565. * @param other defines the quaternion to add
  4566. * @returns the current quaternion
  4567. */
  4568. Quaternion.prototype.addInPlace = function (other) {
  4569. this.x += other.x;
  4570. this.y += other.y;
  4571. this.z += other.z;
  4572. this.w += other.w;
  4573. return this;
  4574. };
  4575. /**
  4576. * Subtract two quaternions
  4577. * @param other defines the second operand
  4578. * @returns a new quaternion as the subtraction result of the given one from the current one
  4579. */
  4580. Quaternion.prototype.subtract = function (other) {
  4581. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4582. };
  4583. /**
  4584. * Multiplies the current quaternion by a scale factor
  4585. * @param value defines the scale factor
  4586. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4587. */
  4588. Quaternion.prototype.scale = function (value) {
  4589. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4590. };
  4591. /**
  4592. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4593. * @param scale defines the scale factor
  4594. * @param result defines the Quaternion object where to store the result
  4595. * @returns the unmodified current quaternion
  4596. */
  4597. Quaternion.prototype.scaleToRef = function (scale, result) {
  4598. result.x = this.x * scale;
  4599. result.y = this.y * scale;
  4600. result.z = this.z * scale;
  4601. result.w = this.w * scale;
  4602. return this;
  4603. };
  4604. /**
  4605. * Multiplies in place the current quaternion by a scale factor
  4606. * @param value defines the scale factor
  4607. * @returns the current modified quaternion
  4608. */
  4609. Quaternion.prototype.scaleInPlace = function (value) {
  4610. this.x *= value;
  4611. this.y *= value;
  4612. this.z *= value;
  4613. this.w *= value;
  4614. return this;
  4615. };
  4616. /**
  4617. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4618. * @param scale defines the scale factor
  4619. * @param result defines the Quaternion object where to store the result
  4620. * @returns the unmodified current quaternion
  4621. */
  4622. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4623. result.x += this.x * scale;
  4624. result.y += this.y * scale;
  4625. result.z += this.z * scale;
  4626. result.w += this.w * scale;
  4627. return this;
  4628. };
  4629. /**
  4630. * Multiplies two quaternions
  4631. * @param q1 defines the second operand
  4632. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4633. */
  4634. Quaternion.prototype.multiply = function (q1) {
  4635. var result = new Quaternion(0, 0, 0, 1.0);
  4636. this.multiplyToRef(q1, result);
  4637. return result;
  4638. };
  4639. /**
  4640. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4641. * @param q1 defines the second operand
  4642. * @param result defines the target quaternion
  4643. * @returns the current quaternion
  4644. */
  4645. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4646. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4647. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4648. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4649. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4650. result.copyFromFloats(x, y, z, w);
  4651. return this;
  4652. };
  4653. /**
  4654. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4655. * @param q1 defines the second operand
  4656. * @returns the currentupdated quaternion
  4657. */
  4658. Quaternion.prototype.multiplyInPlace = function (q1) {
  4659. this.multiplyToRef(q1, this);
  4660. return this;
  4661. };
  4662. /**
  4663. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4664. * @param ref defines the target quaternion
  4665. * @returns the current quaternion
  4666. */
  4667. Quaternion.prototype.conjugateToRef = function (ref) {
  4668. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4669. return this;
  4670. };
  4671. /**
  4672. * Conjugates in place (1-q) the current quaternion
  4673. * @returns the current updated quaternion
  4674. */
  4675. Quaternion.prototype.conjugateInPlace = function () {
  4676. this.x *= -1;
  4677. this.y *= -1;
  4678. this.z *= -1;
  4679. return this;
  4680. };
  4681. /**
  4682. * Conjugates in place (1-q) the current quaternion
  4683. * @returns a new quaternion
  4684. */
  4685. Quaternion.prototype.conjugate = function () {
  4686. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4687. return result;
  4688. };
  4689. /**
  4690. * Gets length of current quaternion
  4691. * @returns the quaternion length (float)
  4692. */
  4693. Quaternion.prototype.length = function () {
  4694. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4695. };
  4696. /**
  4697. * Normalize in place the current quaternion
  4698. * @returns the current updated quaternion
  4699. */
  4700. Quaternion.prototype.normalize = function () {
  4701. var length = 1.0 / this.length();
  4702. this.x *= length;
  4703. this.y *= length;
  4704. this.z *= length;
  4705. this.w *= length;
  4706. return this;
  4707. };
  4708. /**
  4709. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4710. * @param order is a reserved parameter and is ignore for now
  4711. * @returns a new Vector3 containing the Euler angles
  4712. */
  4713. Quaternion.prototype.toEulerAngles = function (order) {
  4714. if (order === void 0) { order = "YZX"; }
  4715. var result = Vector3.Zero();
  4716. this.toEulerAnglesToRef(result, order);
  4717. return result;
  4718. };
  4719. /**
  4720. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4721. * @param result defines the vector which will be filled with the Euler angles
  4722. * @param order is a reserved parameter and is ignore for now
  4723. * @returns the current unchanged quaternion
  4724. */
  4725. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4726. if (order === void 0) { order = "YZX"; }
  4727. var qz = this.z;
  4728. var qx = this.x;
  4729. var qy = this.y;
  4730. var qw = this.w;
  4731. var sqw = qw * qw;
  4732. var sqz = qz * qz;
  4733. var sqx = qx * qx;
  4734. var sqy = qy * qy;
  4735. var zAxisY = qy * qz - qx * qw;
  4736. var limit = .4999999;
  4737. if (zAxisY < -limit) {
  4738. result.y = 2 * Math.atan2(qy, qw);
  4739. result.x = Math.PI / 2;
  4740. result.z = 0;
  4741. }
  4742. else if (zAxisY > limit) {
  4743. result.y = 2 * Math.atan2(qy, qw);
  4744. result.x = -Math.PI / 2;
  4745. result.z = 0;
  4746. }
  4747. else {
  4748. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4749. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4750. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4751. }
  4752. return this;
  4753. };
  4754. /**
  4755. * Updates the given rotation matrix with the current quaternion values
  4756. * @param result defines the target matrix
  4757. * @returns the current unchanged quaternion
  4758. */
  4759. Quaternion.prototype.toRotationMatrix = function (result) {
  4760. var xx = this.x * this.x;
  4761. var yy = this.y * this.y;
  4762. var zz = this.z * this.z;
  4763. var xy = this.x * this.y;
  4764. var zw = this.z * this.w;
  4765. var zx = this.z * this.x;
  4766. var yw = this.y * this.w;
  4767. var yz = this.y * this.z;
  4768. var xw = this.x * this.w;
  4769. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4770. result.m[1] = 2.0 * (xy + zw);
  4771. result.m[2] = 2.0 * (zx - yw);
  4772. result.m[3] = 0;
  4773. result.m[4] = 2.0 * (xy - zw);
  4774. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4775. result.m[6] = 2.0 * (yz + xw);
  4776. result.m[7] = 0;
  4777. result.m[8] = 2.0 * (zx + yw);
  4778. result.m[9] = 2.0 * (yz - xw);
  4779. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4780. result.m[11] = 0;
  4781. result.m[12] = 0;
  4782. result.m[13] = 0;
  4783. result.m[14] = 0;
  4784. result.m[15] = 1.0;
  4785. result._markAsUpdated();
  4786. return this;
  4787. };
  4788. /**
  4789. * Updates the current quaternion from the given rotation matrix values
  4790. * @param matrix defines the source matrix
  4791. * @returns the current updated quaternion
  4792. */
  4793. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4794. Quaternion.FromRotationMatrixToRef(matrix, this);
  4795. return this;
  4796. };
  4797. // Statics
  4798. /**
  4799. * Creates a new quaternion from a rotation matrix
  4800. * @param matrix defines the source matrix
  4801. * @returns a new quaternion created from the given rotation matrix values
  4802. */
  4803. Quaternion.FromRotationMatrix = function (matrix) {
  4804. var result = new Quaternion();
  4805. Quaternion.FromRotationMatrixToRef(matrix, result);
  4806. return result;
  4807. };
  4808. /**
  4809. * Updates the given quaternion with the given rotation matrix values
  4810. * @param matrix defines the source matrix
  4811. * @param result defines the target quaternion
  4812. */
  4813. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4814. var data = matrix.m;
  4815. var m11 = data[0], m12 = data[4], m13 = data[8];
  4816. var m21 = data[1], m22 = data[5], m23 = data[9];
  4817. var m31 = data[2], m32 = data[6], m33 = data[10];
  4818. var trace = m11 + m22 + m33;
  4819. var s;
  4820. if (trace > 0) {
  4821. s = 0.5 / Math.sqrt(trace + 1.0);
  4822. result.w = 0.25 / s;
  4823. result.x = (m32 - m23) * s;
  4824. result.y = (m13 - m31) * s;
  4825. result.z = (m21 - m12) * s;
  4826. }
  4827. else if (m11 > m22 && m11 > m33) {
  4828. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4829. result.w = (m32 - m23) / s;
  4830. result.x = 0.25 * s;
  4831. result.y = (m12 + m21) / s;
  4832. result.z = (m13 + m31) / s;
  4833. }
  4834. else if (m22 > m33) {
  4835. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4836. result.w = (m13 - m31) / s;
  4837. result.x = (m12 + m21) / s;
  4838. result.y = 0.25 * s;
  4839. result.z = (m23 + m32) / s;
  4840. }
  4841. else {
  4842. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4843. result.w = (m21 - m12) / s;
  4844. result.x = (m13 + m31) / s;
  4845. result.y = (m23 + m32) / s;
  4846. result.z = 0.25 * s;
  4847. }
  4848. };
  4849. /**
  4850. * Returns the dot product (float) between the quaternions "left" and "right"
  4851. * @param left defines the left operand
  4852. * @param right defines the right operand
  4853. * @returns the dot product
  4854. */
  4855. Quaternion.Dot = function (left, right) {
  4856. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4857. };
  4858. /**
  4859. * Checks if the two quaternions are close to each other
  4860. * @param quat0 defines the first quaternion to check
  4861. * @param quat1 defines the second quaternion to check
  4862. * @returns true if the two quaternions are close to each other
  4863. */
  4864. Quaternion.AreClose = function (quat0, quat1) {
  4865. var dot = Quaternion.Dot(quat0, quat1);
  4866. return dot >= 0;
  4867. };
  4868. /**
  4869. * Creates an empty quaternion
  4870. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4871. */
  4872. Quaternion.Zero = function () {
  4873. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4874. };
  4875. /**
  4876. * Inverse a given quaternion
  4877. * @param q defines the source quaternion
  4878. * @returns a new quaternion as the inverted current quaternion
  4879. */
  4880. Quaternion.Inverse = function (q) {
  4881. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4882. };
  4883. /**
  4884. * Creates an identity quaternion
  4885. * @returns the identity quaternion
  4886. */
  4887. Quaternion.Identity = function () {
  4888. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4889. };
  4890. /**
  4891. * Gets a boolean indicating if the given quaternion is identity
  4892. * @param quaternion defines the quaternion to check
  4893. * @returns true if the quaternion is identity
  4894. */
  4895. Quaternion.IsIdentity = function (quaternion) {
  4896. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4897. };
  4898. /**
  4899. * Creates a quaternion from a rotation around an axis
  4900. * @param axis defines the axis to use
  4901. * @param angle defines the angle to use
  4902. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4903. */
  4904. Quaternion.RotationAxis = function (axis, angle) {
  4905. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4906. };
  4907. /**
  4908. * Creates a rotation around an axis and stores it into the given quaternion
  4909. * @param axis defines the axis to use
  4910. * @param angle defines the angle to use
  4911. * @param result defines the target quaternion
  4912. * @returns the target quaternion
  4913. */
  4914. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4915. var sin = Math.sin(angle / 2);
  4916. axis.normalize();
  4917. result.w = Math.cos(angle / 2);
  4918. result.x = axis.x * sin;
  4919. result.y = axis.y * sin;
  4920. result.z = axis.z * sin;
  4921. return result;
  4922. };
  4923. /**
  4924. * Creates a new quaternion from data stored into an array
  4925. * @param array defines the data source
  4926. * @param offset defines the offset in the source array where the data starts
  4927. * @returns a new quaternion
  4928. */
  4929. Quaternion.FromArray = function (array, offset) {
  4930. if (!offset) {
  4931. offset = 0;
  4932. }
  4933. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4934. };
  4935. /**
  4936. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4937. * @param yaw defines the rotation around Y axis
  4938. * @param pitch defines the rotation around X axis
  4939. * @param roll defines the rotation around Z axis
  4940. * @returns the new quaternion
  4941. */
  4942. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4943. var q = new Quaternion();
  4944. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4945. return q;
  4946. };
  4947. /**
  4948. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4949. * @param yaw defines the rotation around Y axis
  4950. * @param pitch defines the rotation around X axis
  4951. * @param roll defines the rotation around Z axis
  4952. * @param result defines the target quaternion
  4953. */
  4954. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4955. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4956. var halfRoll = roll * 0.5;
  4957. var halfPitch = pitch * 0.5;
  4958. var halfYaw = yaw * 0.5;
  4959. var sinRoll = Math.sin(halfRoll);
  4960. var cosRoll = Math.cos(halfRoll);
  4961. var sinPitch = Math.sin(halfPitch);
  4962. var cosPitch = Math.cos(halfPitch);
  4963. var sinYaw = Math.sin(halfYaw);
  4964. var cosYaw = Math.cos(halfYaw);
  4965. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4966. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4967. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4968. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4969. };
  4970. /**
  4971. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4972. * @param alpha defines the rotation around first axis
  4973. * @param beta defines the rotation around second axis
  4974. * @param gamma defines the rotation around third axis
  4975. * @returns the new quaternion
  4976. */
  4977. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4978. var result = new Quaternion();
  4979. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4980. return result;
  4981. };
  4982. /**
  4983. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4984. * @param alpha defines the rotation around first axis
  4985. * @param beta defines the rotation around second axis
  4986. * @param gamma defines the rotation around third axis
  4987. * @param result defines the target quaternion
  4988. */
  4989. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4990. // Produces a quaternion from Euler angles in the z-x-z orientation
  4991. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4992. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4993. var halfBeta = beta * 0.5;
  4994. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4995. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4996. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4997. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4998. };
  4999. /**
  5000. * 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)
  5001. * @param axis1 defines the first axis
  5002. * @param axis2 defines the second axis
  5003. * @param axis3 defines the third axis
  5004. * @returns the new quaternion
  5005. */
  5006. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5007. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5008. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5009. return quat;
  5010. };
  5011. /**
  5012. * 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
  5013. * @param axis1 defines the first axis
  5014. * @param axis2 defines the second axis
  5015. * @param axis3 defines the third axis
  5016. * @param ref defines the target quaternion
  5017. */
  5018. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5019. var rotMat = MathTmp.Matrix[0];
  5020. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5021. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5022. };
  5023. /**
  5024. * Interpolates between two quaternions
  5025. * @param left defines first quaternion
  5026. * @param right defines second quaternion
  5027. * @param amount defines the gradient to use
  5028. * @returns the new interpolated quaternion
  5029. */
  5030. Quaternion.Slerp = function (left, right, amount) {
  5031. var result = Quaternion.Identity();
  5032. Quaternion.SlerpToRef(left, right, amount, result);
  5033. return result;
  5034. };
  5035. /**
  5036. * Interpolates between two quaternions and stores it into a target quaternion
  5037. * @param left defines first quaternion
  5038. * @param right defines second quaternion
  5039. * @param amount defines the gradient to use
  5040. * @param result defines the target quaternion
  5041. */
  5042. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5043. var num2;
  5044. var num3;
  5045. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5046. var flag = false;
  5047. if (num4 < 0) {
  5048. flag = true;
  5049. num4 = -num4;
  5050. }
  5051. if (num4 > 0.999999) {
  5052. num3 = 1 - amount;
  5053. num2 = flag ? -amount : amount;
  5054. }
  5055. else {
  5056. var num5 = Math.acos(num4);
  5057. var num6 = (1.0 / Math.sin(num5));
  5058. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5059. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5060. }
  5061. result.x = (num3 * left.x) + (num2 * right.x);
  5062. result.y = (num3 * left.y) + (num2 * right.y);
  5063. result.z = (num3 * left.z) + (num2 * right.z);
  5064. result.w = (num3 * left.w) + (num2 * right.w);
  5065. };
  5066. /**
  5067. * Interpolate between two quaternions using Hermite interpolation
  5068. * @param value1 defines first quaternion
  5069. * @param tangent1 defines the incoming tangent
  5070. * @param value2 defines second quaternion
  5071. * @param tangent2 defines the outgoing tangent
  5072. * @param amount defines the target quaternion
  5073. * @returns the new interpolated quaternion
  5074. */
  5075. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5076. var squared = amount * amount;
  5077. var cubed = amount * squared;
  5078. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5079. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5080. var part3 = (cubed - (2.0 * squared)) + amount;
  5081. var part4 = cubed - squared;
  5082. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5083. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5084. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5085. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5086. return new Quaternion(x, y, z, w);
  5087. };
  5088. return Quaternion;
  5089. }());
  5090. BABYLON.Quaternion = Quaternion;
  5091. /**
  5092. * Class used to store matrix data (4x4)
  5093. */
  5094. var Matrix = /** @class */ (function () {
  5095. /**
  5096. * Creates an empty matrix (filled with zeros)
  5097. */
  5098. function Matrix() {
  5099. this._isIdentity = false;
  5100. this._isIdentityDirty = true;
  5101. /**
  5102. * Gets or sets the internal data of the matrix
  5103. */
  5104. this.m = new Float32Array(16);
  5105. this._markAsUpdated();
  5106. }
  5107. /** @hidden */
  5108. Matrix.prototype._markAsUpdated = function () {
  5109. this.updateFlag = Matrix._updateFlagSeed++;
  5110. this._isIdentityDirty = true;
  5111. };
  5112. // Properties
  5113. /**
  5114. * Check if the current matrix is indentity
  5115. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5116. * @returns true is the matrix is the identity matrix
  5117. */
  5118. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5119. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5120. if (this._isIdentityDirty) {
  5121. this._isIdentityDirty = false;
  5122. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5123. this._isIdentity = false;
  5124. }
  5125. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5126. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5127. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5128. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5129. this._isIdentity = false;
  5130. }
  5131. else {
  5132. this._isIdentity = true;
  5133. }
  5134. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5135. this._isIdentity = false;
  5136. }
  5137. }
  5138. return this._isIdentity;
  5139. };
  5140. /**
  5141. * Gets the determinant of the matrix
  5142. * @returns the matrix determinant
  5143. */
  5144. Matrix.prototype.determinant = function () {
  5145. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5146. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5147. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5148. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5149. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5150. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5151. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5152. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5153. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5154. };
  5155. // Methods
  5156. /**
  5157. * Returns the matrix as a Float32Array
  5158. * @returns the matrix underlying array
  5159. */
  5160. Matrix.prototype.toArray = function () {
  5161. return this.m;
  5162. };
  5163. /**
  5164. * Returns the matrix as a Float32Array
  5165. * @returns the matrix underlying array.
  5166. */
  5167. Matrix.prototype.asArray = function () {
  5168. return this.toArray();
  5169. };
  5170. /**
  5171. * Inverts the current matrix in place
  5172. * @returns the current inverted matrix
  5173. */
  5174. Matrix.prototype.invert = function () {
  5175. this.invertToRef(this);
  5176. return this;
  5177. };
  5178. /**
  5179. * Sets all the matrix elements to zero
  5180. * @returns the current matrix
  5181. */
  5182. Matrix.prototype.reset = function () {
  5183. for (var index = 0; index < 16; index++) {
  5184. this.m[index] = 0.0;
  5185. }
  5186. this._markAsUpdated();
  5187. return this;
  5188. };
  5189. /**
  5190. * Adds the current matrix with a second one
  5191. * @param other defines the matrix to add
  5192. * @returns a new matrix as the addition of the current matrix and the given one
  5193. */
  5194. Matrix.prototype.add = function (other) {
  5195. var result = new Matrix();
  5196. this.addToRef(other, result);
  5197. return result;
  5198. };
  5199. /**
  5200. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5201. * @param other defines the matrix to add
  5202. * @param result defines the target matrix
  5203. * @returns the current matrix
  5204. */
  5205. Matrix.prototype.addToRef = function (other, result) {
  5206. for (var index = 0; index < 16; index++) {
  5207. result.m[index] = this.m[index] + other.m[index];
  5208. }
  5209. result._markAsUpdated();
  5210. return this;
  5211. };
  5212. /**
  5213. * Adds in place the given matrix to the current matrix
  5214. * @param other defines the second operand
  5215. * @returns the current updated matrix
  5216. */
  5217. Matrix.prototype.addToSelf = function (other) {
  5218. for (var index = 0; index < 16; index++) {
  5219. this.m[index] += other.m[index];
  5220. }
  5221. this._markAsUpdated();
  5222. return this;
  5223. };
  5224. /**
  5225. * Sets the given matrix to the current inverted Matrix
  5226. * @param other defines the target matrix
  5227. * @returns the unmodified current matrix
  5228. */
  5229. Matrix.prototype.invertToRef = function (other) {
  5230. var l1 = this.m[0];
  5231. var l2 = this.m[1];
  5232. var l3 = this.m[2];
  5233. var l4 = this.m[3];
  5234. var l5 = this.m[4];
  5235. var l6 = this.m[5];
  5236. var l7 = this.m[6];
  5237. var l8 = this.m[7];
  5238. var l9 = this.m[8];
  5239. var l10 = this.m[9];
  5240. var l11 = this.m[10];
  5241. var l12 = this.m[11];
  5242. var l13 = this.m[12];
  5243. var l14 = this.m[13];
  5244. var l15 = this.m[14];
  5245. var l16 = this.m[15];
  5246. var l17 = (l11 * l16) - (l12 * l15);
  5247. var l18 = (l10 * l16) - (l12 * l14);
  5248. var l19 = (l10 * l15) - (l11 * l14);
  5249. var l20 = (l9 * l16) - (l12 * l13);
  5250. var l21 = (l9 * l15) - (l11 * l13);
  5251. var l22 = (l9 * l14) - (l10 * l13);
  5252. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5253. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5254. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5255. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5256. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5257. var l28 = (l7 * l16) - (l8 * l15);
  5258. var l29 = (l6 * l16) - (l8 * l14);
  5259. var l30 = (l6 * l15) - (l7 * l14);
  5260. var l31 = (l5 * l16) - (l8 * l13);
  5261. var l32 = (l5 * l15) - (l7 * l13);
  5262. var l33 = (l5 * l14) - (l6 * l13);
  5263. var l34 = (l7 * l12) - (l8 * l11);
  5264. var l35 = (l6 * l12) - (l8 * l10);
  5265. var l36 = (l6 * l11) - (l7 * l10);
  5266. var l37 = (l5 * l12) - (l8 * l9);
  5267. var l38 = (l5 * l11) - (l7 * l9);
  5268. var l39 = (l5 * l10) - (l6 * l9);
  5269. other.m[0] = l23 * l27;
  5270. other.m[4] = l24 * l27;
  5271. other.m[8] = l25 * l27;
  5272. other.m[12] = l26 * l27;
  5273. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5274. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5275. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5276. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5277. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5278. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5279. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5280. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5281. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5282. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5283. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5284. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5285. other._markAsUpdated();
  5286. return this;
  5287. };
  5288. /**
  5289. * Inserts the translation vector (using 3 floats) in the current matrix
  5290. * @param x defines the 1st component of the translation
  5291. * @param y defines the 2nd component of the translation
  5292. * @param z defines the 3rd component of the translation
  5293. * @returns the current updated matrix
  5294. */
  5295. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5296. this.m[12] = x;
  5297. this.m[13] = y;
  5298. this.m[14] = z;
  5299. this._markAsUpdated();
  5300. return this;
  5301. };
  5302. /**
  5303. * Inserts the translation vector in the current matrix
  5304. * @param vector3 defines the translation to insert
  5305. * @returns the current updated matrix
  5306. */
  5307. Matrix.prototype.setTranslation = function (vector3) {
  5308. this.m[12] = vector3.x;
  5309. this.m[13] = vector3.y;
  5310. this.m[14] = vector3.z;
  5311. this._markAsUpdated();
  5312. return this;
  5313. };
  5314. /**
  5315. * Gets the translation value of the current matrix
  5316. * @returns a new Vector3 as the extracted translation from the matrix
  5317. */
  5318. Matrix.prototype.getTranslation = function () {
  5319. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5320. };
  5321. /**
  5322. * Fill a Vector3 with the extracted translation from the matrix
  5323. * @param result defines the Vector3 where to store the translation
  5324. * @returns the current matrix
  5325. */
  5326. Matrix.prototype.getTranslationToRef = function (result) {
  5327. result.x = this.m[12];
  5328. result.y = this.m[13];
  5329. result.z = this.m[14];
  5330. return this;
  5331. };
  5332. /**
  5333. * Remove rotation and scaling part from the matrix
  5334. * @returns the updated matrix
  5335. */
  5336. Matrix.prototype.removeRotationAndScaling = function () {
  5337. this.setRowFromFloats(0, 1, 0, 0, 0);
  5338. this.setRowFromFloats(1, 0, 1, 0, 0);
  5339. this.setRowFromFloats(2, 0, 0, 1, 0);
  5340. return this;
  5341. };
  5342. /**
  5343. * Multiply two matrices
  5344. * @param other defines the second operand
  5345. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5346. */
  5347. Matrix.prototype.multiply = function (other) {
  5348. var result = new Matrix();
  5349. this.multiplyToRef(other, result);
  5350. return result;
  5351. };
  5352. /**
  5353. * Copy the current matrix from the given one
  5354. * @param other defines the source matrix
  5355. * @returns the current updated matrix
  5356. */
  5357. Matrix.prototype.copyFrom = function (other) {
  5358. for (var index = 0; index < 16; index++) {
  5359. this.m[index] = other.m[index];
  5360. }
  5361. this._markAsUpdated();
  5362. return this;
  5363. };
  5364. /**
  5365. * Populates the given array from the starting index with the current matrix values
  5366. * @param array defines the target array
  5367. * @param offset defines the offset in the target array where to start storing values
  5368. * @returns the current matrix
  5369. */
  5370. Matrix.prototype.copyToArray = function (array, offset) {
  5371. if (offset === void 0) { offset = 0; }
  5372. for (var index = 0; index < 16; index++) {
  5373. array[offset + index] = this.m[index];
  5374. }
  5375. return this;
  5376. };
  5377. /**
  5378. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5379. * @param other defines the second operand
  5380. * @param result defines the matrix where to store the multiplication
  5381. * @returns the current matrix
  5382. */
  5383. Matrix.prototype.multiplyToRef = function (other, result) {
  5384. this.multiplyToArray(other, result.m, 0);
  5385. result._markAsUpdated();
  5386. return this;
  5387. };
  5388. /**
  5389. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5390. * @param other defines the second operand
  5391. * @param result defines the array where to store the multiplication
  5392. * @param offset defines the offset in the target array where to start storing values
  5393. * @returns the current matrix
  5394. */
  5395. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5396. var tm0 = this.m[0];
  5397. var tm1 = this.m[1];
  5398. var tm2 = this.m[2];
  5399. var tm3 = this.m[3];
  5400. var tm4 = this.m[4];
  5401. var tm5 = this.m[5];
  5402. var tm6 = this.m[6];
  5403. var tm7 = this.m[7];
  5404. var tm8 = this.m[8];
  5405. var tm9 = this.m[9];
  5406. var tm10 = this.m[10];
  5407. var tm11 = this.m[11];
  5408. var tm12 = this.m[12];
  5409. var tm13 = this.m[13];
  5410. var tm14 = this.m[14];
  5411. var tm15 = this.m[15];
  5412. var om0 = other.m[0];
  5413. var om1 = other.m[1];
  5414. var om2 = other.m[2];
  5415. var om3 = other.m[3];
  5416. var om4 = other.m[4];
  5417. var om5 = other.m[5];
  5418. var om6 = other.m[6];
  5419. var om7 = other.m[7];
  5420. var om8 = other.m[8];
  5421. var om9 = other.m[9];
  5422. var om10 = other.m[10];
  5423. var om11 = other.m[11];
  5424. var om12 = other.m[12];
  5425. var om13 = other.m[13];
  5426. var om14 = other.m[14];
  5427. var om15 = other.m[15];
  5428. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5429. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5430. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5431. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5432. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5433. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5434. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5435. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5436. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5437. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5438. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5439. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5440. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5441. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5442. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5443. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5444. return this;
  5445. };
  5446. /**
  5447. * Check equality between this matrix and a second one
  5448. * @param value defines the second matrix to compare
  5449. * @returns true is the current matrix and the given one values are strictly equal
  5450. */
  5451. Matrix.prototype.equals = function (value) {
  5452. return value &&
  5453. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5454. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5455. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5456. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5457. };
  5458. /**
  5459. * Clone the current matrix
  5460. * @returns a new matrix from the current matrix
  5461. */
  5462. Matrix.prototype.clone = function () {
  5463. 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]);
  5464. };
  5465. /**
  5466. * Returns the name of the current matrix class
  5467. * @returns the string "Matrix"
  5468. */
  5469. Matrix.prototype.getClassName = function () {
  5470. return "Matrix";
  5471. };
  5472. /**
  5473. * Gets the hash code of the current matrix
  5474. * @returns the hash code
  5475. */
  5476. Matrix.prototype.getHashCode = function () {
  5477. var hash = this.m[0] || 0;
  5478. for (var i = 1; i < 16; i++) {
  5479. hash = (hash * 397) ^ (this.m[i] || 0);
  5480. }
  5481. return hash;
  5482. };
  5483. /**
  5484. * Decomposes the current Matrix into a translation, rotation and scaling components
  5485. * @param scale defines the scale vector3 given as a reference to update
  5486. * @param rotation defines the rotation quaternion given as a reference to update
  5487. * @param translation defines the translation vector3 given as a reference to update
  5488. * @returns true if operation was successful
  5489. */
  5490. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5491. if (translation) {
  5492. translation.x = this.m[12];
  5493. translation.y = this.m[13];
  5494. translation.z = this.m[14];
  5495. }
  5496. scale = scale || MathTmp.Vector3[0];
  5497. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5498. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5499. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5500. if (this.determinant() <= 0) {
  5501. scale.y *= -1;
  5502. }
  5503. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5504. if (rotation) {
  5505. rotation.x = 0;
  5506. rotation.y = 0;
  5507. rotation.z = 0;
  5508. rotation.w = 1;
  5509. }
  5510. return false;
  5511. }
  5512. if (rotation) {
  5513. 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]);
  5514. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5515. }
  5516. return true;
  5517. };
  5518. /**
  5519. * Gets specific row of the matrix
  5520. * @param index defines the number of the row to get
  5521. * @returns the index-th row of the current matrix as a new Vector4
  5522. */
  5523. Matrix.prototype.getRow = function (index) {
  5524. if (index < 0 || index > 3) {
  5525. return null;
  5526. }
  5527. var i = index * 4;
  5528. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5529. };
  5530. /**
  5531. * Sets the index-th row of the current matrix to the vector4 values
  5532. * @param index defines the number of the row to set
  5533. * @param row defines the target vector4
  5534. * @returns the updated current matrix
  5535. */
  5536. Matrix.prototype.setRow = function (index, row) {
  5537. if (index < 0 || index > 3) {
  5538. return this;
  5539. }
  5540. var i = index * 4;
  5541. this.m[i + 0] = row.x;
  5542. this.m[i + 1] = row.y;
  5543. this.m[i + 2] = row.z;
  5544. this.m[i + 3] = row.w;
  5545. this._markAsUpdated();
  5546. return this;
  5547. };
  5548. /**
  5549. * Compute the transpose of the matrix
  5550. * @returns the new transposed matrix
  5551. */
  5552. Matrix.prototype.transpose = function () {
  5553. return Matrix.Transpose(this);
  5554. };
  5555. /**
  5556. * Compute the transpose of the matrix and store it in a given matrix
  5557. * @param result defines the target matrix
  5558. * @returns the current matrix
  5559. */
  5560. Matrix.prototype.transposeToRef = function (result) {
  5561. Matrix.TransposeToRef(this, result);
  5562. return this;
  5563. };
  5564. /**
  5565. * Sets the index-th row of the current matrix with the given 4 x float values
  5566. * @param index defines the row index
  5567. * @param x defines the x component to set
  5568. * @param y defines the y component to set
  5569. * @param z defines the z component to set
  5570. * @param w defines the w component to set
  5571. * @returns the updated current matrix
  5572. */
  5573. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5574. if (index < 0 || index > 3) {
  5575. return this;
  5576. }
  5577. var i = index * 4;
  5578. this.m[i + 0] = x;
  5579. this.m[i + 1] = y;
  5580. this.m[i + 2] = z;
  5581. this.m[i + 3] = w;
  5582. this._markAsUpdated();
  5583. return this;
  5584. };
  5585. /**
  5586. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5587. * @param scale defines the scale factor
  5588. * @returns a new matrix
  5589. */
  5590. Matrix.prototype.scale = function (scale) {
  5591. var result = new Matrix();
  5592. this.scaleToRef(scale, result);
  5593. return result;
  5594. };
  5595. /**
  5596. * Scale the current matrix values by a factor to a given result matrix
  5597. * @param scale defines the scale factor
  5598. * @param result defines the matrix to store the result
  5599. * @returns the current matrix
  5600. */
  5601. Matrix.prototype.scaleToRef = function (scale, result) {
  5602. for (var index = 0; index < 16; index++) {
  5603. result.m[index] = this.m[index] * scale;
  5604. }
  5605. result._markAsUpdated();
  5606. return this;
  5607. };
  5608. /**
  5609. * Scale the current matrix values by a factor and add the result to a given matrix
  5610. * @param scale defines the scale factor
  5611. * @param result defines the Matrix to store the result
  5612. * @returns the current matrix
  5613. */
  5614. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5615. for (var index = 0; index < 16; index++) {
  5616. result.m[index] += this.m[index] * scale;
  5617. }
  5618. result._markAsUpdated();
  5619. return this;
  5620. };
  5621. /**
  5622. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5623. * @param ref matrix to store the result
  5624. */
  5625. Matrix.prototype.toNormalMatrix = function (ref) {
  5626. this.invertToRef(ref);
  5627. ref.transpose();
  5628. var m = ref.m;
  5629. 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);
  5630. };
  5631. /**
  5632. * Gets only rotation part of the current matrix
  5633. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5634. */
  5635. Matrix.prototype.getRotationMatrix = function () {
  5636. var result = Matrix.Identity();
  5637. this.getRotationMatrixToRef(result);
  5638. return result;
  5639. };
  5640. /**
  5641. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5642. * @param result defines the target matrix to store data to
  5643. * @returns the current matrix
  5644. */
  5645. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5646. var m = this.m;
  5647. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5648. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5649. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5650. if (this.determinant() <= 0) {
  5651. sy *= -1;
  5652. }
  5653. if (sx === 0 || sy === 0 || sz === 0) {
  5654. Matrix.IdentityToRef(result);
  5655. }
  5656. else {
  5657. 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);
  5658. }
  5659. return this;
  5660. };
  5661. // Statics
  5662. /**
  5663. * Creates a matrix from an array
  5664. * @param array defines the source array
  5665. * @param offset defines an offset in the source array
  5666. * @returns a new Matrix set from the starting index of the given array
  5667. */
  5668. Matrix.FromArray = function (array, offset) {
  5669. var result = new Matrix();
  5670. if (!offset) {
  5671. offset = 0;
  5672. }
  5673. Matrix.FromArrayToRef(array, offset, result);
  5674. return result;
  5675. };
  5676. /**
  5677. * Copy the content of an array into a given matrix
  5678. * @param array defines the source array
  5679. * @param offset defines an offset in the source array
  5680. * @param result defines the target matrix
  5681. */
  5682. Matrix.FromArrayToRef = function (array, offset, result) {
  5683. for (var index = 0; index < 16; index++) {
  5684. result.m[index] = array[index + offset];
  5685. }
  5686. result._markAsUpdated();
  5687. };
  5688. /**
  5689. * Stores an array into a matrix after having multiplied each component by a given factor
  5690. * @param array defines the source array
  5691. * @param offset defines the offset in the source array
  5692. * @param scale defines the scaling factor
  5693. * @param result defines the target matrix
  5694. */
  5695. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5696. for (var index = 0; index < 16; index++) {
  5697. result.m[index] = array[index + offset] * scale;
  5698. }
  5699. result._markAsUpdated();
  5700. };
  5701. /**
  5702. * Stores a list of values (16) inside a given matrix
  5703. * @param initialM11 defines 1st value of 1st row
  5704. * @param initialM12 defines 2nd value of 1st row
  5705. * @param initialM13 defines 3rd value of 1st row
  5706. * @param initialM14 defines 4th value of 1st row
  5707. * @param initialM21 defines 1st value of 2nd row
  5708. * @param initialM22 defines 2nd value of 2nd row
  5709. * @param initialM23 defines 3rd value of 2nd row
  5710. * @param initialM24 defines 4th value of 2nd row
  5711. * @param initialM31 defines 1st value of 3rd row
  5712. * @param initialM32 defines 2nd value of 3rd row
  5713. * @param initialM33 defines 3rd value of 3rd row
  5714. * @param initialM34 defines 4th value of 3rd row
  5715. * @param initialM41 defines 1st value of 4th row
  5716. * @param initialM42 defines 2nd value of 4th row
  5717. * @param initialM43 defines 3rd value of 4th row
  5718. * @param initialM44 defines 4th value of 4th row
  5719. * @param result defines the target matrix
  5720. */
  5721. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5722. result.m[0] = initialM11;
  5723. result.m[1] = initialM12;
  5724. result.m[2] = initialM13;
  5725. result.m[3] = initialM14;
  5726. result.m[4] = initialM21;
  5727. result.m[5] = initialM22;
  5728. result.m[6] = initialM23;
  5729. result.m[7] = initialM24;
  5730. result.m[8] = initialM31;
  5731. result.m[9] = initialM32;
  5732. result.m[10] = initialM33;
  5733. result.m[11] = initialM34;
  5734. result.m[12] = initialM41;
  5735. result.m[13] = initialM42;
  5736. result.m[14] = initialM43;
  5737. result.m[15] = initialM44;
  5738. result._markAsUpdated();
  5739. };
  5740. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5741. /**
  5742. * Gets an identity matrix that must not be updated
  5743. */
  5744. get: function () {
  5745. return Matrix._identityReadOnly;
  5746. },
  5747. enumerable: true,
  5748. configurable: true
  5749. });
  5750. /**
  5751. * Creates new matrix from a list of values (16)
  5752. * @param initialM11 defines 1st value of 1st row
  5753. * @param initialM12 defines 2nd value of 1st row
  5754. * @param initialM13 defines 3rd value of 1st row
  5755. * @param initialM14 defines 4th value of 1st row
  5756. * @param initialM21 defines 1st value of 2nd row
  5757. * @param initialM22 defines 2nd value of 2nd row
  5758. * @param initialM23 defines 3rd value of 2nd row
  5759. * @param initialM24 defines 4th value of 2nd row
  5760. * @param initialM31 defines 1st value of 3rd row
  5761. * @param initialM32 defines 2nd value of 3rd row
  5762. * @param initialM33 defines 3rd value of 3rd row
  5763. * @param initialM34 defines 4th value of 3rd row
  5764. * @param initialM41 defines 1st value of 4th row
  5765. * @param initialM42 defines 2nd value of 4th row
  5766. * @param initialM43 defines 3rd value of 4th row
  5767. * @param initialM44 defines 4th value of 4th row
  5768. * @returns the new matrix
  5769. */
  5770. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5771. var result = new Matrix();
  5772. result.m[0] = initialM11;
  5773. result.m[1] = initialM12;
  5774. result.m[2] = initialM13;
  5775. result.m[3] = initialM14;
  5776. result.m[4] = initialM21;
  5777. result.m[5] = initialM22;
  5778. result.m[6] = initialM23;
  5779. result.m[7] = initialM24;
  5780. result.m[8] = initialM31;
  5781. result.m[9] = initialM32;
  5782. result.m[10] = initialM33;
  5783. result.m[11] = initialM34;
  5784. result.m[12] = initialM41;
  5785. result.m[13] = initialM42;
  5786. result.m[14] = initialM43;
  5787. result.m[15] = initialM44;
  5788. return result;
  5789. };
  5790. /**
  5791. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5792. * @param scale defines the scale vector3
  5793. * @param rotation defines the rotation quaternion
  5794. * @param translation defines the translation vector3
  5795. * @returns a new matrix
  5796. */
  5797. Matrix.Compose = function (scale, rotation, translation) {
  5798. var result = Matrix.Identity();
  5799. Matrix.ComposeToRef(scale, rotation, translation, result);
  5800. return result;
  5801. };
  5802. /**
  5803. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5804. * @param scale defines the scale vector3
  5805. * @param rotation defines the rotation quaternion
  5806. * @param translation defines the translation vector3
  5807. * @param result defines the target matrix
  5808. */
  5809. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5810. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5811. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5812. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5813. result.setTranslation(translation);
  5814. };
  5815. /**
  5816. * Creates a new identity matrix
  5817. * @returns a new identity matrix
  5818. */
  5819. Matrix.Identity = function () {
  5820. 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);
  5821. };
  5822. /**
  5823. * Creates a new identity matrix and stores the result in a given matrix
  5824. * @param result defines the target matrix
  5825. */
  5826. Matrix.IdentityToRef = function (result) {
  5827. 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);
  5828. };
  5829. /**
  5830. * Creates a new zero matrix
  5831. * @returns a new zero matrix
  5832. */
  5833. Matrix.Zero = function () {
  5834. 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);
  5835. };
  5836. /**
  5837. * Creates a new rotation matrix for "angle" radians around the X axis
  5838. * @param angle defines the angle (in radians) to use
  5839. * @return the new matrix
  5840. */
  5841. Matrix.RotationX = function (angle) {
  5842. var result = new Matrix();
  5843. Matrix.RotationXToRef(angle, result);
  5844. return result;
  5845. };
  5846. /**
  5847. * Creates a new matrix as the invert of a given matrix
  5848. * @param source defines the source matrix
  5849. * @returns the new matrix
  5850. */
  5851. Matrix.Invert = function (source) {
  5852. var result = new Matrix();
  5853. source.invertToRef(result);
  5854. return result;
  5855. };
  5856. /**
  5857. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5858. * @param angle defines the angle (in radians) to use
  5859. * @param result defines the target matrix
  5860. */
  5861. Matrix.RotationXToRef = function (angle, result) {
  5862. var s = Math.sin(angle);
  5863. var c = Math.cos(angle);
  5864. result.m[0] = 1.0;
  5865. result.m[15] = 1.0;
  5866. result.m[5] = c;
  5867. result.m[10] = c;
  5868. result.m[9] = -s;
  5869. result.m[6] = s;
  5870. result.m[1] = 0.0;
  5871. result.m[2] = 0.0;
  5872. result.m[3] = 0.0;
  5873. result.m[4] = 0.0;
  5874. result.m[7] = 0.0;
  5875. result.m[8] = 0.0;
  5876. result.m[11] = 0.0;
  5877. result.m[12] = 0.0;
  5878. result.m[13] = 0.0;
  5879. result.m[14] = 0.0;
  5880. result._markAsUpdated();
  5881. };
  5882. /**
  5883. * Creates a new rotation matrix for "angle" radians around the Y axis
  5884. * @param angle defines the angle (in radians) to use
  5885. * @return the new matrix
  5886. */
  5887. Matrix.RotationY = function (angle) {
  5888. var result = new Matrix();
  5889. Matrix.RotationYToRef(angle, result);
  5890. return result;
  5891. };
  5892. /**
  5893. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5894. * @param angle defines the angle (in radians) to use
  5895. * @param result defines the target matrix
  5896. */
  5897. Matrix.RotationYToRef = function (angle, result) {
  5898. var s = Math.sin(angle);
  5899. var c = Math.cos(angle);
  5900. result.m[5] = 1.0;
  5901. result.m[15] = 1.0;
  5902. result.m[0] = c;
  5903. result.m[2] = -s;
  5904. result.m[8] = s;
  5905. result.m[10] = c;
  5906. result.m[1] = 0.0;
  5907. result.m[3] = 0.0;
  5908. result.m[4] = 0.0;
  5909. result.m[6] = 0.0;
  5910. result.m[7] = 0.0;
  5911. result.m[9] = 0.0;
  5912. result.m[11] = 0.0;
  5913. result.m[12] = 0.0;
  5914. result.m[13] = 0.0;
  5915. result.m[14] = 0.0;
  5916. result._markAsUpdated();
  5917. };
  5918. /**
  5919. * Creates a new rotation matrix for "angle" radians around the Z axis
  5920. * @param angle defines the angle (in radians) to use
  5921. * @return the new matrix
  5922. */
  5923. Matrix.RotationZ = function (angle) {
  5924. var result = new Matrix();
  5925. Matrix.RotationZToRef(angle, result);
  5926. return result;
  5927. };
  5928. /**
  5929. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5930. * @param angle defines the angle (in radians) to use
  5931. * @param result defines the target matrix
  5932. */
  5933. Matrix.RotationZToRef = function (angle, result) {
  5934. var s = Math.sin(angle);
  5935. var c = Math.cos(angle);
  5936. result.m[10] = 1.0;
  5937. result.m[15] = 1.0;
  5938. result.m[0] = c;
  5939. result.m[1] = s;
  5940. result.m[4] = -s;
  5941. result.m[5] = c;
  5942. result.m[2] = 0.0;
  5943. result.m[3] = 0.0;
  5944. result.m[6] = 0.0;
  5945. result.m[7] = 0.0;
  5946. result.m[8] = 0.0;
  5947. result.m[9] = 0.0;
  5948. result.m[11] = 0.0;
  5949. result.m[12] = 0.0;
  5950. result.m[13] = 0.0;
  5951. result.m[14] = 0.0;
  5952. result._markAsUpdated();
  5953. };
  5954. /**
  5955. * Creates a new rotation matrix for "angle" radians around the given axis
  5956. * @param axis defines the axis to use
  5957. * @param angle defines the angle (in radians) to use
  5958. * @return the new matrix
  5959. */
  5960. Matrix.RotationAxis = function (axis, angle) {
  5961. var result = Matrix.Zero();
  5962. Matrix.RotationAxisToRef(axis, angle, result);
  5963. return result;
  5964. };
  5965. /**
  5966. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5967. * @param axis defines the axis to use
  5968. * @param angle defines the angle (in radians) to use
  5969. * @param result defines the target matrix
  5970. */
  5971. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5972. var s = Math.sin(-angle);
  5973. var c = Math.cos(-angle);
  5974. var c1 = 1 - c;
  5975. axis.normalize();
  5976. result.m[0] = (axis.x * axis.x) * c1 + c;
  5977. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5978. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5979. result.m[3] = 0.0;
  5980. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5981. result.m[5] = (axis.y * axis.y) * c1 + c;
  5982. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5983. result.m[7] = 0.0;
  5984. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5985. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5986. result.m[10] = (axis.z * axis.z) * c1 + c;
  5987. result.m[11] = 0.0;
  5988. result.m[15] = 1.0;
  5989. result._markAsUpdated();
  5990. };
  5991. /**
  5992. * Creates a rotation matrix
  5993. * @param yaw defines the yaw angle in radians (Y axis)
  5994. * @param pitch defines the pitch angle in radians (X axis)
  5995. * @param roll defines the roll angle in radians (X axis)
  5996. * @returns the new rotation matrix
  5997. */
  5998. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5999. var result = new Matrix();
  6000. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6001. return result;
  6002. };
  6003. /**
  6004. * Creates a rotation matrix and stores it in a given matrix
  6005. * @param yaw defines the yaw angle in radians (Y axis)
  6006. * @param pitch defines the pitch angle in radians (X axis)
  6007. * @param roll defines the roll angle in radians (X axis)
  6008. * @param result defines the target matrix
  6009. */
  6010. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6011. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6012. this._tempQuaternion.toRotationMatrix(result);
  6013. };
  6014. /**
  6015. * Creates a scaling matrix
  6016. * @param x defines the scale factor on X axis
  6017. * @param y defines the scale factor on Y axis
  6018. * @param z defines the scale factor on Z axis
  6019. * @returns the new matrix
  6020. */
  6021. Matrix.Scaling = function (x, y, z) {
  6022. var result = Matrix.Zero();
  6023. Matrix.ScalingToRef(x, y, z, result);
  6024. return result;
  6025. };
  6026. /**
  6027. * Creates a scaling matrix and stores it in a given matrix
  6028. * @param x defines the scale factor on X axis
  6029. * @param y defines the scale factor on Y axis
  6030. * @param z defines the scale factor on Z axis
  6031. * @param result defines the target matrix
  6032. */
  6033. Matrix.ScalingToRef = function (x, y, z, result) {
  6034. result.m[0] = x;
  6035. result.m[1] = 0.0;
  6036. result.m[2] = 0.0;
  6037. result.m[3] = 0.0;
  6038. result.m[4] = 0.0;
  6039. result.m[5] = y;
  6040. result.m[6] = 0.0;
  6041. result.m[7] = 0.0;
  6042. result.m[8] = 0.0;
  6043. result.m[9] = 0.0;
  6044. result.m[10] = z;
  6045. result.m[11] = 0.0;
  6046. result.m[12] = 0.0;
  6047. result.m[13] = 0.0;
  6048. result.m[14] = 0.0;
  6049. result.m[15] = 1.0;
  6050. result._markAsUpdated();
  6051. };
  6052. /**
  6053. * Creates a translation matrix
  6054. * @param x defines the translation on X axis
  6055. * @param y defines the translation on Y axis
  6056. * @param z defines the translationon Z axis
  6057. * @returns the new matrix
  6058. */
  6059. Matrix.Translation = function (x, y, z) {
  6060. var result = Matrix.Identity();
  6061. Matrix.TranslationToRef(x, y, z, result);
  6062. return result;
  6063. };
  6064. /**
  6065. * Creates a translation matrix and stores it in a given matrix
  6066. * @param x defines the translation on X axis
  6067. * @param y defines the translation on Y axis
  6068. * @param z defines the translationon Z axis
  6069. * @param result defines the target matrix
  6070. */
  6071. Matrix.TranslationToRef = function (x, y, z, result) {
  6072. 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);
  6073. };
  6074. /**
  6075. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6076. * @param startValue defines the start value
  6077. * @param endValue defines the end value
  6078. * @param gradient defines the gradient factor
  6079. * @returns the new matrix
  6080. */
  6081. Matrix.Lerp = function (startValue, endValue, gradient) {
  6082. var result = Matrix.Zero();
  6083. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6084. return result;
  6085. };
  6086. /**
  6087. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6088. * @param startValue defines the start value
  6089. * @param endValue defines the end value
  6090. * @param gradient defines the gradient factor
  6091. * @param result defines the Matrix object where to store data
  6092. */
  6093. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6094. for (var index = 0; index < 16; index++) {
  6095. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6096. }
  6097. result._markAsUpdated();
  6098. };
  6099. /**
  6100. * Builds a new matrix whose values are computed by:
  6101. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6102. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6103. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6104. * @param startValue defines the first matrix
  6105. * @param endValue defines the second matrix
  6106. * @param gradient defines the gradient between the two matrices
  6107. * @returns the new matrix
  6108. */
  6109. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6110. var result = Matrix.Zero();
  6111. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6112. return result;
  6113. };
  6114. /**
  6115. * Update a matrix to values which are computed by:
  6116. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6117. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6118. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6119. * @param startValue defines the first matrix
  6120. * @param endValue defines the second matrix
  6121. * @param gradient defines the gradient between the two matrices
  6122. * @param result defines the target matrix
  6123. */
  6124. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6125. var startScale = MathTmp.Vector3[0];
  6126. var startRotation = MathTmp.Quaternion[0];
  6127. var startTranslation = MathTmp.Vector3[1];
  6128. startValue.decompose(startScale, startRotation, startTranslation);
  6129. var endScale = MathTmp.Vector3[2];
  6130. var endRotation = MathTmp.Quaternion[1];
  6131. var endTranslation = MathTmp.Vector3[3];
  6132. endValue.decompose(endScale, endRotation, endTranslation);
  6133. var resultScale = MathTmp.Vector3[4];
  6134. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6135. var resultRotation = MathTmp.Quaternion[2];
  6136. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6137. var resultTranslation = MathTmp.Vector3[5];
  6138. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6139. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6140. };
  6141. /**
  6142. * 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"
  6143. * This function works in left handed mode
  6144. * @param eye defines the final position of the entity
  6145. * @param target defines where the entity should look at
  6146. * @param up defines the up vector for the entity
  6147. * @returns the new matrix
  6148. */
  6149. Matrix.LookAtLH = function (eye, target, up) {
  6150. var result = Matrix.Zero();
  6151. Matrix.LookAtLHToRef(eye, target, up, result);
  6152. return result;
  6153. };
  6154. /**
  6155. * 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".
  6156. * This function works in left handed mode
  6157. * @param eye defines the final position of the entity
  6158. * @param target defines where the entity should look at
  6159. * @param up defines the up vector for the entity
  6160. * @param result defines the target matrix
  6161. */
  6162. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6163. // Z axis
  6164. target.subtractToRef(eye, this._zAxis);
  6165. this._zAxis.normalize();
  6166. // X axis
  6167. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6168. if (this._xAxis.lengthSquared() === 0) {
  6169. this._xAxis.x = 1.0;
  6170. }
  6171. else {
  6172. this._xAxis.normalize();
  6173. }
  6174. // Y axis
  6175. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6176. this._yAxis.normalize();
  6177. // Eye angles
  6178. var ex = -Vector3.Dot(this._xAxis, eye);
  6179. var ey = -Vector3.Dot(this._yAxis, eye);
  6180. var ez = -Vector3.Dot(this._zAxis, eye);
  6181. 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);
  6182. };
  6183. /**
  6184. * 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"
  6185. * This function works in right handed mode
  6186. * @param eye defines the final position of the entity
  6187. * @param target defines where the entity should look at
  6188. * @param up defines the up vector for the entity
  6189. * @returns the new matrix
  6190. */
  6191. Matrix.LookAtRH = function (eye, target, up) {
  6192. var result = Matrix.Zero();
  6193. Matrix.LookAtRHToRef(eye, target, up, result);
  6194. return result;
  6195. };
  6196. /**
  6197. * 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".
  6198. * This function works in right handed mode
  6199. * @param eye defines the final position of the entity
  6200. * @param target defines where the entity should look at
  6201. * @param up defines the up vector for the entity
  6202. * @param result defines the target matrix
  6203. */
  6204. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6205. // Z axis
  6206. eye.subtractToRef(target, this._zAxis);
  6207. this._zAxis.normalize();
  6208. // X axis
  6209. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6210. if (this._xAxis.lengthSquared() === 0) {
  6211. this._xAxis.x = 1.0;
  6212. }
  6213. else {
  6214. this._xAxis.normalize();
  6215. }
  6216. // Y axis
  6217. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6218. this._yAxis.normalize();
  6219. // Eye angles
  6220. var ex = -Vector3.Dot(this._xAxis, eye);
  6221. var ey = -Vector3.Dot(this._yAxis, eye);
  6222. var ez = -Vector3.Dot(this._zAxis, eye);
  6223. 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);
  6224. };
  6225. /**
  6226. * Create a left-handed orthographic projection matrix
  6227. * @param width defines the viewport width
  6228. * @param height defines the viewport height
  6229. * @param znear defines the near clip plane
  6230. * @param zfar defines the far clip plane
  6231. * @returns a new matrix as a left-handed orthographic projection matrix
  6232. */
  6233. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6234. var matrix = Matrix.Zero();
  6235. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6236. return matrix;
  6237. };
  6238. /**
  6239. * Store a left-handed orthographic projection to a given matrix
  6240. * @param width defines the viewport width
  6241. * @param height defines the viewport height
  6242. * @param znear defines the near clip plane
  6243. * @param zfar defines the far clip plane
  6244. * @param result defines the target matrix
  6245. */
  6246. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6247. var n = znear;
  6248. var f = zfar;
  6249. var a = 2.0 / width;
  6250. var b = 2.0 / height;
  6251. var c = 2.0 / (f - n);
  6252. var d = -(f + n) / (f - n);
  6253. 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);
  6254. };
  6255. /**
  6256. * Create a left-handed orthographic projection matrix
  6257. * @param left defines the viewport left coordinate
  6258. * @param right defines the viewport right coordinate
  6259. * @param bottom defines the viewport bottom coordinate
  6260. * @param top defines the viewport top coordinate
  6261. * @param znear defines the near clip plane
  6262. * @param zfar defines the far clip plane
  6263. * @returns a new matrix as a left-handed orthographic projection matrix
  6264. */
  6265. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6266. var matrix = Matrix.Zero();
  6267. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6268. return matrix;
  6269. };
  6270. /**
  6271. * Stores a left-handed orthographic projection into a given matrix
  6272. * @param left defines the viewport left coordinate
  6273. * @param right defines the viewport right coordinate
  6274. * @param bottom defines the viewport bottom coordinate
  6275. * @param top defines the viewport top coordinate
  6276. * @param znear defines the near clip plane
  6277. * @param zfar defines the far clip plane
  6278. * @param result defines the target matrix
  6279. */
  6280. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6281. var n = znear;
  6282. var f = zfar;
  6283. var a = 2.0 / (right - left);
  6284. var b = 2.0 / (top - bottom);
  6285. var c = 2.0 / (f - n);
  6286. var d = -(f + n) / (f - n);
  6287. var i0 = (left + right) / (left - right);
  6288. var i1 = (top + bottom) / (bottom - top);
  6289. 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);
  6290. };
  6291. /**
  6292. * Creates a right-handed orthographic projection matrix
  6293. * @param left defines the viewport left coordinate
  6294. * @param right defines the viewport right coordinate
  6295. * @param bottom defines the viewport bottom coordinate
  6296. * @param top defines the viewport top coordinate
  6297. * @param znear defines the near clip plane
  6298. * @param zfar defines the far clip plane
  6299. * @returns a new matrix as a right-handed orthographic projection matrix
  6300. */
  6301. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6302. var matrix = Matrix.Zero();
  6303. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6304. return matrix;
  6305. };
  6306. /**
  6307. * Stores a right-handed orthographic projection into a given matrix
  6308. * @param left defines the viewport left coordinate
  6309. * @param right defines the viewport right coordinate
  6310. * @param bottom defines the viewport bottom coordinate
  6311. * @param top defines the viewport top coordinate
  6312. * @param znear defines the near clip plane
  6313. * @param zfar defines the far clip plane
  6314. * @param result defines the target matrix
  6315. */
  6316. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6317. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6318. result.m[10] *= -1.0;
  6319. };
  6320. /**
  6321. * Creates a left-handed perspective projection matrix
  6322. * @param width defines the viewport width
  6323. * @param height defines the viewport height
  6324. * @param znear defines the near clip plane
  6325. * @param zfar defines the far clip plane
  6326. * @returns a new matrix as a left-handed perspective projection matrix
  6327. */
  6328. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6329. var matrix = Matrix.Zero();
  6330. var n = znear;
  6331. var f = zfar;
  6332. var a = 2.0 * n / width;
  6333. var b = 2.0 * n / height;
  6334. var c = (f + n) / (f - n);
  6335. var d = -2.0 * f * n / (f - n);
  6336. 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);
  6337. return matrix;
  6338. };
  6339. /**
  6340. * Creates a left-handed perspective projection matrix
  6341. * @param fov defines the horizontal field of view
  6342. * @param aspect defines the aspect ratio
  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.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6348. var matrix = Matrix.Zero();
  6349. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6350. return matrix;
  6351. };
  6352. /**
  6353. * Stores a left-handed perspective projection into a given matrix
  6354. * @param fov defines the horizontal field of view
  6355. * @param aspect defines the aspect ratio
  6356. * @param znear defines the near clip plane
  6357. * @param zfar defines the far clip plane
  6358. * @param result defines the target matrix
  6359. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6360. */
  6361. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6362. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6363. var n = znear;
  6364. var f = zfar;
  6365. var t = 1.0 / (Math.tan(fov * 0.5));
  6366. var a = isVerticalFovFixed ? (t / aspect) : t;
  6367. var b = isVerticalFovFixed ? t : (t * aspect);
  6368. var c = (f + n) / (f - n);
  6369. var d = -2.0 * f * n / (f - n);
  6370. 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);
  6371. };
  6372. /**
  6373. * Creates a right-handed perspective projection matrix
  6374. * @param fov defines the horizontal field of view
  6375. * @param aspect defines the aspect ratio
  6376. * @param znear defines the near clip plane
  6377. * @param zfar defines the far clip plane
  6378. * @returns a new matrix as a right-handed perspective projection matrix
  6379. */
  6380. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6381. var matrix = Matrix.Zero();
  6382. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6383. return matrix;
  6384. };
  6385. /**
  6386. * Stores a right-handed perspective projection into a given matrix
  6387. * @param fov defines the horizontal field of view
  6388. * @param aspect defines the aspect ratio
  6389. * @param znear defines the near clip plane
  6390. * @param zfar defines the far clip plane
  6391. * @param result defines the target matrix
  6392. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6393. */
  6394. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6395. //alternatively this could be expressed as:
  6396. // m = PerspectiveFovLHToRef
  6397. // m[10] *= -1.0;
  6398. // m[11] *= -1.0;
  6399. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6400. var n = znear;
  6401. var f = zfar;
  6402. var t = 1.0 / (Math.tan(fov * 0.5));
  6403. var a = isVerticalFovFixed ? (t / aspect) : t;
  6404. var b = isVerticalFovFixed ? t : (t * aspect);
  6405. var c = -(f + n) / (f - n);
  6406. var d = -2 * f * n / (f - n);
  6407. 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);
  6408. };
  6409. /**
  6410. * Stores a perspective projection for WebVR info a given matrix
  6411. * @param fov defines the field of view
  6412. * @param znear defines the near clip plane
  6413. * @param zfar defines the far clip plane
  6414. * @param result defines the target matrix
  6415. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6416. */
  6417. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6418. if (rightHanded === void 0) { rightHanded = false; }
  6419. var rightHandedFactor = rightHanded ? -1 : 1;
  6420. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6421. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6422. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6423. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6424. var xScale = 2.0 / (leftTan + rightTan);
  6425. var yScale = 2.0 / (upTan + downTan);
  6426. result.m[0] = xScale;
  6427. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6428. result.m[5] = yScale;
  6429. result.m[6] = result.m[7] = 0.0;
  6430. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6431. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6432. result.m[10] = -zfar / (znear - zfar);
  6433. result.m[11] = 1.0 * rightHandedFactor;
  6434. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6435. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6436. result._markAsUpdated();
  6437. };
  6438. /**
  6439. * Computes a complete transformation matrix
  6440. * @param viewport defines the viewport to use
  6441. * @param world defines the world matrix
  6442. * @param view defines the view matrix
  6443. * @param projection defines the projection matrix
  6444. * @param zmin defines the near clip plane
  6445. * @param zmax defines the far clip plane
  6446. * @returns the transformation matrix
  6447. */
  6448. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6449. var cw = viewport.width;
  6450. var ch = viewport.height;
  6451. var cx = viewport.x;
  6452. var cy = viewport.y;
  6453. 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);
  6454. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6455. };
  6456. /**
  6457. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6458. * @param matrix defines the matrix to use
  6459. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6460. */
  6461. Matrix.GetAsMatrix2x2 = function (matrix) {
  6462. return new Float32Array([
  6463. matrix.m[0], matrix.m[1],
  6464. matrix.m[4], matrix.m[5]
  6465. ]);
  6466. };
  6467. /**
  6468. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6469. * @param matrix defines the matrix to use
  6470. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6471. */
  6472. Matrix.GetAsMatrix3x3 = function (matrix) {
  6473. return new Float32Array([
  6474. matrix.m[0], matrix.m[1], matrix.m[2],
  6475. matrix.m[4], matrix.m[5], matrix.m[6],
  6476. matrix.m[8], matrix.m[9], matrix.m[10]
  6477. ]);
  6478. };
  6479. /**
  6480. * Compute the transpose of a given matrix
  6481. * @param matrix defines the matrix to transpose
  6482. * @returns the new matrix
  6483. */
  6484. Matrix.Transpose = function (matrix) {
  6485. var result = new Matrix();
  6486. Matrix.TransposeToRef(matrix, result);
  6487. return result;
  6488. };
  6489. /**
  6490. * Compute the transpose of a matrix and store it in a target matrix
  6491. * @param matrix defines the matrix to transpose
  6492. * @param result defines the target matrix
  6493. */
  6494. Matrix.TransposeToRef = function (matrix, result) {
  6495. result.m[0] = matrix.m[0];
  6496. result.m[1] = matrix.m[4];
  6497. result.m[2] = matrix.m[8];
  6498. result.m[3] = matrix.m[12];
  6499. result.m[4] = matrix.m[1];
  6500. result.m[5] = matrix.m[5];
  6501. result.m[6] = matrix.m[9];
  6502. result.m[7] = matrix.m[13];
  6503. result.m[8] = matrix.m[2];
  6504. result.m[9] = matrix.m[6];
  6505. result.m[10] = matrix.m[10];
  6506. result.m[11] = matrix.m[14];
  6507. result.m[12] = matrix.m[3];
  6508. result.m[13] = matrix.m[7];
  6509. result.m[14] = matrix.m[11];
  6510. result.m[15] = matrix.m[15];
  6511. };
  6512. /**
  6513. * Computes a reflection matrix from a plane
  6514. * @param plane defines the reflection plane
  6515. * @returns a new matrix
  6516. */
  6517. Matrix.Reflection = function (plane) {
  6518. var matrix = new Matrix();
  6519. Matrix.ReflectionToRef(plane, matrix);
  6520. return matrix;
  6521. };
  6522. /**
  6523. * Computes a reflection matrix from a plane
  6524. * @param plane defines the reflection plane
  6525. * @param result defines the target matrix
  6526. */
  6527. Matrix.ReflectionToRef = function (plane, result) {
  6528. plane.normalize();
  6529. var x = plane.normal.x;
  6530. var y = plane.normal.y;
  6531. var z = plane.normal.z;
  6532. var temp = -2 * x;
  6533. var temp2 = -2 * y;
  6534. var temp3 = -2 * z;
  6535. result.m[0] = (temp * x) + 1;
  6536. result.m[1] = temp2 * x;
  6537. result.m[2] = temp3 * x;
  6538. result.m[3] = 0.0;
  6539. result.m[4] = temp * y;
  6540. result.m[5] = (temp2 * y) + 1;
  6541. result.m[6] = temp3 * y;
  6542. result.m[7] = 0.0;
  6543. result.m[8] = temp * z;
  6544. result.m[9] = temp2 * z;
  6545. result.m[10] = (temp3 * z) + 1;
  6546. result.m[11] = 0.0;
  6547. result.m[12] = temp * plane.d;
  6548. result.m[13] = temp2 * plane.d;
  6549. result.m[14] = temp3 * plane.d;
  6550. result.m[15] = 1.0;
  6551. result._markAsUpdated();
  6552. };
  6553. /**
  6554. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6555. * @param xaxis defines the value of the 1st axis
  6556. * @param yaxis defines the value of the 2nd axis
  6557. * @param zaxis defines the value of the 3rd axis
  6558. * @param result defines the target matrix
  6559. */
  6560. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6561. result.m[0] = xaxis.x;
  6562. result.m[1] = xaxis.y;
  6563. result.m[2] = xaxis.z;
  6564. result.m[3] = 0.0;
  6565. result.m[4] = yaxis.x;
  6566. result.m[5] = yaxis.y;
  6567. result.m[6] = yaxis.z;
  6568. result.m[7] = 0.0;
  6569. result.m[8] = zaxis.x;
  6570. result.m[9] = zaxis.y;
  6571. result.m[10] = zaxis.z;
  6572. result.m[11] = 0.0;
  6573. result.m[12] = 0.0;
  6574. result.m[13] = 0.0;
  6575. result.m[14] = 0.0;
  6576. result.m[15] = 1.0;
  6577. result._markAsUpdated();
  6578. };
  6579. /**
  6580. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6581. * @param quat defines the quaternion to use
  6582. * @param result defines the target matrix
  6583. */
  6584. Matrix.FromQuaternionToRef = function (quat, result) {
  6585. var xx = quat.x * quat.x;
  6586. var yy = quat.y * quat.y;
  6587. var zz = quat.z * quat.z;
  6588. var xy = quat.x * quat.y;
  6589. var zw = quat.z * quat.w;
  6590. var zx = quat.z * quat.x;
  6591. var yw = quat.y * quat.w;
  6592. var yz = quat.y * quat.z;
  6593. var xw = quat.x * quat.w;
  6594. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6595. result.m[1] = 2.0 * (xy + zw);
  6596. result.m[2] = 2.0 * (zx - yw);
  6597. result.m[3] = 0.0;
  6598. result.m[4] = 2.0 * (xy - zw);
  6599. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6600. result.m[6] = 2.0 * (yz + xw);
  6601. result.m[7] = 0.0;
  6602. result.m[8] = 2.0 * (zx + yw);
  6603. result.m[9] = 2.0 * (yz - xw);
  6604. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6605. result.m[11] = 0.0;
  6606. result.m[12] = 0.0;
  6607. result.m[13] = 0.0;
  6608. result.m[14] = 0.0;
  6609. result.m[15] = 1.0;
  6610. result._markAsUpdated();
  6611. };
  6612. Matrix._tempQuaternion = new Quaternion();
  6613. Matrix._xAxis = Vector3.Zero();
  6614. Matrix._yAxis = Vector3.Zero();
  6615. Matrix._zAxis = Vector3.Zero();
  6616. Matrix._updateFlagSeed = 0;
  6617. Matrix._identityReadOnly = Matrix.Identity();
  6618. return Matrix;
  6619. }());
  6620. BABYLON.Matrix = Matrix;
  6621. var Plane = /** @class */ (function () {
  6622. /**
  6623. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6624. */
  6625. function Plane(a, b, c, d) {
  6626. this.normal = new Vector3(a, b, c);
  6627. this.d = d;
  6628. }
  6629. /**
  6630. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6631. */
  6632. Plane.prototype.asArray = function () {
  6633. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6634. };
  6635. // Methods
  6636. /**
  6637. * Returns a new plane copied from the current Plane.
  6638. */
  6639. Plane.prototype.clone = function () {
  6640. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6641. };
  6642. /**
  6643. * Returns the string "Plane".
  6644. */
  6645. Plane.prototype.getClassName = function () {
  6646. return "Plane";
  6647. };
  6648. /**
  6649. * Returns the Plane hash code.
  6650. */
  6651. Plane.prototype.getHashCode = function () {
  6652. var hash = this.normal.getHashCode();
  6653. hash = (hash * 397) ^ (this.d || 0);
  6654. return hash;
  6655. };
  6656. /**
  6657. * Normalize the current Plane in place.
  6658. * Returns the updated Plane.
  6659. */
  6660. Plane.prototype.normalize = function () {
  6661. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6662. var magnitude = 0.0;
  6663. if (norm !== 0) {
  6664. magnitude = 1.0 / norm;
  6665. }
  6666. this.normal.x *= magnitude;
  6667. this.normal.y *= magnitude;
  6668. this.normal.z *= magnitude;
  6669. this.d *= magnitude;
  6670. return this;
  6671. };
  6672. /**
  6673. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6674. */
  6675. Plane.prototype.transform = function (transformation) {
  6676. var transposedMatrix = Matrix.Transpose(transformation);
  6677. var x = this.normal.x;
  6678. var y = this.normal.y;
  6679. var z = this.normal.z;
  6680. var d = this.d;
  6681. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6682. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6683. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6684. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6685. return new Plane(normalX, normalY, normalZ, finalD);
  6686. };
  6687. /**
  6688. * Returns the dot product (float) of the point coordinates and the plane normal.
  6689. */
  6690. Plane.prototype.dotCoordinate = function (point) {
  6691. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6692. };
  6693. /**
  6694. * Updates the current Plane from the plane defined by the three given points.
  6695. * Returns the updated Plane.
  6696. */
  6697. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6698. var x1 = point2.x - point1.x;
  6699. var y1 = point2.y - point1.y;
  6700. var z1 = point2.z - point1.z;
  6701. var x2 = point3.x - point1.x;
  6702. var y2 = point3.y - point1.y;
  6703. var z2 = point3.z - point1.z;
  6704. var yz = (y1 * z2) - (z1 * y2);
  6705. var xz = (z1 * x2) - (x1 * z2);
  6706. var xy = (x1 * y2) - (y1 * x2);
  6707. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6708. var invPyth;
  6709. if (pyth !== 0) {
  6710. invPyth = 1.0 / pyth;
  6711. }
  6712. else {
  6713. invPyth = 0.0;
  6714. }
  6715. this.normal.x = yz * invPyth;
  6716. this.normal.y = xz * invPyth;
  6717. this.normal.z = xy * invPyth;
  6718. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6719. return this;
  6720. };
  6721. /**
  6722. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6723. */
  6724. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6725. var dot = Vector3.Dot(this.normal, direction);
  6726. return (dot <= epsilon);
  6727. };
  6728. /**
  6729. * Returns the signed distance (float) from the given point to the Plane.
  6730. */
  6731. Plane.prototype.signedDistanceTo = function (point) {
  6732. return Vector3.Dot(point, this.normal) + this.d;
  6733. };
  6734. // Statics
  6735. /**
  6736. * Returns a new Plane from the given array.
  6737. */
  6738. Plane.FromArray = function (array) {
  6739. return new Plane(array[0], array[1], array[2], array[3]);
  6740. };
  6741. /**
  6742. * Returns a new Plane defined by the three given points.
  6743. */
  6744. Plane.FromPoints = function (point1, point2, point3) {
  6745. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6746. result.copyFromPoints(point1, point2, point3);
  6747. return result;
  6748. };
  6749. /**
  6750. * Returns a new Plane the normal vector to this plane at the given origin point.
  6751. * Note : the vector "normal" is updated because normalized.
  6752. */
  6753. Plane.FromPositionAndNormal = function (origin, normal) {
  6754. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6755. normal.normalize();
  6756. result.normal = normal;
  6757. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6758. return result;
  6759. };
  6760. /**
  6761. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6762. */
  6763. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6764. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6765. return Vector3.Dot(point, normal) + d;
  6766. };
  6767. return Plane;
  6768. }());
  6769. BABYLON.Plane = Plane;
  6770. var Viewport = /** @class */ (function () {
  6771. /**
  6772. * Creates a Viewport object located at (x, y) and sized (width, height).
  6773. */
  6774. function Viewport(x, y, width, height) {
  6775. this.x = x;
  6776. this.y = y;
  6777. this.width = width;
  6778. this.height = height;
  6779. }
  6780. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6781. if (renderWidthOrEngine.getRenderWidth) {
  6782. var engine = renderWidthOrEngine;
  6783. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6784. }
  6785. var renderWidth = renderWidthOrEngine;
  6786. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6787. };
  6788. /**
  6789. * Returns a new Viewport copied from the current one.
  6790. */
  6791. Viewport.prototype.clone = function () {
  6792. return new Viewport(this.x, this.y, this.width, this.height);
  6793. };
  6794. return Viewport;
  6795. }());
  6796. BABYLON.Viewport = Viewport;
  6797. var Frustum = /** @class */ (function () {
  6798. function Frustum() {
  6799. }
  6800. /**
  6801. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6802. */
  6803. Frustum.GetPlanes = function (transform) {
  6804. var frustumPlanes = [];
  6805. for (var index = 0; index < 6; index++) {
  6806. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6807. }
  6808. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6809. return frustumPlanes;
  6810. };
  6811. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6812. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6813. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6814. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6815. frustumPlane.d = transform.m[15] + transform.m[14];
  6816. frustumPlane.normalize();
  6817. };
  6818. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6819. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6820. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6821. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6822. frustumPlane.d = transform.m[15] - transform.m[14];
  6823. frustumPlane.normalize();
  6824. };
  6825. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6826. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6827. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6828. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6829. frustumPlane.d = transform.m[15] + transform.m[12];
  6830. frustumPlane.normalize();
  6831. };
  6832. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6833. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6834. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6835. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6836. frustumPlane.d = transform.m[15] - transform.m[12];
  6837. frustumPlane.normalize();
  6838. };
  6839. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6840. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6841. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6842. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6843. frustumPlane.d = transform.m[15] - transform.m[13];
  6844. frustumPlane.normalize();
  6845. };
  6846. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6847. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6848. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6849. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6850. frustumPlane.d = transform.m[15] + transform.m[13];
  6851. frustumPlane.normalize();
  6852. };
  6853. /**
  6854. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6855. */
  6856. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6857. // Near
  6858. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6859. // Far
  6860. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6861. // Left
  6862. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6863. // Right
  6864. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6865. // Top
  6866. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6867. // Bottom
  6868. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6869. };
  6870. return Frustum;
  6871. }());
  6872. BABYLON.Frustum = Frustum;
  6873. /** Defines supported spaces */
  6874. var Space;
  6875. (function (Space) {
  6876. /** Local (object) space */
  6877. Space[Space["LOCAL"] = 0] = "LOCAL";
  6878. /** World space */
  6879. Space[Space["WORLD"] = 1] = "WORLD";
  6880. /** Bone space */
  6881. Space[Space["BONE"] = 2] = "BONE";
  6882. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6883. /** Defines the 3 main axes */
  6884. var Axis = /** @class */ (function () {
  6885. function Axis() {
  6886. }
  6887. /** X axis */
  6888. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6889. /** Y axis */
  6890. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6891. /** Z axis */
  6892. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6893. return Axis;
  6894. }());
  6895. BABYLON.Axis = Axis;
  6896. ;
  6897. var BezierCurve = /** @class */ (function () {
  6898. function BezierCurve() {
  6899. }
  6900. /**
  6901. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6902. */
  6903. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6904. // Extract X (which is equal to time here)
  6905. var f0 = 1 - 3 * x2 + 3 * x1;
  6906. var f1 = 3 * x2 - 6 * x1;
  6907. var f2 = 3 * x1;
  6908. var refinedT = t;
  6909. for (var i = 0; i < 5; i++) {
  6910. var refinedT2 = refinedT * refinedT;
  6911. var refinedT3 = refinedT2 * refinedT;
  6912. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6913. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6914. refinedT -= (x - t) * slope;
  6915. refinedT = Math.min(1, Math.max(0, refinedT));
  6916. }
  6917. // Resolve cubic bezier for the given x
  6918. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6919. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6920. Math.pow(refinedT, 3);
  6921. };
  6922. return BezierCurve;
  6923. }());
  6924. BABYLON.BezierCurve = BezierCurve;
  6925. /**
  6926. * Defines potential orientation for back face culling
  6927. */
  6928. var Orientation;
  6929. (function (Orientation) {
  6930. /**
  6931. * Clockwise
  6932. */
  6933. Orientation[Orientation["CW"] = 0] = "CW";
  6934. /** Counter clockwise */
  6935. Orientation[Orientation["CCW"] = 1] = "CCW";
  6936. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6937. /**
  6938. * Defines angle representation
  6939. */
  6940. var Angle = /** @class */ (function () {
  6941. /**
  6942. * Creates an Angle object of "radians" radians (float).
  6943. */
  6944. function Angle(radians) {
  6945. this._radians = radians;
  6946. if (this._radians < 0.0)
  6947. this._radians += (2.0 * Math.PI);
  6948. }
  6949. /**
  6950. * Get value in degrees
  6951. * @returns the Angle value in degrees (float)
  6952. */
  6953. Angle.prototype.degrees = function () {
  6954. return this._radians * 180.0 / Math.PI;
  6955. };
  6956. /**
  6957. * Get value in radians
  6958. * @returns the Angle value in radians (float)
  6959. */
  6960. Angle.prototype.radians = function () {
  6961. return this._radians;
  6962. };
  6963. /**
  6964. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6965. * @param a defines first vector
  6966. * @param b defines second vector
  6967. * @returns a new Angle
  6968. */
  6969. Angle.BetweenTwoPoints = function (a, b) {
  6970. var delta = b.subtract(a);
  6971. var theta = Math.atan2(delta.y, delta.x);
  6972. return new Angle(theta);
  6973. };
  6974. /**
  6975. * Gets a new Angle object from the given float in radians
  6976. * @param radians defines the angle value in radians
  6977. * @returns a new Angle
  6978. */
  6979. Angle.FromRadians = function (radians) {
  6980. return new Angle(radians);
  6981. };
  6982. /**
  6983. * Gets a new Angle object from the given float in degrees
  6984. * @param degrees defines the angle value in degrees
  6985. * @returns a new Angle
  6986. */
  6987. Angle.FromDegrees = function (degrees) {
  6988. return new Angle(degrees * Math.PI / 180.0);
  6989. };
  6990. return Angle;
  6991. }());
  6992. BABYLON.Angle = Angle;
  6993. var Arc2 = /** @class */ (function () {
  6994. /**
  6995. * Creates an Arc object from the three given points : start, middle and end.
  6996. */
  6997. function Arc2(startPoint, midPoint, endPoint) {
  6998. this.startPoint = startPoint;
  6999. this.midPoint = midPoint;
  7000. this.endPoint = endPoint;
  7001. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7002. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7003. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7004. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7005. 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);
  7006. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7007. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7008. var a1 = this.startAngle.degrees();
  7009. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7010. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7011. // angles correction
  7012. if (a2 - a1 > +180.0)
  7013. a2 -= 360.0;
  7014. if (a2 - a1 < -180.0)
  7015. a2 += 360.0;
  7016. if (a3 - a2 > +180.0)
  7017. a3 -= 360.0;
  7018. if (a3 - a2 < -180.0)
  7019. a3 += 360.0;
  7020. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7021. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7022. }
  7023. return Arc2;
  7024. }());
  7025. BABYLON.Arc2 = Arc2;
  7026. var Path2 = /** @class */ (function () {
  7027. /**
  7028. * Creates a Path2 object from the starting 2D coordinates x and y.
  7029. */
  7030. function Path2(x, y) {
  7031. this._points = new Array();
  7032. this._length = 0.0;
  7033. this.closed = false;
  7034. this._points.push(new Vector2(x, y));
  7035. }
  7036. /**
  7037. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7038. * Returns the updated Path2.
  7039. */
  7040. Path2.prototype.addLineTo = function (x, y) {
  7041. if (this.closed) {
  7042. return this;
  7043. }
  7044. var newPoint = new Vector2(x, y);
  7045. var previousPoint = this._points[this._points.length - 1];
  7046. this._points.push(newPoint);
  7047. this._length += newPoint.subtract(previousPoint).length();
  7048. return this;
  7049. };
  7050. /**
  7051. * 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.
  7052. * Returns the updated Path2.
  7053. */
  7054. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7055. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7056. if (this.closed) {
  7057. return this;
  7058. }
  7059. var startPoint = this._points[this._points.length - 1];
  7060. var midPoint = new Vector2(midX, midY);
  7061. var endPoint = new Vector2(endX, endY);
  7062. var arc = new Arc2(startPoint, midPoint, endPoint);
  7063. var increment = arc.angle.radians() / numberOfSegments;
  7064. if (arc.orientation === Orientation.CW)
  7065. increment *= -1;
  7066. var currentAngle = arc.startAngle.radians() + increment;
  7067. for (var i = 0; i < numberOfSegments; i++) {
  7068. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7069. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7070. this.addLineTo(x, y);
  7071. currentAngle += increment;
  7072. }
  7073. return this;
  7074. };
  7075. /**
  7076. * Closes the Path2.
  7077. * Returns the Path2.
  7078. */
  7079. Path2.prototype.close = function () {
  7080. this.closed = true;
  7081. return this;
  7082. };
  7083. /**
  7084. * Returns the Path2 total length (float).
  7085. */
  7086. Path2.prototype.length = function () {
  7087. var result = this._length;
  7088. if (!this.closed) {
  7089. var lastPoint = this._points[this._points.length - 1];
  7090. var firstPoint = this._points[0];
  7091. result += (firstPoint.subtract(lastPoint).length());
  7092. }
  7093. return result;
  7094. };
  7095. /**
  7096. * Returns the Path2 internal array of points.
  7097. */
  7098. Path2.prototype.getPoints = function () {
  7099. return this._points;
  7100. };
  7101. /**
  7102. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7103. */
  7104. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7105. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7106. return Vector2.Zero();
  7107. }
  7108. var lengthPosition = normalizedLengthPosition * this.length();
  7109. var previousOffset = 0;
  7110. for (var i = 0; i < this._points.length; i++) {
  7111. var j = (i + 1) % this._points.length;
  7112. var a = this._points[i];
  7113. var b = this._points[j];
  7114. var bToA = b.subtract(a);
  7115. var nextOffset = (bToA.length() + previousOffset);
  7116. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7117. var dir = bToA.normalize();
  7118. var localOffset = lengthPosition - previousOffset;
  7119. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7120. }
  7121. previousOffset = nextOffset;
  7122. }
  7123. return Vector2.Zero();
  7124. };
  7125. /**
  7126. * Returns a new Path2 starting at the coordinates (x, y).
  7127. */
  7128. Path2.StartingAt = function (x, y) {
  7129. return new Path2(x, y);
  7130. };
  7131. return Path2;
  7132. }());
  7133. BABYLON.Path2 = Path2;
  7134. var Path3D = /** @class */ (function () {
  7135. /**
  7136. * new Path3D(path, normal, raw)
  7137. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7138. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7139. * path : an array of Vector3, the curve axis of the Path3D
  7140. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7141. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7142. */
  7143. function Path3D(path, firstNormal, raw) {
  7144. if (firstNormal === void 0) { firstNormal = null; }
  7145. this.path = path;
  7146. this._curve = new Array();
  7147. this._distances = new Array();
  7148. this._tangents = new Array();
  7149. this._normals = new Array();
  7150. this._binormals = new Array();
  7151. for (var p = 0; p < path.length; p++) {
  7152. this._curve[p] = path[p].clone(); // hard copy
  7153. }
  7154. this._raw = raw || false;
  7155. this._compute(firstNormal);
  7156. }
  7157. /**
  7158. * Returns the Path3D array of successive Vector3 designing its curve.
  7159. */
  7160. Path3D.prototype.getCurve = function () {
  7161. return this._curve;
  7162. };
  7163. /**
  7164. * Returns an array populated with tangent vectors on each Path3D curve point.
  7165. */
  7166. Path3D.prototype.getTangents = function () {
  7167. return this._tangents;
  7168. };
  7169. /**
  7170. * Returns an array populated with normal vectors on each Path3D curve point.
  7171. */
  7172. Path3D.prototype.getNormals = function () {
  7173. return this._normals;
  7174. };
  7175. /**
  7176. * Returns an array populated with binormal vectors on each Path3D curve point.
  7177. */
  7178. Path3D.prototype.getBinormals = function () {
  7179. return this._binormals;
  7180. };
  7181. /**
  7182. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7183. */
  7184. Path3D.prototype.getDistances = function () {
  7185. return this._distances;
  7186. };
  7187. /**
  7188. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7189. * Returns the same object updated.
  7190. */
  7191. Path3D.prototype.update = function (path, firstNormal) {
  7192. if (firstNormal === void 0) { firstNormal = null; }
  7193. for (var p = 0; p < path.length; p++) {
  7194. this._curve[p].x = path[p].x;
  7195. this._curve[p].y = path[p].y;
  7196. this._curve[p].z = path[p].z;
  7197. }
  7198. this._compute(firstNormal);
  7199. return this;
  7200. };
  7201. // private function compute() : computes tangents, normals and binormals
  7202. Path3D.prototype._compute = function (firstNormal) {
  7203. var l = this._curve.length;
  7204. // first and last tangents
  7205. this._tangents[0] = this._getFirstNonNullVector(0);
  7206. if (!this._raw) {
  7207. this._tangents[0].normalize();
  7208. }
  7209. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7210. if (!this._raw) {
  7211. this._tangents[l - 1].normalize();
  7212. }
  7213. // normals and binormals at first point : arbitrary vector with _normalVector()
  7214. var tg0 = this._tangents[0];
  7215. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7216. this._normals[0] = pp0;
  7217. if (!this._raw) {
  7218. this._normals[0].normalize();
  7219. }
  7220. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7221. if (!this._raw) {
  7222. this._binormals[0].normalize();
  7223. }
  7224. this._distances[0] = 0.0;
  7225. // normals and binormals : next points
  7226. var prev; // previous vector (segment)
  7227. var cur; // current vector (segment)
  7228. var curTang; // current tangent
  7229. // previous normal
  7230. var prevBinor; // previous binormal
  7231. for (var i = 1; i < l; i++) {
  7232. // tangents
  7233. prev = this._getLastNonNullVector(i);
  7234. if (i < l - 1) {
  7235. cur = this._getFirstNonNullVector(i);
  7236. this._tangents[i] = prev.add(cur);
  7237. this._tangents[i].normalize();
  7238. }
  7239. this._distances[i] = this._distances[i - 1] + prev.length();
  7240. // normals and binormals
  7241. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7242. curTang = this._tangents[i];
  7243. prevBinor = this._binormals[i - 1];
  7244. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7245. if (!this._raw) {
  7246. this._normals[i].normalize();
  7247. }
  7248. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7249. if (!this._raw) {
  7250. this._binormals[i].normalize();
  7251. }
  7252. }
  7253. };
  7254. // private function getFirstNonNullVector(index)
  7255. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7256. Path3D.prototype._getFirstNonNullVector = function (index) {
  7257. var i = 1;
  7258. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7259. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7260. i++;
  7261. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7262. }
  7263. return nNVector;
  7264. };
  7265. // private function getLastNonNullVector(index)
  7266. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7267. Path3D.prototype._getLastNonNullVector = function (index) {
  7268. var i = 1;
  7269. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7270. while (nLVector.length() === 0 && index > i + 1) {
  7271. i++;
  7272. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7273. }
  7274. return nLVector;
  7275. };
  7276. // private function normalVector(v0, vt, va) :
  7277. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7278. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7279. Path3D.prototype._normalVector = function (v0, vt, va) {
  7280. var normal0;
  7281. var tgl = vt.length();
  7282. if (tgl === 0.0) {
  7283. tgl = 1.0;
  7284. }
  7285. if (va === undefined || va === null) {
  7286. var point;
  7287. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7288. point = new Vector3(0.0, -1.0, 0.0);
  7289. }
  7290. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7291. point = new Vector3(1.0, 0.0, 0.0);
  7292. }
  7293. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7294. point = new Vector3(0.0, 0.0, 1.0);
  7295. }
  7296. else {
  7297. point = Vector3.Zero();
  7298. }
  7299. normal0 = Vector3.Cross(vt, point);
  7300. }
  7301. else {
  7302. normal0 = Vector3.Cross(vt, va);
  7303. Vector3.CrossToRef(normal0, vt, normal0);
  7304. }
  7305. normal0.normalize();
  7306. return normal0;
  7307. };
  7308. return Path3D;
  7309. }());
  7310. BABYLON.Path3D = Path3D;
  7311. var Curve3 = /** @class */ (function () {
  7312. /**
  7313. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7314. * A Curve3 is designed from a series of successive Vector3.
  7315. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7316. */
  7317. function Curve3(points) {
  7318. this._length = 0.0;
  7319. this._points = points;
  7320. this._length = this._computeLength(points);
  7321. }
  7322. /**
  7323. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7324. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7325. * @param v1 (Vector3) the control point
  7326. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7327. * @param nbPoints (integer) the wanted number of points in the curve
  7328. */
  7329. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7330. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7331. var bez = new Array();
  7332. var equation = function (t, val0, val1, val2) {
  7333. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7334. return res;
  7335. };
  7336. for (var i = 0; i <= nbPoints; i++) {
  7337. 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)));
  7338. }
  7339. return new Curve3(bez);
  7340. };
  7341. /**
  7342. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7343. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7344. * @param v1 (Vector3) the first control point
  7345. * @param v2 (Vector3) the second control point
  7346. * @param v3 (Vector3) the end point of the Cubic Bezier
  7347. * @param nbPoints (integer) the wanted number of points in the curve
  7348. */
  7349. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7350. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7351. var bez = new Array();
  7352. var equation = function (t, val0, val1, val2, val3) {
  7353. 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;
  7354. return res;
  7355. };
  7356. for (var i = 0; i <= nbPoints; i++) {
  7357. 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)));
  7358. }
  7359. return new Curve3(bez);
  7360. };
  7361. /**
  7362. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7363. * @param p1 (Vector3) the origin point of the Hermite Spline
  7364. * @param t1 (Vector3) the tangent vector at the origin point
  7365. * @param p2 (Vector3) the end point of the Hermite Spline
  7366. * @param t2 (Vector3) the tangent vector at the end point
  7367. * @param nbPoints (integer) the wanted number of points in the curve
  7368. */
  7369. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7370. var hermite = new Array();
  7371. var step = 1.0 / nbPoints;
  7372. for (var i = 0; i <= nbPoints; i++) {
  7373. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7374. }
  7375. return new Curve3(hermite);
  7376. };
  7377. /**
  7378. * Returns a Curve3 object along a CatmullRom Spline curve :
  7379. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7380. * @param nbPoints (integer) the wanted number of points between each curve control points
  7381. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7382. */
  7383. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7384. var catmullRom = new Array();
  7385. var step = 1.0 / nbPoints;
  7386. var amount = 0.0;
  7387. if (closed) {
  7388. var pointsCount = points.length;
  7389. for (var i = 0; i < pointsCount; i++) {
  7390. amount = 0;
  7391. for (var c = 0; c < nbPoints; c++) {
  7392. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7393. amount += step;
  7394. }
  7395. }
  7396. catmullRom.push(catmullRom[0]);
  7397. }
  7398. else {
  7399. var totalPoints = new Array();
  7400. totalPoints.push(points[0].clone());
  7401. Array.prototype.push.apply(totalPoints, points);
  7402. totalPoints.push(points[points.length - 1].clone());
  7403. for (var i = 0; i < totalPoints.length - 3; i++) {
  7404. amount = 0;
  7405. for (var c = 0; c < nbPoints; c++) {
  7406. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7407. amount += step;
  7408. }
  7409. }
  7410. i--;
  7411. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7412. }
  7413. return new Curve3(catmullRom);
  7414. };
  7415. /**
  7416. * Returns the Curve3 stored array of successive Vector3
  7417. */
  7418. Curve3.prototype.getPoints = function () {
  7419. return this._points;
  7420. };
  7421. /**
  7422. * Returns the computed length (float) of the curve.
  7423. */
  7424. Curve3.prototype.length = function () {
  7425. return this._length;
  7426. };
  7427. /**
  7428. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7429. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7430. * curveA and curveB keep unchanged.
  7431. */
  7432. Curve3.prototype.continue = function (curve) {
  7433. var lastPoint = this._points[this._points.length - 1];
  7434. var continuedPoints = this._points.slice();
  7435. var curvePoints = curve.getPoints();
  7436. for (var i = 1; i < curvePoints.length; i++) {
  7437. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7438. }
  7439. var continuedCurve = new Curve3(continuedPoints);
  7440. return continuedCurve;
  7441. };
  7442. Curve3.prototype._computeLength = function (path) {
  7443. var l = 0;
  7444. for (var i = 1; i < path.length; i++) {
  7445. l += (path[i].subtract(path[i - 1])).length();
  7446. }
  7447. return l;
  7448. };
  7449. return Curve3;
  7450. }());
  7451. BABYLON.Curve3 = Curve3;
  7452. // Vertex formats
  7453. var PositionNormalVertex = /** @class */ (function () {
  7454. function PositionNormalVertex(position, normal) {
  7455. if (position === void 0) { position = Vector3.Zero(); }
  7456. if (normal === void 0) { normal = Vector3.Up(); }
  7457. this.position = position;
  7458. this.normal = normal;
  7459. }
  7460. PositionNormalVertex.prototype.clone = function () {
  7461. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7462. };
  7463. return PositionNormalVertex;
  7464. }());
  7465. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7466. var PositionNormalTextureVertex = /** @class */ (function () {
  7467. function PositionNormalTextureVertex(position, normal, uv) {
  7468. if (position === void 0) { position = Vector3.Zero(); }
  7469. if (normal === void 0) { normal = Vector3.Up(); }
  7470. if (uv === void 0) { uv = Vector2.Zero(); }
  7471. this.position = position;
  7472. this.normal = normal;
  7473. this.uv = uv;
  7474. }
  7475. PositionNormalTextureVertex.prototype.clone = function () {
  7476. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7477. };
  7478. return PositionNormalTextureVertex;
  7479. }());
  7480. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7481. // Temporary pre-allocated objects for engine internal use
  7482. // usage in any internal function :
  7483. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7484. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7485. var Tmp = /** @class */ (function () {
  7486. function Tmp() {
  7487. }
  7488. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7489. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7490. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7491. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7492. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7493. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7494. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7495. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7496. Matrix.Zero(), Matrix.Zero(),
  7497. Matrix.Zero(), Matrix.Zero(),
  7498. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7499. return Tmp;
  7500. }());
  7501. BABYLON.Tmp = Tmp;
  7502. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7503. var MathTmp = /** @class */ (function () {
  7504. function MathTmp() {
  7505. }
  7506. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7507. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7508. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7509. return MathTmp;
  7510. }());
  7511. })(BABYLON || (BABYLON = {}));
  7512. //# sourceMappingURL=babylon.math.js.map
  7513. var BABYLON;
  7514. (function (BABYLON) {
  7515. var Scalar = /** @class */ (function () {
  7516. function Scalar() {
  7517. }
  7518. /**
  7519. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7520. */
  7521. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7522. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7523. var num = a - b;
  7524. return -epsilon <= num && num <= epsilon;
  7525. };
  7526. /**
  7527. * Returns a string : the upper case translation of the number i to hexadecimal.
  7528. */
  7529. Scalar.ToHex = function (i) {
  7530. var str = i.toString(16);
  7531. if (i <= 15) {
  7532. return ("0" + str).toUpperCase();
  7533. }
  7534. return str.toUpperCase();
  7535. };
  7536. /**
  7537. * Returns -1 if value is negative and +1 is value is positive.
  7538. * Returns the value itself if it's equal to zero.
  7539. */
  7540. Scalar.Sign = function (value) {
  7541. value = +value; // convert to a number
  7542. if (value === 0 || isNaN(value))
  7543. return value;
  7544. return value > 0 ? 1 : -1;
  7545. };
  7546. /**
  7547. * Returns the value itself if it's between min and max.
  7548. * Returns min if the value is lower than min.
  7549. * Returns max if the value is greater than max.
  7550. */
  7551. Scalar.Clamp = function (value, min, max) {
  7552. if (min === void 0) { min = 0; }
  7553. if (max === void 0) { max = 1; }
  7554. return Math.min(max, Math.max(min, value));
  7555. };
  7556. /**
  7557. * Returns the log2 of value.
  7558. */
  7559. Scalar.Log2 = function (value) {
  7560. return Math.log(value) * Math.LOG2E;
  7561. };
  7562. /**
  7563. * Loops the value, so that it is never larger than length and never smaller than 0.
  7564. *
  7565. * This is similar to the modulo operator but it works with floating point numbers.
  7566. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7567. * With t = 5 and length = 2.5, the result would be 0.0.
  7568. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7569. */
  7570. Scalar.Repeat = function (value, length) {
  7571. return value - Math.floor(value / length) * length;
  7572. };
  7573. /**
  7574. * Normalize the value between 0.0 and 1.0 using min and max values
  7575. */
  7576. Scalar.Normalize = function (value, min, max) {
  7577. return (value - min) / (max - min);
  7578. };
  7579. /**
  7580. * Denormalize the value from 0.0 and 1.0 using min and max values
  7581. */
  7582. Scalar.Denormalize = function (normalized, min, max) {
  7583. return (normalized * (max - min) + min);
  7584. };
  7585. /**
  7586. * Calculates the shortest difference between two given angles given in degrees.
  7587. */
  7588. Scalar.DeltaAngle = function (current, target) {
  7589. var num = Scalar.Repeat(target - current, 360.0);
  7590. if (num > 180.0) {
  7591. num -= 360.0;
  7592. }
  7593. return num;
  7594. };
  7595. /**
  7596. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7597. *
  7598. * The returned value will move back and forth between 0 and length
  7599. */
  7600. Scalar.PingPong = function (tx, length) {
  7601. var t = Scalar.Repeat(tx, length * 2.0);
  7602. return length - Math.abs(t - length);
  7603. };
  7604. /**
  7605. * Interpolates between min and max with smoothing at the limits.
  7606. *
  7607. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7608. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7609. */
  7610. Scalar.SmoothStep = function (from, to, tx) {
  7611. var t = Scalar.Clamp(tx);
  7612. t = -2.0 * t * t * t + 3.0 * t * t;
  7613. return to * t + from * (1.0 - t);
  7614. };
  7615. /**
  7616. * Moves a value current towards target.
  7617. *
  7618. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7619. * Negative values of maxDelta pushes the value away from target.
  7620. */
  7621. Scalar.MoveTowards = function (current, target, maxDelta) {
  7622. var result = 0;
  7623. if (Math.abs(target - current) <= maxDelta) {
  7624. result = target;
  7625. }
  7626. else {
  7627. result = current + Scalar.Sign(target - current) * maxDelta;
  7628. }
  7629. return result;
  7630. };
  7631. /**
  7632. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7633. *
  7634. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7635. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7636. */
  7637. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7638. var num = Scalar.DeltaAngle(current, target);
  7639. var result = 0;
  7640. if (-maxDelta < num && num < maxDelta) {
  7641. result = target;
  7642. }
  7643. else {
  7644. target = current + num;
  7645. result = Scalar.MoveTowards(current, target, maxDelta);
  7646. }
  7647. return result;
  7648. };
  7649. /**
  7650. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7651. */
  7652. Scalar.Lerp = function (start, end, amount) {
  7653. return start + ((end - start) * amount);
  7654. };
  7655. /**
  7656. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7657. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7658. */
  7659. Scalar.LerpAngle = function (start, end, amount) {
  7660. var num = Scalar.Repeat(end - start, 360.0);
  7661. if (num > 180.0) {
  7662. num -= 360.0;
  7663. }
  7664. return start + num * Scalar.Clamp(amount);
  7665. };
  7666. /**
  7667. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7668. */
  7669. Scalar.InverseLerp = function (a, b, value) {
  7670. var result = 0;
  7671. if (a != b) {
  7672. result = Scalar.Clamp((value - a) / (b - a));
  7673. }
  7674. else {
  7675. result = 0.0;
  7676. }
  7677. return result;
  7678. };
  7679. /**
  7680. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7681. */
  7682. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7683. var squared = amount * amount;
  7684. var cubed = amount * squared;
  7685. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7686. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7687. var part3 = (cubed - (2.0 * squared)) + amount;
  7688. var part4 = cubed - squared;
  7689. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7690. };
  7691. /**
  7692. * Returns a random float number between and min and max values
  7693. */
  7694. Scalar.RandomRange = function (min, max) {
  7695. if (min === max)
  7696. return min;
  7697. return ((Math.random() * (max - min)) + min);
  7698. };
  7699. /**
  7700. * This function returns percentage of a number in a given range.
  7701. *
  7702. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7703. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7704. */
  7705. Scalar.RangeToPercent = function (number, min, max) {
  7706. return ((number - min) / (max - min));
  7707. };
  7708. /**
  7709. * This function returns number that corresponds to the percentage in a given range.
  7710. *
  7711. * PercentToRange(0.34,0,100) will return 34.
  7712. */
  7713. Scalar.PercentToRange = function (percent, min, max) {
  7714. return ((max - min) * percent + min);
  7715. };
  7716. /**
  7717. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7718. * @param angle The angle to normalize in radian.
  7719. * @return The converted angle.
  7720. */
  7721. Scalar.NormalizeRadians = function (angle) {
  7722. // More precise but slower version kept for reference.
  7723. // angle = angle % Tools.TwoPi;
  7724. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7725. //if (angle > Math.PI) {
  7726. // angle -= Tools.TwoPi;
  7727. //}
  7728. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7729. return angle;
  7730. };
  7731. /**
  7732. * Two pi constants convenient for computation.
  7733. */
  7734. Scalar.TwoPi = Math.PI * 2;
  7735. return Scalar;
  7736. }());
  7737. BABYLON.Scalar = Scalar;
  7738. })(BABYLON || (BABYLON = {}));
  7739. //# sourceMappingURL=babylon.math.scalar.js.map
  7740. //# sourceMappingURL=babylon.mixins.js.map
  7741. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7742. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7743. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7744. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7745. //# sourceMappingURL=babylon.webgl2.js.map
  7746. var BABYLON;
  7747. (function (BABYLON) {
  7748. var __decoratorInitialStore = {};
  7749. var __mergedStore = {};
  7750. var _copySource = function (creationFunction, source, instanciate) {
  7751. var destination = creationFunction();
  7752. // Tags
  7753. if (BABYLON.Tags) {
  7754. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7755. }
  7756. var classStore = getMergedStore(destination);
  7757. // Properties
  7758. for (var property in classStore) {
  7759. var propertyDescriptor = classStore[property];
  7760. var sourceProperty = source[property];
  7761. var propertyType = propertyDescriptor.type;
  7762. if (sourceProperty !== undefined && sourceProperty !== null) {
  7763. switch (propertyType) {
  7764. case 0: // Value
  7765. case 6: // Mesh reference
  7766. case 11: // Camera reference
  7767. destination[property] = sourceProperty;
  7768. break;
  7769. case 1: // Texture
  7770. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7771. break;
  7772. case 2: // Color3
  7773. case 3: // FresnelParameters
  7774. case 4: // Vector2
  7775. case 5: // Vector3
  7776. case 7: // Color Curves
  7777. case 10: // Quaternion
  7778. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7779. break;
  7780. }
  7781. }
  7782. }
  7783. return destination;
  7784. };
  7785. function getDirectStore(target) {
  7786. var classKey = target.getClassName();
  7787. if (!__decoratorInitialStore[classKey]) {
  7788. __decoratorInitialStore[classKey] = {};
  7789. }
  7790. return __decoratorInitialStore[classKey];
  7791. }
  7792. /**
  7793. * Return the list of properties flagged as serializable
  7794. * @param target: host object
  7795. */
  7796. function getMergedStore(target) {
  7797. var classKey = target.getClassName();
  7798. if (__mergedStore[classKey]) {
  7799. return __mergedStore[classKey];
  7800. }
  7801. __mergedStore[classKey] = {};
  7802. var store = __mergedStore[classKey];
  7803. var currentTarget = target;
  7804. var currentKey = classKey;
  7805. while (currentKey) {
  7806. var initialStore = __decoratorInitialStore[currentKey];
  7807. for (var property in initialStore) {
  7808. store[property] = initialStore[property];
  7809. }
  7810. var parent_1 = void 0;
  7811. var done = false;
  7812. do {
  7813. parent_1 = Object.getPrototypeOf(currentTarget);
  7814. if (!parent_1.getClassName) {
  7815. done = true;
  7816. break;
  7817. }
  7818. if (parent_1.getClassName() !== currentKey) {
  7819. break;
  7820. }
  7821. currentTarget = parent_1;
  7822. } while (parent_1);
  7823. if (done) {
  7824. break;
  7825. }
  7826. currentKey = parent_1.getClassName();
  7827. currentTarget = parent_1;
  7828. }
  7829. return store;
  7830. }
  7831. function generateSerializableMember(type, sourceName) {
  7832. return function (target, propertyKey) {
  7833. var classStore = getDirectStore(target);
  7834. if (!classStore[propertyKey]) {
  7835. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7836. }
  7837. };
  7838. }
  7839. function generateExpandMember(setCallback, targetKey) {
  7840. if (targetKey === void 0) { targetKey = null; }
  7841. return function (target, propertyKey) {
  7842. var key = targetKey || ("_" + propertyKey);
  7843. Object.defineProperty(target, propertyKey, {
  7844. get: function () {
  7845. return this[key];
  7846. },
  7847. set: function (value) {
  7848. if (this[key] === value) {
  7849. return;
  7850. }
  7851. this[key] = value;
  7852. target[setCallback].apply(this);
  7853. },
  7854. enumerable: true,
  7855. configurable: true
  7856. });
  7857. };
  7858. }
  7859. function expandToProperty(callback, targetKey) {
  7860. if (targetKey === void 0) { targetKey = null; }
  7861. return generateExpandMember(callback, targetKey);
  7862. }
  7863. BABYLON.expandToProperty = expandToProperty;
  7864. function serialize(sourceName) {
  7865. return generateSerializableMember(0, sourceName); // value member
  7866. }
  7867. BABYLON.serialize = serialize;
  7868. function serializeAsTexture(sourceName) {
  7869. return generateSerializableMember(1, sourceName); // texture member
  7870. }
  7871. BABYLON.serializeAsTexture = serializeAsTexture;
  7872. function serializeAsColor3(sourceName) {
  7873. return generateSerializableMember(2, sourceName); // color3 member
  7874. }
  7875. BABYLON.serializeAsColor3 = serializeAsColor3;
  7876. function serializeAsFresnelParameters(sourceName) {
  7877. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7878. }
  7879. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7880. function serializeAsVector2(sourceName) {
  7881. return generateSerializableMember(4, sourceName); // vector2 member
  7882. }
  7883. BABYLON.serializeAsVector2 = serializeAsVector2;
  7884. function serializeAsVector3(sourceName) {
  7885. return generateSerializableMember(5, sourceName); // vector3 member
  7886. }
  7887. BABYLON.serializeAsVector3 = serializeAsVector3;
  7888. function serializeAsMeshReference(sourceName) {
  7889. return generateSerializableMember(6, sourceName); // mesh reference member
  7890. }
  7891. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7892. function serializeAsColorCurves(sourceName) {
  7893. return generateSerializableMember(7, sourceName); // color curves
  7894. }
  7895. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7896. function serializeAsColor4(sourceName) {
  7897. return generateSerializableMember(8, sourceName); // color 4
  7898. }
  7899. BABYLON.serializeAsColor4 = serializeAsColor4;
  7900. function serializeAsImageProcessingConfiguration(sourceName) {
  7901. return generateSerializableMember(9, sourceName); // image processing
  7902. }
  7903. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7904. function serializeAsQuaternion(sourceName) {
  7905. return generateSerializableMember(10, sourceName); // quaternion member
  7906. }
  7907. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7908. /**
  7909. * Decorator used to define property that can be serialized as reference to a camera
  7910. * @param sourceName defines the name of the property to decorate
  7911. */
  7912. function serializeAsCameraReference(sourceName) {
  7913. return generateSerializableMember(11, sourceName); // camera reference member
  7914. }
  7915. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7916. var SerializationHelper = /** @class */ (function () {
  7917. function SerializationHelper() {
  7918. }
  7919. SerializationHelper.Serialize = function (entity, serializationObject) {
  7920. if (!serializationObject) {
  7921. serializationObject = {};
  7922. }
  7923. // Tags
  7924. if (BABYLON.Tags) {
  7925. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7926. }
  7927. var serializedProperties = getMergedStore(entity);
  7928. // Properties
  7929. for (var property in serializedProperties) {
  7930. var propertyDescriptor = serializedProperties[property];
  7931. var targetPropertyName = propertyDescriptor.sourceName || property;
  7932. var propertyType = propertyDescriptor.type;
  7933. var sourceProperty = entity[property];
  7934. if (sourceProperty !== undefined && sourceProperty !== null) {
  7935. switch (propertyType) {
  7936. case 0: // Value
  7937. serializationObject[targetPropertyName] = sourceProperty;
  7938. break;
  7939. case 1: // Texture
  7940. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7941. break;
  7942. case 2: // Color3
  7943. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7944. break;
  7945. case 3: // FresnelParameters
  7946. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7947. break;
  7948. case 4: // Vector2
  7949. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7950. break;
  7951. case 5: // Vector3
  7952. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7953. break;
  7954. case 6: // Mesh reference
  7955. serializationObject[targetPropertyName] = sourceProperty.id;
  7956. break;
  7957. case 7: // Color Curves
  7958. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7959. break;
  7960. case 8: // Color 4
  7961. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7962. break;
  7963. case 9: // Image Processing
  7964. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7965. break;
  7966. case 10: // Quaternion
  7967. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7968. break;
  7969. case 11: // Camera reference
  7970. serializationObject[targetPropertyName] = sourceProperty.id;
  7971. break;
  7972. }
  7973. }
  7974. }
  7975. return serializationObject;
  7976. };
  7977. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7978. if (rootUrl === void 0) { rootUrl = null; }
  7979. var destination = creationFunction();
  7980. if (!rootUrl) {
  7981. rootUrl = "";
  7982. }
  7983. // Tags
  7984. if (BABYLON.Tags) {
  7985. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7986. }
  7987. var classStore = getMergedStore(destination);
  7988. // Properties
  7989. for (var property in classStore) {
  7990. var propertyDescriptor = classStore[property];
  7991. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7992. var propertyType = propertyDescriptor.type;
  7993. if (sourceProperty !== undefined && sourceProperty !== null) {
  7994. var dest = destination;
  7995. switch (propertyType) {
  7996. case 0: // Value
  7997. dest[property] = sourceProperty;
  7998. break;
  7999. case 1: // Texture
  8000. if (scene) {
  8001. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8002. }
  8003. break;
  8004. case 2: // Color3
  8005. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8006. break;
  8007. case 3: // FresnelParameters
  8008. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8009. break;
  8010. case 4: // Vector2
  8011. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8012. break;
  8013. case 5: // Vector3
  8014. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8015. break;
  8016. case 6: // Mesh reference
  8017. if (scene) {
  8018. dest[property] = scene.getLastMeshByID(sourceProperty);
  8019. }
  8020. break;
  8021. case 7: // Color Curves
  8022. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8023. break;
  8024. case 8: // Color 4
  8025. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8026. break;
  8027. case 9: // Image Processing
  8028. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8029. break;
  8030. case 10: // Quaternion
  8031. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8032. break;
  8033. case 11: // Camera reference
  8034. if (scene) {
  8035. dest[property] = scene.getCameraByID(sourceProperty);
  8036. }
  8037. break;
  8038. }
  8039. }
  8040. }
  8041. return destination;
  8042. };
  8043. SerializationHelper.Clone = function (creationFunction, source) {
  8044. return _copySource(creationFunction, source, false);
  8045. };
  8046. SerializationHelper.Instanciate = function (creationFunction, source) {
  8047. return _copySource(creationFunction, source, true);
  8048. };
  8049. return SerializationHelper;
  8050. }());
  8051. BABYLON.SerializationHelper = SerializationHelper;
  8052. })(BABYLON || (BABYLON = {}));
  8053. //# sourceMappingURL=babylon.decorators.js.map
  8054. var BABYLON;
  8055. (function (BABYLON) {
  8056. /**
  8057. * Wrapper class for promise with external resolve and reject.
  8058. */
  8059. var Deferred = /** @class */ (function () {
  8060. /**
  8061. * Constructor for this deferred object.
  8062. */
  8063. function Deferred() {
  8064. var _this = this;
  8065. this.promise = new Promise(function (resolve, reject) {
  8066. _this._resolve = resolve;
  8067. _this._reject = reject;
  8068. });
  8069. }
  8070. Object.defineProperty(Deferred.prototype, "resolve", {
  8071. /**
  8072. * The resolve method of the promise associated with this deferred object.
  8073. */
  8074. get: function () {
  8075. return this._resolve;
  8076. },
  8077. enumerable: true,
  8078. configurable: true
  8079. });
  8080. Object.defineProperty(Deferred.prototype, "reject", {
  8081. /**
  8082. * The reject method of the promise associated with this deferred object.
  8083. */
  8084. get: function () {
  8085. return this._reject;
  8086. },
  8087. enumerable: true,
  8088. configurable: true
  8089. });
  8090. return Deferred;
  8091. }());
  8092. BABYLON.Deferred = Deferred;
  8093. })(BABYLON || (BABYLON = {}));
  8094. //# sourceMappingURL=babylon.deferred.js.map
  8095. var BABYLON;
  8096. (function (BABYLON) {
  8097. /**
  8098. * A class serves as a medium between the observable and its observers
  8099. */
  8100. var EventState = /** @class */ (function () {
  8101. /**
  8102. * Create a new EventState
  8103. * @param mask defines the mask associated with this state
  8104. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8105. * @param target defines the original target of the state
  8106. * @param currentTarget defines the current target of the state
  8107. */
  8108. function EventState(mask, skipNextObservers, target, currentTarget) {
  8109. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8110. this.initalize(mask, skipNextObservers, target, currentTarget);
  8111. }
  8112. /**
  8113. * Initialize the current event state
  8114. * @param mask defines the mask associated with this state
  8115. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8116. * @param target defines the original target of the state
  8117. * @param currentTarget defines the current target of the state
  8118. * @returns the current event state
  8119. */
  8120. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8121. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8122. this.mask = mask;
  8123. this.skipNextObservers = skipNextObservers;
  8124. this.target = target;
  8125. this.currentTarget = currentTarget;
  8126. return this;
  8127. };
  8128. return EventState;
  8129. }());
  8130. BABYLON.EventState = EventState;
  8131. /**
  8132. * Represent an Observer registered to a given Observable object.
  8133. */
  8134. var Observer = /** @class */ (function () {
  8135. /**
  8136. * Creates a new observer
  8137. * @param callback defines the callback to call when the observer is notified
  8138. * @param mask defines the mask of the observer (used to filter notifications)
  8139. * @param scope defines the current scope used to restore the JS context
  8140. */
  8141. function Observer(
  8142. /**
  8143. * Defines the callback to call when the observer is notified
  8144. */
  8145. callback,
  8146. /**
  8147. * Defines the mask of the observer (used to filter notifications)
  8148. */
  8149. mask,
  8150. /**
  8151. * Defines the current scope used to restore the JS context
  8152. */
  8153. scope) {
  8154. if (scope === void 0) { scope = null; }
  8155. this.callback = callback;
  8156. this.mask = mask;
  8157. this.scope = scope;
  8158. /** @hidden */
  8159. this._willBeUnregistered = false;
  8160. /**
  8161. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8162. */
  8163. this.unregisterOnNextCall = false;
  8164. }
  8165. return Observer;
  8166. }());
  8167. BABYLON.Observer = Observer;
  8168. /**
  8169. * Represent a list of observers registered to multiple Observables object.
  8170. */
  8171. var MultiObserver = /** @class */ (function () {
  8172. function MultiObserver() {
  8173. }
  8174. /**
  8175. * Release associated resources
  8176. */
  8177. MultiObserver.prototype.dispose = function () {
  8178. if (this._observers && this._observables) {
  8179. for (var index = 0; index < this._observers.length; index++) {
  8180. this._observables[index].remove(this._observers[index]);
  8181. }
  8182. }
  8183. this._observers = null;
  8184. this._observables = null;
  8185. };
  8186. /**
  8187. * Raise a callback when one of the observable will notify
  8188. * @param observables defines a list of observables to watch
  8189. * @param callback defines the callback to call on notification
  8190. * @param mask defines the mask used to filter notifications
  8191. * @param scope defines the current scope used to restore the JS context
  8192. * @returns the new MultiObserver
  8193. */
  8194. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8195. if (mask === void 0) { mask = -1; }
  8196. if (scope === void 0) { scope = null; }
  8197. var result = new MultiObserver();
  8198. result._observers = new Array();
  8199. result._observables = observables;
  8200. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8201. var observable = observables_1[_i];
  8202. var observer = observable.add(callback, mask, false, scope);
  8203. if (observer) {
  8204. result._observers.push(observer);
  8205. }
  8206. }
  8207. return result;
  8208. };
  8209. return MultiObserver;
  8210. }());
  8211. BABYLON.MultiObserver = MultiObserver;
  8212. /**
  8213. * The Observable class is a simple implementation of the Observable pattern.
  8214. *
  8215. * 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.
  8216. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8217. * 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).
  8218. * 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.
  8219. */
  8220. var Observable = /** @class */ (function () {
  8221. /**
  8222. * Creates a new observable
  8223. * @param onObserverAdded defines a callback to call when a new observer is added
  8224. */
  8225. function Observable(onObserverAdded) {
  8226. this._observers = new Array();
  8227. this._eventState = new EventState(0);
  8228. if (onObserverAdded) {
  8229. this._onObserverAdded = onObserverAdded;
  8230. }
  8231. }
  8232. /**
  8233. * Create a new Observer with the specified callback
  8234. * @param callback the callback that will be executed for that Observer
  8235. * @param mask the mask used to filter observers
  8236. * @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.
  8237. * @param scope optional scope for the callback to be called from
  8238. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8239. * @returns the new observer created for the callback
  8240. */
  8241. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8242. if (mask === void 0) { mask = -1; }
  8243. if (insertFirst === void 0) { insertFirst = false; }
  8244. if (scope === void 0) { scope = null; }
  8245. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8246. if (!callback) {
  8247. return null;
  8248. }
  8249. var observer = new Observer(callback, mask, scope);
  8250. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8251. if (insertFirst) {
  8252. this._observers.unshift(observer);
  8253. }
  8254. else {
  8255. this._observers.push(observer);
  8256. }
  8257. if (this._onObserverAdded) {
  8258. this._onObserverAdded(observer);
  8259. }
  8260. return observer;
  8261. };
  8262. /**
  8263. * Create a new Observer with the specified callback and unregisters after the next notification
  8264. * @param callback the callback that will be executed for that Observer
  8265. * @returns the new observer created for the callback
  8266. */
  8267. Observable.prototype.addOnce = function (callback) {
  8268. return this.add(callback, undefined, undefined, undefined, true);
  8269. };
  8270. /**
  8271. * Remove an Observer from the Observable object
  8272. * @param observer the instance of the Observer to remove
  8273. * @returns false if it doesn't belong to this Observable
  8274. */
  8275. Observable.prototype.remove = function (observer) {
  8276. if (!observer) {
  8277. return false;
  8278. }
  8279. var index = this._observers.indexOf(observer);
  8280. if (index !== -1) {
  8281. this._deferUnregister(observer);
  8282. return true;
  8283. }
  8284. return false;
  8285. };
  8286. /**
  8287. * Remove a callback from the Observable object
  8288. * @param callback the callback to remove
  8289. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8290. * @returns false if it doesn't belong to this Observable
  8291. */
  8292. Observable.prototype.removeCallback = function (callback, scope) {
  8293. for (var index = 0; index < this._observers.length; index++) {
  8294. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8295. this._deferUnregister(this._observers[index]);
  8296. return true;
  8297. }
  8298. }
  8299. return false;
  8300. };
  8301. Observable.prototype._deferUnregister = function (observer) {
  8302. var _this = this;
  8303. observer.unregisterOnNextCall = false;
  8304. observer._willBeUnregistered = true;
  8305. BABYLON.Tools.SetImmediate(function () {
  8306. _this._remove(observer);
  8307. });
  8308. };
  8309. // This should only be called when not iterating over _observers to avoid callback skipping.
  8310. // Removes an observer from the _observer Array.
  8311. Observable.prototype._remove = function (observer) {
  8312. if (!observer) {
  8313. return false;
  8314. }
  8315. var index = this._observers.indexOf(observer);
  8316. if (index !== -1) {
  8317. this._observers.splice(index, 1);
  8318. return true;
  8319. }
  8320. return false;
  8321. };
  8322. /**
  8323. * Notify all Observers by calling their respective callback with the given data
  8324. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8325. * @param eventData defines the data to send to all observers
  8326. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8327. * @param target defines the original target of the state
  8328. * @param currentTarget defines the current target of the state
  8329. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8330. */
  8331. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8332. if (mask === void 0) { mask = -1; }
  8333. if (!this._observers.length) {
  8334. return true;
  8335. }
  8336. var state = this._eventState;
  8337. state.mask = mask;
  8338. state.target = target;
  8339. state.currentTarget = currentTarget;
  8340. state.skipNextObservers = false;
  8341. state.lastReturnValue = eventData;
  8342. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8343. var obs = _a[_i];
  8344. if (obs._willBeUnregistered) {
  8345. continue;
  8346. }
  8347. if (obs.mask & mask) {
  8348. if (obs.scope) {
  8349. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8350. }
  8351. else {
  8352. state.lastReturnValue = obs.callback(eventData, state);
  8353. }
  8354. if (obs.unregisterOnNextCall) {
  8355. this._deferUnregister(obs);
  8356. }
  8357. }
  8358. if (state.skipNextObservers) {
  8359. return false;
  8360. }
  8361. }
  8362. return true;
  8363. };
  8364. /**
  8365. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8366. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8367. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8368. * and it is crucial that all callbacks will be executed.
  8369. * The order of the callbacks is kept, callbacks are not executed parallel.
  8370. *
  8371. * @param eventData The data to be sent to each callback
  8372. * @param mask is used to filter observers defaults to -1
  8373. * @param target defines the callback target (see EventState)
  8374. * @param currentTarget defines he current object in the bubbling phase
  8375. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8376. */
  8377. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8378. var _this = this;
  8379. if (mask === void 0) { mask = -1; }
  8380. // create an empty promise
  8381. var p = Promise.resolve(eventData);
  8382. // no observers? return this promise.
  8383. if (!this._observers.length) {
  8384. return p;
  8385. }
  8386. var state = this._eventState;
  8387. state.mask = mask;
  8388. state.target = target;
  8389. state.currentTarget = currentTarget;
  8390. state.skipNextObservers = false;
  8391. // execute one callback after another (not using Promise.all, the order is important)
  8392. this._observers.forEach(function (obs) {
  8393. if (state.skipNextObservers) {
  8394. return;
  8395. }
  8396. if (obs._willBeUnregistered) {
  8397. return;
  8398. }
  8399. if (obs.mask & mask) {
  8400. if (obs.scope) {
  8401. p = p.then(function (lastReturnedValue) {
  8402. state.lastReturnValue = lastReturnedValue;
  8403. return obs.callback.apply(obs.scope, [eventData, state]);
  8404. });
  8405. }
  8406. else {
  8407. p = p.then(function (lastReturnedValue) {
  8408. state.lastReturnValue = lastReturnedValue;
  8409. return obs.callback(eventData, state);
  8410. });
  8411. }
  8412. if (obs.unregisterOnNextCall) {
  8413. _this._deferUnregister(obs);
  8414. }
  8415. }
  8416. });
  8417. // return the eventData
  8418. return p.then(function () { return eventData; });
  8419. };
  8420. /**
  8421. * Notify a specific observer
  8422. * @param observer defines the observer to notify
  8423. * @param eventData defines the data to be sent to each callback
  8424. * @param mask is used to filter observers defaults to -1
  8425. */
  8426. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8427. if (mask === void 0) { mask = -1; }
  8428. var state = this._eventState;
  8429. state.mask = mask;
  8430. state.skipNextObservers = false;
  8431. observer.callback(eventData, state);
  8432. };
  8433. /**
  8434. * Gets a boolean indicating if the observable has at least one observer
  8435. * @returns true is the Observable has at least one Observer registered
  8436. */
  8437. Observable.prototype.hasObservers = function () {
  8438. return this._observers.length > 0;
  8439. };
  8440. /**
  8441. * Clear the list of observers
  8442. */
  8443. Observable.prototype.clear = function () {
  8444. this._observers = new Array();
  8445. this._onObserverAdded = null;
  8446. };
  8447. /**
  8448. * Clone the current observable
  8449. * @returns a new observable
  8450. */
  8451. Observable.prototype.clone = function () {
  8452. var result = new Observable();
  8453. result._observers = this._observers.slice(0);
  8454. return result;
  8455. };
  8456. /**
  8457. * Does this observable handles observer registered with a given mask
  8458. * @param mask defines the mask to be tested
  8459. * @return whether or not one observer registered with the given mask is handeled
  8460. **/
  8461. Observable.prototype.hasSpecificMask = function (mask) {
  8462. if (mask === void 0) { mask = -1; }
  8463. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8464. var obs = _a[_i];
  8465. if (obs.mask & mask || obs.mask === mask) {
  8466. return true;
  8467. }
  8468. }
  8469. return false;
  8470. };
  8471. return Observable;
  8472. }());
  8473. BABYLON.Observable = Observable;
  8474. })(BABYLON || (BABYLON = {}));
  8475. //# sourceMappingURL=babylon.observable.js.map
  8476. var BABYLON;
  8477. (function (BABYLON) {
  8478. /**
  8479. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8480. */
  8481. var SmartArray = /** @class */ (function () {
  8482. /**
  8483. * Instantiates a Smart Array.
  8484. * @param capacity defines the default capacity of the array.
  8485. */
  8486. function SmartArray(capacity) {
  8487. /**
  8488. * The active length of the array.
  8489. */
  8490. this.length = 0;
  8491. this.data = new Array(capacity);
  8492. this._id = SmartArray._GlobalId++;
  8493. }
  8494. /**
  8495. * Pushes a value at the end of the active data.
  8496. * @param value defines the object to push in the array.
  8497. */
  8498. SmartArray.prototype.push = function (value) {
  8499. this.data[this.length++] = value;
  8500. if (this.length > this.data.length) {
  8501. this.data.length *= 2;
  8502. }
  8503. };
  8504. /**
  8505. * Iterates over the active data and apply the lambda to them.
  8506. * @param func defines the action to apply on each value.
  8507. */
  8508. SmartArray.prototype.forEach = function (func) {
  8509. for (var index = 0; index < this.length; index++) {
  8510. func(this.data[index]);
  8511. }
  8512. };
  8513. /**
  8514. * Sorts the full sets of data.
  8515. * @param compareFn defines the comparison function to apply.
  8516. */
  8517. SmartArray.prototype.sort = function (compareFn) {
  8518. this.data.sort(compareFn);
  8519. };
  8520. /**
  8521. * Resets the active data to an empty array.
  8522. */
  8523. SmartArray.prototype.reset = function () {
  8524. this.length = 0;
  8525. };
  8526. /**
  8527. * Releases all the data from the array as well as the array.
  8528. */
  8529. SmartArray.prototype.dispose = function () {
  8530. this.reset();
  8531. if (this.data) {
  8532. this.data.length = 0;
  8533. this.data = [];
  8534. }
  8535. };
  8536. /**
  8537. * Concats the active data with a given array.
  8538. * @param array defines the data to concatenate with.
  8539. */
  8540. SmartArray.prototype.concat = function (array) {
  8541. if (array.length === 0) {
  8542. return;
  8543. }
  8544. if (this.length + array.length > this.data.length) {
  8545. this.data.length = (this.length + array.length) * 2;
  8546. }
  8547. for (var index = 0; index < array.length; index++) {
  8548. this.data[this.length++] = (array.data || array)[index];
  8549. }
  8550. };
  8551. /**
  8552. * Returns the position of a value in the active data.
  8553. * @param value defines the value to find the index for
  8554. * @returns the index if found in the active data otherwise -1
  8555. */
  8556. SmartArray.prototype.indexOf = function (value) {
  8557. var position = this.data.indexOf(value);
  8558. if (position >= this.length) {
  8559. return -1;
  8560. }
  8561. return position;
  8562. };
  8563. /**
  8564. * Returns whether an element is part of the active data.
  8565. * @param value defines the value to look for
  8566. * @returns true if found in the active data otherwise false
  8567. */
  8568. SmartArray.prototype.contains = function (value) {
  8569. return this.indexOf(value) !== -1;
  8570. };
  8571. // Statics
  8572. SmartArray._GlobalId = 0;
  8573. return SmartArray;
  8574. }());
  8575. BABYLON.SmartArray = SmartArray;
  8576. /**
  8577. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8578. * The data in this array can only be present once
  8579. */
  8580. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8581. __extends(SmartArrayNoDuplicate, _super);
  8582. function SmartArrayNoDuplicate() {
  8583. var _this = _super !== null && _super.apply(this, arguments) || this;
  8584. _this._duplicateId = 0;
  8585. return _this;
  8586. }
  8587. /**
  8588. * Pushes a value at the end of the active data.
  8589. * THIS DOES NOT PREVENT DUPPLICATE DATA
  8590. * @param value defines the object to push in the array.
  8591. */
  8592. SmartArrayNoDuplicate.prototype.push = function (value) {
  8593. _super.prototype.push.call(this, value);
  8594. if (!value.__smartArrayFlags) {
  8595. value.__smartArrayFlags = {};
  8596. }
  8597. value.__smartArrayFlags[this._id] = this._duplicateId;
  8598. };
  8599. /**
  8600. * Pushes a value at the end of the active data.
  8601. * If the data is already present, it won t be added again
  8602. * @param value defines the object to push in the array.
  8603. * @returns true if added false if it was already present
  8604. */
  8605. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8606. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8607. return false;
  8608. }
  8609. this.push(value);
  8610. return true;
  8611. };
  8612. /**
  8613. * Resets the active data to an empty array.
  8614. */
  8615. SmartArrayNoDuplicate.prototype.reset = function () {
  8616. _super.prototype.reset.call(this);
  8617. this._duplicateId++;
  8618. };
  8619. /**
  8620. * Concats the active data with a given array.
  8621. * This ensures no dupplicate will be present in the result.
  8622. * @param array defines the data to concatenate with.
  8623. */
  8624. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8625. if (array.length === 0) {
  8626. return;
  8627. }
  8628. if (this.length + array.length > this.data.length) {
  8629. this.data.length = (this.length + array.length) * 2;
  8630. }
  8631. for (var index = 0; index < array.length; index++) {
  8632. var item = (array.data || array)[index];
  8633. this.pushNoDuplicate(item);
  8634. }
  8635. };
  8636. return SmartArrayNoDuplicate;
  8637. }(SmartArray));
  8638. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8639. })(BABYLON || (BABYLON = {}));
  8640. //# sourceMappingURL=babylon.smartArray.js.map
  8641. var BABYLON;
  8642. (function (BABYLON) {
  8643. /** Class used to store color4 gradient */
  8644. var ColorGradient = /** @class */ (function () {
  8645. function ColorGradient() {
  8646. }
  8647. /**
  8648. * Will get a color picked randomly between color1 and color2.
  8649. * If color2 is undefined then color1 will be used
  8650. * @param result defines the target Color4 to store the result in
  8651. */
  8652. ColorGradient.prototype.getColorToRef = function (result) {
  8653. if (!this.color2) {
  8654. result.copyFrom(this.color1);
  8655. return;
  8656. }
  8657. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8658. };
  8659. return ColorGradient;
  8660. }());
  8661. BABYLON.ColorGradient = ColorGradient;
  8662. /** Class used to store color 3 gradient */
  8663. var Color3Gradient = /** @class */ (function () {
  8664. function Color3Gradient() {
  8665. }
  8666. return Color3Gradient;
  8667. }());
  8668. BABYLON.Color3Gradient = Color3Gradient;
  8669. /** Class used to store factor gradient */
  8670. var FactorGradient = /** @class */ (function () {
  8671. function FactorGradient() {
  8672. }
  8673. /**
  8674. * Will get a number picked randomly between factor1 and factor2.
  8675. * If factor2 is undefined then factor1 will be used
  8676. * @returns the picked number
  8677. */
  8678. FactorGradient.prototype.getFactor = function () {
  8679. if (this.factor2 === undefined) {
  8680. return this.factor1;
  8681. }
  8682. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8683. };
  8684. return FactorGradient;
  8685. }());
  8686. BABYLON.FactorGradient = FactorGradient;
  8687. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8688. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8689. var LoadFileError = /** @class */ (function (_super) {
  8690. __extends(LoadFileError, _super);
  8691. function LoadFileError(message, request) {
  8692. var _this = _super.call(this, message) || this;
  8693. _this.request = request;
  8694. _this.name = "LoadFileError";
  8695. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8696. return _this;
  8697. }
  8698. // Polyfill for Object.setPrototypeOf if necessary.
  8699. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8700. return LoadFileError;
  8701. }(Error));
  8702. BABYLON.LoadFileError = LoadFileError;
  8703. var RetryStrategy = /** @class */ (function () {
  8704. function RetryStrategy() {
  8705. }
  8706. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8707. if (maxRetries === void 0) { maxRetries = 3; }
  8708. if (baseInterval === void 0) { baseInterval = 500; }
  8709. return function (url, request, retryIndex) {
  8710. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8711. return -1;
  8712. }
  8713. return Math.pow(2, retryIndex) * baseInterval;
  8714. };
  8715. };
  8716. return RetryStrategy;
  8717. }());
  8718. BABYLON.RetryStrategy = RetryStrategy;
  8719. // Screenshots
  8720. var screenshotCanvas;
  8721. var cloneValue = function (source, destinationObject) {
  8722. if (!source)
  8723. return null;
  8724. if (source instanceof BABYLON.Mesh) {
  8725. return null;
  8726. }
  8727. if (source instanceof BABYLON.SubMesh) {
  8728. return source.clone(destinationObject);
  8729. }
  8730. else if (source.clone) {
  8731. return source.clone();
  8732. }
  8733. return null;
  8734. };
  8735. var Tools = /** @class */ (function () {
  8736. function Tools() {
  8737. }
  8738. /**
  8739. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8740. * @param u defines the coordinate on X axis
  8741. * @param v defines the coordinate on Y axis
  8742. * @param width defines the width of the source data
  8743. * @param height defines the height of the source data
  8744. * @param pixels defines the source byte array
  8745. * @param color defines the output color
  8746. */
  8747. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8748. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8749. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8750. var position = (wrappedU + wrappedV * width) * 4;
  8751. color.r = pixels[position] / 255;
  8752. color.g = pixels[position + 1] / 255;
  8753. color.b = pixels[position + 2] / 255;
  8754. color.a = pixels[position + 3] / 255;
  8755. };
  8756. /**
  8757. * Interpolates between a and b via alpha
  8758. * @param a The lower value (returned when alpha = 0)
  8759. * @param b The upper value (returned when alpha = 1)
  8760. * @param alpha The interpolation-factor
  8761. * @return The mixed value
  8762. */
  8763. Tools.Mix = function (a, b, alpha) {
  8764. return a * (1 - alpha) + b * alpha;
  8765. };
  8766. Tools.Instantiate = function (className) {
  8767. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8768. return Tools.RegisteredExternalClasses[className];
  8769. }
  8770. var arr = className.split(".");
  8771. var fn = (window || this);
  8772. for (var i = 0, len = arr.length; i < len; i++) {
  8773. fn = fn[arr[i]];
  8774. }
  8775. if (typeof fn !== "function") {
  8776. return null;
  8777. }
  8778. return fn;
  8779. };
  8780. /**
  8781. * Provides a slice function that will work even on IE
  8782. * @param data defines the array to slice
  8783. * @param start defines the start of the data (optional)
  8784. * @param end defines the end of the data (optional)
  8785. * @returns the new sliced array
  8786. */
  8787. Tools.Slice = function (data, start, end) {
  8788. if (data.slice) {
  8789. return data.slice(start, end);
  8790. }
  8791. return Array.prototype.slice.call(data, start, end);
  8792. };
  8793. Tools.SetImmediate = function (action) {
  8794. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8795. window.setImmediate(action);
  8796. }
  8797. else {
  8798. setTimeout(action, 1);
  8799. }
  8800. };
  8801. Tools.IsExponentOfTwo = function (value) {
  8802. var count = 1;
  8803. do {
  8804. count *= 2;
  8805. } while (count < value);
  8806. return count === value;
  8807. };
  8808. /**
  8809. * Returns the nearest 32-bit single precision float representation of a Number
  8810. * @param value A Number. If the parameter is of a different type, it will get converted
  8811. * to a number or to NaN if it cannot be converted
  8812. * @returns number
  8813. */
  8814. Tools.FloatRound = function (value) {
  8815. if (Math.fround) {
  8816. return Math.fround(value);
  8817. }
  8818. return (Tools._tmpFloatArray[0] = value);
  8819. };
  8820. /**
  8821. * Find the next highest power of two.
  8822. * @param x Number to start search from.
  8823. * @return Next highest power of two.
  8824. */
  8825. Tools.CeilingPOT = function (x) {
  8826. x--;
  8827. x |= x >> 1;
  8828. x |= x >> 2;
  8829. x |= x >> 4;
  8830. x |= x >> 8;
  8831. x |= x >> 16;
  8832. x++;
  8833. return x;
  8834. };
  8835. /**
  8836. * Find the next lowest power of two.
  8837. * @param x Number to start search from.
  8838. * @return Next lowest power of two.
  8839. */
  8840. Tools.FloorPOT = function (x) {
  8841. x = x | (x >> 1);
  8842. x = x | (x >> 2);
  8843. x = x | (x >> 4);
  8844. x = x | (x >> 8);
  8845. x = x | (x >> 16);
  8846. return x - (x >> 1);
  8847. };
  8848. /**
  8849. * Find the nearest power of two.
  8850. * @param x Number to start search from.
  8851. * @return Next nearest power of two.
  8852. */
  8853. Tools.NearestPOT = function (x) {
  8854. var c = Tools.CeilingPOT(x);
  8855. var f = Tools.FloorPOT(x);
  8856. return (c - x) > (x - f) ? f : c;
  8857. };
  8858. Tools.GetExponentOfTwo = function (value, max, mode) {
  8859. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8860. var pot;
  8861. switch (mode) {
  8862. case BABYLON.Engine.SCALEMODE_FLOOR:
  8863. pot = Tools.FloorPOT(value);
  8864. break;
  8865. case BABYLON.Engine.SCALEMODE_NEAREST:
  8866. pot = Tools.NearestPOT(value);
  8867. break;
  8868. case BABYLON.Engine.SCALEMODE_CEILING:
  8869. default:
  8870. pot = Tools.CeilingPOT(value);
  8871. break;
  8872. }
  8873. return Math.min(pot, max);
  8874. };
  8875. Tools.GetFilename = function (path) {
  8876. var index = path.lastIndexOf("/");
  8877. if (index < 0)
  8878. return path;
  8879. return path.substring(index + 1);
  8880. };
  8881. /**
  8882. * Extracts the "folder" part of a path (everything before the filename).
  8883. * @param uri The URI to extract the info from
  8884. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8885. * @returns The "folder" part of the path
  8886. */
  8887. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8888. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8889. var index = uri.lastIndexOf("/");
  8890. if (index < 0) {
  8891. if (returnUnchangedIfNoSlash) {
  8892. return uri;
  8893. }
  8894. return "";
  8895. }
  8896. return uri.substring(0, index + 1);
  8897. };
  8898. Tools.GetDOMTextContent = function (element) {
  8899. var result = "";
  8900. var child = element.firstChild;
  8901. while (child) {
  8902. if (child.nodeType === 3) {
  8903. result += child.textContent;
  8904. }
  8905. child = child.nextSibling;
  8906. }
  8907. return result;
  8908. };
  8909. Tools.ToDegrees = function (angle) {
  8910. return angle * 180 / Math.PI;
  8911. };
  8912. Tools.ToRadians = function (angle) {
  8913. return angle * Math.PI / 180;
  8914. };
  8915. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8916. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8917. var output = "";
  8918. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8919. var i = 0;
  8920. var bytes = new Uint8Array(buffer);
  8921. while (i < bytes.length) {
  8922. chr1 = bytes[i++];
  8923. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8924. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8925. enc1 = chr1 >> 2;
  8926. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8927. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8928. enc4 = chr3 & 63;
  8929. if (isNaN(chr2)) {
  8930. enc3 = enc4 = 64;
  8931. }
  8932. else if (isNaN(chr3)) {
  8933. enc4 = 64;
  8934. }
  8935. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8936. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8937. }
  8938. return "data:image/png;base64," + output;
  8939. };
  8940. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8941. if (bias === void 0) { bias = null; }
  8942. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8943. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8944. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8945. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8946. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8947. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8948. }
  8949. if (bias) {
  8950. minimum.x -= minimum.x * bias.x + bias.y;
  8951. minimum.y -= minimum.y * bias.x + bias.y;
  8952. minimum.z -= minimum.z * bias.x + bias.y;
  8953. maximum.x += maximum.x * bias.x + bias.y;
  8954. maximum.y += maximum.y * bias.x + bias.y;
  8955. maximum.z += maximum.z * bias.x + bias.y;
  8956. }
  8957. return {
  8958. minimum: minimum,
  8959. maximum: maximum
  8960. };
  8961. };
  8962. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8963. if (bias === void 0) { bias = null; }
  8964. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8965. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8966. if (!stride) {
  8967. stride = 3;
  8968. }
  8969. for (var index = start; index < start + count; index++) {
  8970. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8971. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8972. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8973. }
  8974. if (bias) {
  8975. minimum.x -= minimum.x * bias.x + bias.y;
  8976. minimum.y -= minimum.y * bias.x + bias.y;
  8977. minimum.z -= minimum.z * bias.x + bias.y;
  8978. maximum.x += maximum.x * bias.x + bias.y;
  8979. maximum.y += maximum.y * bias.x + bias.y;
  8980. maximum.z += maximum.z * bias.x + bias.y;
  8981. }
  8982. return {
  8983. minimum: minimum,
  8984. maximum: maximum
  8985. };
  8986. };
  8987. Tools.Vector2ArrayFeeder = function (array) {
  8988. return function (index) {
  8989. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8990. var length = isFloatArray ? array.length / 2 : array.length;
  8991. if (index >= length) {
  8992. return null;
  8993. }
  8994. if (isFloatArray) {
  8995. var fa = array;
  8996. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8997. }
  8998. var a = array;
  8999. return a[index];
  9000. };
  9001. };
  9002. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  9003. if (bias === void 0) { bias = null; }
  9004. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  9005. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  9006. var i = 0;
  9007. var cur = feeder(i++);
  9008. while (cur) {
  9009. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  9010. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  9011. cur = feeder(i++);
  9012. }
  9013. if (bias) {
  9014. minimum.x -= minimum.x * bias.x + bias.y;
  9015. minimum.y -= minimum.y * bias.x + bias.y;
  9016. maximum.x += maximum.x * bias.x + bias.y;
  9017. maximum.y += maximum.y * bias.x + bias.y;
  9018. }
  9019. return {
  9020. minimum: minimum,
  9021. maximum: maximum
  9022. };
  9023. };
  9024. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9025. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9026. return null;
  9027. return Array.isArray(obj) ? obj : [obj];
  9028. };
  9029. // Misc.
  9030. Tools.GetPointerPrefix = function () {
  9031. var eventPrefix = "pointer";
  9032. // Check if pointer events are supported
  9033. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9034. eventPrefix = "mouse";
  9035. }
  9036. return eventPrefix;
  9037. };
  9038. /**
  9039. * @param func - the function to be called
  9040. * @param requester - the object that will request the next frame. Falls back to window.
  9041. */
  9042. Tools.QueueNewFrame = function (func, requester) {
  9043. if (!Tools.IsWindowObjectExist()) {
  9044. return setTimeout(func, 16);
  9045. }
  9046. if (!requester) {
  9047. requester = window;
  9048. }
  9049. if (requester.requestAnimationFrame) {
  9050. return requester.requestAnimationFrame(func);
  9051. }
  9052. else if (requester.msRequestAnimationFrame) {
  9053. return requester.msRequestAnimationFrame(func);
  9054. }
  9055. else if (requester.webkitRequestAnimationFrame) {
  9056. return requester.webkitRequestAnimationFrame(func);
  9057. }
  9058. else if (requester.mozRequestAnimationFrame) {
  9059. return requester.mozRequestAnimationFrame(func);
  9060. }
  9061. else if (requester.oRequestAnimationFrame) {
  9062. return requester.oRequestAnimationFrame(func);
  9063. }
  9064. else {
  9065. return window.setTimeout(func, 16);
  9066. }
  9067. };
  9068. Tools.RequestFullscreen = function (element) {
  9069. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9070. if (!requestFunction)
  9071. return;
  9072. requestFunction.call(element);
  9073. };
  9074. Tools.ExitFullscreen = function () {
  9075. if (document.exitFullscreen) {
  9076. document.exitFullscreen();
  9077. }
  9078. else if (document.mozCancelFullScreen) {
  9079. document.mozCancelFullScreen();
  9080. }
  9081. else if (document.webkitCancelFullScreen) {
  9082. document.webkitCancelFullScreen();
  9083. }
  9084. else if (document.msCancelFullScreen) {
  9085. document.msCancelFullScreen();
  9086. }
  9087. };
  9088. Tools.SetCorsBehavior = function (url, element) {
  9089. if (url && url.indexOf("data:") === 0) {
  9090. return;
  9091. }
  9092. if (Tools.CorsBehavior) {
  9093. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9094. element.crossOrigin = Tools.CorsBehavior;
  9095. }
  9096. else {
  9097. var result = Tools.CorsBehavior(url);
  9098. if (result) {
  9099. element.crossOrigin = result;
  9100. }
  9101. }
  9102. }
  9103. };
  9104. // External files
  9105. Tools.CleanUrl = function (url) {
  9106. url = url.replace(/#/mg, "%23");
  9107. return url;
  9108. };
  9109. /**
  9110. * Loads an image as an HTMLImageElement.
  9111. * @param input url string, ArrayBuffer, or Blob to load
  9112. * @param onLoad callback called when the image successfully loads
  9113. * @param onError callback called when the image fails to load
  9114. * @param database database for caching
  9115. * @returns the HTMLImageElement of the loaded image
  9116. */
  9117. Tools.LoadImage = function (input, onLoad, onError, database) {
  9118. var url;
  9119. var usingObjectURL = false;
  9120. if (input instanceof ArrayBuffer) {
  9121. url = URL.createObjectURL(new Blob([input]));
  9122. usingObjectURL = true;
  9123. }
  9124. else if (input instanceof Blob) {
  9125. url = URL.createObjectURL(input);
  9126. usingObjectURL = true;
  9127. }
  9128. else {
  9129. url = Tools.CleanUrl(input);
  9130. url = Tools.PreprocessUrl(input);
  9131. }
  9132. var img = new Image();
  9133. Tools.SetCorsBehavior(url, img);
  9134. var loadHandler = function () {
  9135. if (usingObjectURL && img.src) {
  9136. URL.revokeObjectURL(img.src);
  9137. }
  9138. img.removeEventListener("load", loadHandler);
  9139. img.removeEventListener("error", errorHandler);
  9140. onLoad(img);
  9141. };
  9142. var errorHandler = function (err) {
  9143. if (usingObjectURL && img.src) {
  9144. URL.revokeObjectURL(img.src);
  9145. }
  9146. img.removeEventListener("load", loadHandler);
  9147. img.removeEventListener("error", errorHandler);
  9148. Tools.Error("Error while trying to load image: " + input);
  9149. if (onError) {
  9150. onError("Error while trying to load image: " + input, err);
  9151. }
  9152. };
  9153. img.addEventListener("load", loadHandler);
  9154. img.addEventListener("error", errorHandler);
  9155. var noIndexedDB = function () {
  9156. img.src = url;
  9157. };
  9158. var loadFromIndexedDB = function () {
  9159. if (database) {
  9160. database.loadImageFromDB(url, img);
  9161. }
  9162. };
  9163. //ANY database to do!
  9164. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9165. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9166. }
  9167. else {
  9168. if (url.indexOf("file:") !== -1) {
  9169. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9170. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9171. try {
  9172. var blobURL;
  9173. try {
  9174. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9175. }
  9176. catch (ex) {
  9177. // Chrome doesn't support oneTimeOnly parameter
  9178. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9179. }
  9180. img.src = blobURL;
  9181. usingObjectURL = true;
  9182. }
  9183. catch (e) {
  9184. img.src = "";
  9185. }
  9186. return img;
  9187. }
  9188. }
  9189. noIndexedDB();
  9190. }
  9191. return img;
  9192. };
  9193. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9194. url = Tools.CleanUrl(url);
  9195. url = Tools.PreprocessUrl(url);
  9196. // If file and file input are set
  9197. if (url.indexOf("file:") !== -1) {
  9198. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9199. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9200. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9201. }
  9202. }
  9203. var loadUrl = Tools.BaseUrl + url;
  9204. var aborted = false;
  9205. var fileRequest = {
  9206. onCompleteObservable: new BABYLON.Observable(),
  9207. abort: function () { return aborted = true; },
  9208. };
  9209. var requestFile = function () {
  9210. var request = new XMLHttpRequest();
  9211. var retryHandle = null;
  9212. fileRequest.abort = function () {
  9213. aborted = true;
  9214. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9215. request.abort();
  9216. }
  9217. if (retryHandle !== null) {
  9218. clearTimeout(retryHandle);
  9219. retryHandle = null;
  9220. }
  9221. };
  9222. var retryLoop = function (retryIndex) {
  9223. request.open('GET', loadUrl, true);
  9224. if (useArrayBuffer) {
  9225. request.responseType = "arraybuffer";
  9226. }
  9227. if (onProgress) {
  9228. request.addEventListener("progress", onProgress);
  9229. }
  9230. var onLoadEnd = function () {
  9231. request.removeEventListener("loadend", onLoadEnd);
  9232. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9233. fileRequest.onCompleteObservable.clear();
  9234. };
  9235. request.addEventListener("loadend", onLoadEnd);
  9236. var onReadyStateChange = function () {
  9237. if (aborted) {
  9238. return;
  9239. }
  9240. // In case of undefined state in some browsers.
  9241. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9242. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9243. request.removeEventListener("readystatechange", onReadyStateChange);
  9244. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9245. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9246. return;
  9247. }
  9248. var retryStrategy = Tools.DefaultRetryStrategy;
  9249. if (retryStrategy) {
  9250. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9251. if (waitTime !== -1) {
  9252. // Prevent the request from completing for retry.
  9253. request.removeEventListener("loadend", onLoadEnd);
  9254. request = new XMLHttpRequest();
  9255. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9256. return;
  9257. }
  9258. }
  9259. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9260. if (onError) {
  9261. onError(request, e);
  9262. }
  9263. else {
  9264. throw e;
  9265. }
  9266. }
  9267. };
  9268. request.addEventListener("readystatechange", onReadyStateChange);
  9269. request.send();
  9270. };
  9271. retryLoop(0);
  9272. };
  9273. // Caching all files
  9274. if (database && database.enableSceneOffline) {
  9275. var noIndexedDB_1 = function (request) {
  9276. if (request && request.status > 400) {
  9277. if (onError) {
  9278. onError(request);
  9279. }
  9280. }
  9281. else {
  9282. if (!aborted) {
  9283. requestFile();
  9284. }
  9285. }
  9286. };
  9287. var loadFromIndexedDB = function () {
  9288. // TODO: database needs to support aborting and should return a IFileRequest
  9289. if (aborted) {
  9290. return;
  9291. }
  9292. if (database) {
  9293. database.loadFileFromDB(url, function (data) {
  9294. if (!aborted) {
  9295. onSuccess(data);
  9296. }
  9297. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9298. }, onProgress ? function (event) {
  9299. if (!aborted) {
  9300. onProgress(event);
  9301. }
  9302. } : undefined, noIndexedDB_1, useArrayBuffer);
  9303. }
  9304. };
  9305. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9306. }
  9307. else {
  9308. requestFile();
  9309. }
  9310. return fileRequest;
  9311. };
  9312. /**
  9313. * Load a script (identified by an url). When the url returns, the
  9314. * content of this file is added into a new script element, attached to the DOM (body element)
  9315. */
  9316. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9317. if (!Tools.IsWindowObjectExist()) {
  9318. return;
  9319. }
  9320. var head = document.getElementsByTagName('head')[0];
  9321. var script = document.createElement('script');
  9322. script.type = 'text/javascript';
  9323. script.src = scriptUrl;
  9324. script.onload = function () {
  9325. if (onSuccess) {
  9326. onSuccess();
  9327. }
  9328. };
  9329. script.onerror = function (e) {
  9330. if (onError) {
  9331. onError("Unable to load script '" + scriptUrl + "'", e);
  9332. }
  9333. };
  9334. head.appendChild(script);
  9335. };
  9336. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9337. var reader = new FileReader();
  9338. var request = {
  9339. onCompleteObservable: new BABYLON.Observable(),
  9340. abort: function () { return reader.abort(); },
  9341. };
  9342. reader.onloadend = function (e) {
  9343. request.onCompleteObservable.notifyObservers(request);
  9344. };
  9345. reader.onload = function (e) {
  9346. //target doesn't have result from ts 1.3
  9347. callback(e.target['result']);
  9348. };
  9349. reader.onprogress = progressCallback;
  9350. reader.readAsDataURL(fileToLoad);
  9351. return request;
  9352. };
  9353. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9354. var reader = new FileReader();
  9355. var request = {
  9356. onCompleteObservable: new BABYLON.Observable(),
  9357. abort: function () { return reader.abort(); },
  9358. };
  9359. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9360. reader.onerror = function (e) {
  9361. Tools.Log("Error while reading file: " + fileToLoad.name);
  9362. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9363. };
  9364. reader.onload = function (e) {
  9365. //target doesn't have result from ts 1.3
  9366. callback(e.target['result']);
  9367. };
  9368. if (progressCallBack) {
  9369. reader.onprogress = progressCallBack;
  9370. }
  9371. if (!useArrayBuffer) {
  9372. // Asynchronous read
  9373. reader.readAsText(fileToLoad);
  9374. }
  9375. else {
  9376. reader.readAsArrayBuffer(fileToLoad);
  9377. }
  9378. return request;
  9379. };
  9380. //returns a downloadable url to a file content.
  9381. Tools.FileAsURL = function (content) {
  9382. var fileBlob = new Blob([content]);
  9383. var url = window.URL || window.webkitURL;
  9384. var link = url.createObjectURL(fileBlob);
  9385. return link;
  9386. };
  9387. // Misc.
  9388. Tools.Format = function (value, decimals) {
  9389. if (decimals === void 0) { decimals = 2; }
  9390. return value.toFixed(decimals);
  9391. };
  9392. Tools.CheckExtends = function (v, min, max) {
  9393. if (v.x < min.x)
  9394. min.x = v.x;
  9395. if (v.y < min.y)
  9396. min.y = v.y;
  9397. if (v.z < min.z)
  9398. min.z = v.z;
  9399. if (v.x > max.x)
  9400. max.x = v.x;
  9401. if (v.y > max.y)
  9402. max.y = v.y;
  9403. if (v.z > max.z)
  9404. max.z = v.z;
  9405. };
  9406. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9407. for (var prop in source) {
  9408. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9409. continue;
  9410. }
  9411. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9412. continue;
  9413. }
  9414. var sourceValue = source[prop];
  9415. var typeOfSourceValue = typeof sourceValue;
  9416. if (typeOfSourceValue === "function") {
  9417. continue;
  9418. }
  9419. try {
  9420. if (typeOfSourceValue === "object") {
  9421. if (sourceValue instanceof Array) {
  9422. destination[prop] = [];
  9423. if (sourceValue.length > 0) {
  9424. if (typeof sourceValue[0] == "object") {
  9425. for (var index = 0; index < sourceValue.length; index++) {
  9426. var clonedValue = cloneValue(sourceValue[index], destination);
  9427. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9428. destination[prop].push(clonedValue);
  9429. }
  9430. }
  9431. }
  9432. else {
  9433. destination[prop] = sourceValue.slice(0);
  9434. }
  9435. }
  9436. }
  9437. else {
  9438. destination[prop] = cloneValue(sourceValue, destination);
  9439. }
  9440. }
  9441. else {
  9442. destination[prop] = sourceValue;
  9443. }
  9444. }
  9445. catch (e) {
  9446. // Just ignore error (it could be because of a read-only property)
  9447. }
  9448. }
  9449. };
  9450. Tools.IsEmpty = function (obj) {
  9451. for (var i in obj) {
  9452. if (obj.hasOwnProperty(i)) {
  9453. return false;
  9454. }
  9455. }
  9456. return true;
  9457. };
  9458. Tools.RegisterTopRootEvents = function (events) {
  9459. for (var index = 0; index < events.length; index++) {
  9460. var event = events[index];
  9461. window.addEventListener(event.name, event.handler, false);
  9462. try {
  9463. if (window.parent) {
  9464. window.parent.addEventListener(event.name, event.handler, false);
  9465. }
  9466. }
  9467. catch (e) {
  9468. // Silently fails...
  9469. }
  9470. }
  9471. };
  9472. Tools.UnregisterTopRootEvents = function (events) {
  9473. for (var index = 0; index < events.length; index++) {
  9474. var event = events[index];
  9475. window.removeEventListener(event.name, event.handler);
  9476. try {
  9477. if (window.parent) {
  9478. window.parent.removeEventListener(event.name, event.handler);
  9479. }
  9480. }
  9481. catch (e) {
  9482. // Silently fails...
  9483. }
  9484. }
  9485. };
  9486. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9487. if (mimeType === void 0) { mimeType = "image/png"; }
  9488. // Read the contents of the framebuffer
  9489. var numberOfChannelsByLine = width * 4;
  9490. var halfHeight = height / 2;
  9491. //Reading datas from WebGL
  9492. var data = engine.readPixels(0, 0, width, height);
  9493. //To flip image on Y axis.
  9494. for (var i = 0; i < halfHeight; i++) {
  9495. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9496. var currentCell = j + i * numberOfChannelsByLine;
  9497. var targetLine = height - i - 1;
  9498. var targetCell = j + targetLine * numberOfChannelsByLine;
  9499. var temp = data[currentCell];
  9500. data[currentCell] = data[targetCell];
  9501. data[targetCell] = temp;
  9502. }
  9503. }
  9504. // Create a 2D canvas to store the result
  9505. if (!screenshotCanvas) {
  9506. screenshotCanvas = document.createElement('canvas');
  9507. }
  9508. screenshotCanvas.width = width;
  9509. screenshotCanvas.height = height;
  9510. var context = screenshotCanvas.getContext('2d');
  9511. if (context) {
  9512. // Copy the pixels to a 2D canvas
  9513. var imageData = context.createImageData(width, height);
  9514. var castData = (imageData.data);
  9515. castData.set(data);
  9516. context.putImageData(imageData, 0, 0);
  9517. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9518. }
  9519. };
  9520. /**
  9521. * Converts the canvas data to blob.
  9522. * This acts as a polyfill for browsers not supporting the to blob function.
  9523. * @param canvas Defines the canvas to extract the data from
  9524. * @param successCallback Defines the callback triggered once the data are available
  9525. * @param mimeType Defines the mime type of the result
  9526. */
  9527. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9528. if (mimeType === void 0) { mimeType = "image/png"; }
  9529. // We need HTMLCanvasElement.toBlob for HD screenshots
  9530. if (!canvas.toBlob) {
  9531. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9532. canvas.toBlob = function (callback, type, quality) {
  9533. var _this = this;
  9534. setTimeout(function () {
  9535. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9536. for (var i = 0; i < len; i++) {
  9537. arr[i] = binStr.charCodeAt(i);
  9538. }
  9539. callback(new Blob([arr]));
  9540. });
  9541. };
  9542. }
  9543. canvas.toBlob(function (blob) {
  9544. successCallback(blob);
  9545. }, mimeType);
  9546. };
  9547. /**
  9548. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9549. * @param successCallback Defines the callback triggered once the data are available
  9550. * @param mimeType Defines the mime type of the result
  9551. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9552. */
  9553. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9554. if (mimeType === void 0) { mimeType = "image/png"; }
  9555. if (successCallback) {
  9556. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9557. successCallback(base64Image);
  9558. }
  9559. else {
  9560. this.ToBlob(screenshotCanvas, function (blob) {
  9561. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9562. if (("download" in document.createElement("a"))) {
  9563. if (!fileName) {
  9564. var date = new Date();
  9565. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9566. fileName = "screenshot_" + stringDate + ".png";
  9567. }
  9568. Tools.Download(blob, fileName);
  9569. }
  9570. else {
  9571. var url = URL.createObjectURL(blob);
  9572. var newWindow = window.open("");
  9573. if (!newWindow)
  9574. return;
  9575. var img = newWindow.document.createElement("img");
  9576. img.onload = function () {
  9577. // no longer need to read the blob so it's revoked
  9578. URL.revokeObjectURL(url);
  9579. };
  9580. img.src = url;
  9581. newWindow.document.body.appendChild(img);
  9582. }
  9583. }, mimeType);
  9584. }
  9585. };
  9586. /**
  9587. * Downloads a blob in the browser
  9588. * @param blob defines the blob to download
  9589. * @param fileName defines the name of the downloaded file
  9590. */
  9591. Tools.Download = function (blob, fileName) {
  9592. if (navigator && navigator.msSaveBlob) {
  9593. navigator.msSaveBlob(blob, fileName);
  9594. return;
  9595. }
  9596. var url = window.URL.createObjectURL(blob);
  9597. var a = document.createElement("a");
  9598. document.body.appendChild(a);
  9599. a.style.display = "none";
  9600. a.href = url;
  9601. a.download = fileName;
  9602. a.addEventListener("click", function () {
  9603. if (a.parentElement) {
  9604. a.parentElement.removeChild(a);
  9605. }
  9606. });
  9607. a.click();
  9608. window.URL.revokeObjectURL(url);
  9609. };
  9610. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9611. if (mimeType === void 0) { mimeType = "image/png"; }
  9612. var width;
  9613. var height;
  9614. // If a precision value is specified
  9615. if (size.precision) {
  9616. width = Math.round(engine.getRenderWidth() * size.precision);
  9617. height = Math.round(width / engine.getAspectRatio(camera));
  9618. }
  9619. else if (size.width && size.height) {
  9620. width = size.width;
  9621. height = size.height;
  9622. }
  9623. //If passing only width, computing height to keep display canvas ratio.
  9624. else if (size.width && !size.height) {
  9625. width = size.width;
  9626. height = Math.round(width / engine.getAspectRatio(camera));
  9627. }
  9628. //If passing only height, computing width to keep display canvas ratio.
  9629. else if (size.height && !size.width) {
  9630. height = size.height;
  9631. width = Math.round(height * engine.getAspectRatio(camera));
  9632. }
  9633. //Assuming here that "size" parameter is a number
  9634. else if (!isNaN(size)) {
  9635. height = size;
  9636. width = size;
  9637. }
  9638. else {
  9639. Tools.Error("Invalid 'size' parameter !");
  9640. return;
  9641. }
  9642. if (!screenshotCanvas) {
  9643. screenshotCanvas = document.createElement('canvas');
  9644. }
  9645. screenshotCanvas.width = width;
  9646. screenshotCanvas.height = height;
  9647. var renderContext = screenshotCanvas.getContext("2d");
  9648. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9649. var newWidth = width;
  9650. var newHeight = newWidth / ratio;
  9651. if (newHeight > height) {
  9652. newHeight = height;
  9653. newWidth = newHeight * ratio;
  9654. }
  9655. var offsetX = Math.max(0, width - newWidth) / 2;
  9656. var offsetY = Math.max(0, height - newHeight) / 2;
  9657. var renderingCanvas = engine.getRenderingCanvas();
  9658. if (renderContext && renderingCanvas) {
  9659. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9660. }
  9661. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9662. };
  9663. /**
  9664. * Generates an image screenshot from the specified camera.
  9665. *
  9666. * @param engine The engine to use for rendering
  9667. * @param camera The camera to use for rendering
  9668. * @param size This parameter can be set to a single number or to an object with the
  9669. * following (optional) properties: precision, width, height. If a single number is passed,
  9670. * it will be used for both width and height. If an object is passed, the screenshot size
  9671. * will be derived from the parameters. The precision property is a multiplier allowing
  9672. * rendering at a higher or lower resolution.
  9673. * @param successCallback The callback receives a single parameter which contains the
  9674. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9675. * src parameter of an <img> to display it.
  9676. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9677. * Check your browser for supported MIME types.
  9678. * @param samples Texture samples (default: 1)
  9679. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9680. * @param fileName A name for for the downloaded file.
  9681. * @constructor
  9682. */
  9683. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9684. if (mimeType === void 0) { mimeType = "image/png"; }
  9685. if (samples === void 0) { samples = 1; }
  9686. if (antialiasing === void 0) { antialiasing = false; }
  9687. var width;
  9688. var height;
  9689. //If a precision value is specified
  9690. if (size.precision) {
  9691. width = Math.round(engine.getRenderWidth() * size.precision);
  9692. height = Math.round(width / engine.getAspectRatio(camera));
  9693. size = { width: width, height: height };
  9694. }
  9695. else if (size.width && size.height) {
  9696. width = size.width;
  9697. height = size.height;
  9698. }
  9699. //If passing only width, computing height to keep display canvas ratio.
  9700. else if (size.width && !size.height) {
  9701. width = size.width;
  9702. height = Math.round(width / engine.getAspectRatio(camera));
  9703. size = { width: width, height: height };
  9704. }
  9705. //If passing only height, computing width to keep display canvas ratio.
  9706. else if (size.height && !size.width) {
  9707. height = size.height;
  9708. width = Math.round(height * engine.getAspectRatio(camera));
  9709. size = { width: width, height: height };
  9710. }
  9711. //Assuming here that "size" parameter is a number
  9712. else if (!isNaN(size)) {
  9713. height = size;
  9714. width = size;
  9715. }
  9716. else {
  9717. Tools.Error("Invalid 'size' parameter !");
  9718. return;
  9719. }
  9720. var scene = camera.getScene();
  9721. var previousCamera = null;
  9722. if (scene.activeCamera !== camera) {
  9723. previousCamera = scene.activeCamera;
  9724. scene.activeCamera = camera;
  9725. }
  9726. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9727. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9728. texture.renderList = null;
  9729. texture.samples = samples;
  9730. if (antialiasing) {
  9731. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9732. }
  9733. texture.onAfterRenderObservable.add(function () {
  9734. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9735. });
  9736. scene.incrementRenderId();
  9737. scene.resetCachedMaterial();
  9738. texture.render(true);
  9739. texture.dispose();
  9740. if (previousCamera) {
  9741. scene.activeCamera = previousCamera;
  9742. }
  9743. camera.getProjectionMatrix(true); // Force cache refresh;
  9744. };
  9745. // XHR response validator for local file scenario
  9746. Tools.ValidateXHRData = function (xhr, dataType) {
  9747. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9748. if (dataType === void 0) { dataType = 7; }
  9749. try {
  9750. if (dataType & 1) {
  9751. if (xhr.responseText && xhr.responseText.length > 0) {
  9752. return true;
  9753. }
  9754. else if (dataType === 1) {
  9755. return false;
  9756. }
  9757. }
  9758. if (dataType & 2) {
  9759. // Check header width and height since there is no "TGA" magic number
  9760. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9761. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9762. return true;
  9763. }
  9764. else if (dataType === 2) {
  9765. return false;
  9766. }
  9767. }
  9768. if (dataType & 4) {
  9769. // Check for the "DDS" magic number
  9770. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9771. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9772. return true;
  9773. }
  9774. else {
  9775. return false;
  9776. }
  9777. }
  9778. }
  9779. catch (e) {
  9780. // Global protection
  9781. }
  9782. return false;
  9783. };
  9784. /**
  9785. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9786. * Be aware Math.random() could cause collisions, but:
  9787. * "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"
  9788. */
  9789. Tools.RandomId = function () {
  9790. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9791. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9792. return v.toString(16);
  9793. });
  9794. };
  9795. /**
  9796. * Test if the given uri is a base64 string.
  9797. * @param uri The uri to test
  9798. * @return True if the uri is a base64 string or false otherwise.
  9799. */
  9800. Tools.IsBase64 = function (uri) {
  9801. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9802. };
  9803. /**
  9804. * Decode the given base64 uri.
  9805. * @param uri The uri to decode
  9806. * @return The decoded base64 data.
  9807. */
  9808. Tools.DecodeBase64 = function (uri) {
  9809. var decodedString = atob(uri.split(",")[1]);
  9810. var bufferLength = decodedString.length;
  9811. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9812. for (var i = 0; i < bufferLength; i++) {
  9813. bufferView[i] = decodedString.charCodeAt(i);
  9814. }
  9815. return bufferView.buffer;
  9816. };
  9817. Object.defineProperty(Tools, "NoneLogLevel", {
  9818. get: function () {
  9819. return Tools._NoneLogLevel;
  9820. },
  9821. enumerable: true,
  9822. configurable: true
  9823. });
  9824. Object.defineProperty(Tools, "MessageLogLevel", {
  9825. get: function () {
  9826. return Tools._MessageLogLevel;
  9827. },
  9828. enumerable: true,
  9829. configurable: true
  9830. });
  9831. Object.defineProperty(Tools, "WarningLogLevel", {
  9832. get: function () {
  9833. return Tools._WarningLogLevel;
  9834. },
  9835. enumerable: true,
  9836. configurable: true
  9837. });
  9838. Object.defineProperty(Tools, "ErrorLogLevel", {
  9839. get: function () {
  9840. return Tools._ErrorLogLevel;
  9841. },
  9842. enumerable: true,
  9843. configurable: true
  9844. });
  9845. Object.defineProperty(Tools, "AllLogLevel", {
  9846. get: function () {
  9847. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9848. },
  9849. enumerable: true,
  9850. configurable: true
  9851. });
  9852. Tools._AddLogEntry = function (entry) {
  9853. Tools._LogCache = entry + Tools._LogCache;
  9854. if (Tools.OnNewCacheEntry) {
  9855. Tools.OnNewCacheEntry(entry);
  9856. }
  9857. };
  9858. Tools._FormatMessage = function (message) {
  9859. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9860. var date = new Date();
  9861. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9862. };
  9863. Tools._LogDisabled = function (message) {
  9864. // nothing to do
  9865. };
  9866. Tools._LogEnabled = function (message) {
  9867. var formattedMessage = Tools._FormatMessage(message);
  9868. console.log("BJS - " + formattedMessage);
  9869. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9870. Tools._AddLogEntry(entry);
  9871. };
  9872. Tools._WarnDisabled = function (message) {
  9873. // nothing to do
  9874. };
  9875. Tools._WarnEnabled = function (message) {
  9876. var formattedMessage = Tools._FormatMessage(message);
  9877. console.warn("BJS - " + formattedMessage);
  9878. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9879. Tools._AddLogEntry(entry);
  9880. };
  9881. Tools._ErrorDisabled = function (message) {
  9882. // nothing to do
  9883. };
  9884. Tools._ErrorEnabled = function (message) {
  9885. Tools.errorsCount++;
  9886. var formattedMessage = Tools._FormatMessage(message);
  9887. console.error("BJS - " + formattedMessage);
  9888. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9889. Tools._AddLogEntry(entry);
  9890. };
  9891. Object.defineProperty(Tools, "LogCache", {
  9892. get: function () {
  9893. return Tools._LogCache;
  9894. },
  9895. enumerable: true,
  9896. configurable: true
  9897. });
  9898. Tools.ClearLogCache = function () {
  9899. Tools._LogCache = "";
  9900. Tools.errorsCount = 0;
  9901. };
  9902. Object.defineProperty(Tools, "LogLevels", {
  9903. set: function (level) {
  9904. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9905. Tools.Log = Tools._LogEnabled;
  9906. }
  9907. else {
  9908. Tools.Log = Tools._LogDisabled;
  9909. }
  9910. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9911. Tools.Warn = Tools._WarnEnabled;
  9912. }
  9913. else {
  9914. Tools.Warn = Tools._WarnDisabled;
  9915. }
  9916. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9917. Tools.Error = Tools._ErrorEnabled;
  9918. }
  9919. else {
  9920. Tools.Error = Tools._ErrorDisabled;
  9921. }
  9922. },
  9923. enumerable: true,
  9924. configurable: true
  9925. });
  9926. /**
  9927. * Check if the loaded document was accessed via `file:`-Protocol.
  9928. * @returns boolean
  9929. */
  9930. Tools.IsFileURL = function () {
  9931. return location.protocol === "file:";
  9932. };
  9933. Tools.IsWindowObjectExist = function () {
  9934. return (typeof window) !== "undefined";
  9935. };
  9936. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9937. get: function () {
  9938. return Tools._PerformanceNoneLogLevel;
  9939. },
  9940. enumerable: true,
  9941. configurable: true
  9942. });
  9943. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9944. get: function () {
  9945. return Tools._PerformanceUserMarkLogLevel;
  9946. },
  9947. enumerable: true,
  9948. configurable: true
  9949. });
  9950. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9951. get: function () {
  9952. return Tools._PerformanceConsoleLogLevel;
  9953. },
  9954. enumerable: true,
  9955. configurable: true
  9956. });
  9957. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9958. set: function (level) {
  9959. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9960. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9961. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9962. return;
  9963. }
  9964. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9965. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9966. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9967. return;
  9968. }
  9969. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9970. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9971. },
  9972. enumerable: true,
  9973. configurable: true
  9974. });
  9975. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9976. };
  9977. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9978. };
  9979. Tools._StartUserMark = function (counterName, condition) {
  9980. if (condition === void 0) { condition = true; }
  9981. if (!Tools._performance) {
  9982. if (!Tools.IsWindowObjectExist()) {
  9983. return;
  9984. }
  9985. Tools._performance = window.performance;
  9986. }
  9987. if (!condition || !Tools._performance.mark) {
  9988. return;
  9989. }
  9990. Tools._performance.mark(counterName + "-Begin");
  9991. };
  9992. Tools._EndUserMark = function (counterName, condition) {
  9993. if (condition === void 0) { condition = true; }
  9994. if (!condition || !Tools._performance.mark) {
  9995. return;
  9996. }
  9997. Tools._performance.mark(counterName + "-End");
  9998. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9999. };
  10000. Tools._StartPerformanceConsole = function (counterName, condition) {
  10001. if (condition === void 0) { condition = true; }
  10002. if (!condition) {
  10003. return;
  10004. }
  10005. Tools._StartUserMark(counterName, condition);
  10006. if (console.time) {
  10007. console.time(counterName);
  10008. }
  10009. };
  10010. Tools._EndPerformanceConsole = function (counterName, condition) {
  10011. if (condition === void 0) { condition = true; }
  10012. if (!condition) {
  10013. return;
  10014. }
  10015. Tools._EndUserMark(counterName, condition);
  10016. if (console.time) {
  10017. console.timeEnd(counterName);
  10018. }
  10019. };
  10020. Object.defineProperty(Tools, "Now", {
  10021. get: function () {
  10022. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10023. return window.performance.now();
  10024. }
  10025. return Date.now();
  10026. },
  10027. enumerable: true,
  10028. configurable: true
  10029. });
  10030. /**
  10031. * This method will return the name of the class used to create the instance of the given object.
  10032. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10033. * @param object the object to get the class name from
  10034. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  10035. */
  10036. Tools.GetClassName = function (object, isType) {
  10037. if (isType === void 0) { isType = false; }
  10038. var name = null;
  10039. if (!isType && object.getClassName) {
  10040. name = object.getClassName();
  10041. }
  10042. else {
  10043. if (object instanceof Object) {
  10044. var classObj = isType ? object : Object.getPrototypeOf(object);
  10045. name = classObj.constructor["__bjsclassName__"];
  10046. }
  10047. if (!name) {
  10048. name = typeof object;
  10049. }
  10050. }
  10051. return name;
  10052. };
  10053. Tools.First = function (array, predicate) {
  10054. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10055. var el = array_1[_i];
  10056. if (predicate(el)) {
  10057. return el;
  10058. }
  10059. }
  10060. return null;
  10061. };
  10062. /**
  10063. * This method will return the name of the full name of the class, including its owning module (if any).
  10064. * 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).
  10065. * @param object the object to get the class name from
  10066. * @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.
  10067. */
  10068. Tools.getFullClassName = function (object, isType) {
  10069. if (isType === void 0) { isType = false; }
  10070. var className = null;
  10071. var moduleName = null;
  10072. if (!isType && object.getClassName) {
  10073. className = object.getClassName();
  10074. }
  10075. else {
  10076. if (object instanceof Object) {
  10077. var classObj = isType ? object : Object.getPrototypeOf(object);
  10078. className = classObj.constructor["__bjsclassName__"];
  10079. moduleName = classObj.constructor["__bjsmoduleName__"];
  10080. }
  10081. if (!className) {
  10082. className = typeof object;
  10083. }
  10084. }
  10085. if (!className) {
  10086. return null;
  10087. }
  10088. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10089. };
  10090. /**
  10091. * 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.
  10092. * @param array
  10093. */
  10094. Tools.arrayOrStringFeeder = function (array) {
  10095. return function (index) {
  10096. if (index >= array.length) {
  10097. return null;
  10098. }
  10099. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10100. if (val && val.getHashCode) {
  10101. val = val.getHashCode();
  10102. }
  10103. if (typeof val === "string") {
  10104. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10105. }
  10106. return val;
  10107. };
  10108. };
  10109. /**
  10110. * Compute the hashCode of a stream of number
  10111. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10112. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10113. * @return the hash code computed
  10114. */
  10115. Tools.hashCodeFromStream = function (feeder) {
  10116. // Based from here: http://stackoverflow.com/a/7616484/802124
  10117. var hash = 0;
  10118. var index = 0;
  10119. var chr = feeder(index++);
  10120. while (chr != null) {
  10121. hash = ((hash << 5) - hash) + chr;
  10122. hash |= 0; // Convert to 32bit integer
  10123. chr = feeder(index++);
  10124. }
  10125. return hash;
  10126. };
  10127. /**
  10128. * Returns a promise that resolves after the given amount of time.
  10129. * @param delay Number of milliseconds to delay
  10130. * @returns Promise that resolves after the given amount of time
  10131. */
  10132. Tools.DelayAsync = function (delay) {
  10133. return new Promise(function (resolve) {
  10134. setTimeout(function () {
  10135. resolve();
  10136. }, delay);
  10137. });
  10138. };
  10139. /**
  10140. * Gets the current gradient from an array of IValueGradient
  10141. * @param ratio defines the current ratio to get
  10142. * @param gradients defines the array of IValueGradient
  10143. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10144. */
  10145. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10146. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10147. var currentGradient = gradients[gradientIndex];
  10148. var nextGradient = gradients[gradientIndex + 1];
  10149. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10150. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10151. updateFunc(currentGradient, nextGradient, scale);
  10152. return;
  10153. }
  10154. }
  10155. // Use last index if over
  10156. var lastIndex = gradients.length - 1;
  10157. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10158. };
  10159. Tools.BaseUrl = "";
  10160. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10161. /**
  10162. * Default behaviour for cors in the application.
  10163. * It can be a string if the expected behavior is identical in the entire app.
  10164. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10165. */
  10166. Tools.CorsBehavior = "anonymous";
  10167. Tools.UseFallbackTexture = true;
  10168. /**
  10169. * Use this object to register external classes like custom textures or material
  10170. * to allow the laoders to instantiate them
  10171. */
  10172. Tools.RegisteredExternalClasses = {};
  10173. // Used in case of a texture loading problem
  10174. 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";
  10175. Tools._tmpFloatArray = new Float32Array(1);
  10176. Tools.PreprocessUrl = function (url) {
  10177. return url;
  10178. };
  10179. // Logs
  10180. Tools._NoneLogLevel = 0;
  10181. Tools._MessageLogLevel = 1;
  10182. Tools._WarningLogLevel = 2;
  10183. Tools._ErrorLogLevel = 4;
  10184. Tools._LogCache = "";
  10185. Tools.errorsCount = 0;
  10186. Tools.Log = Tools._LogEnabled;
  10187. Tools.Warn = Tools._WarnEnabled;
  10188. Tools.Error = Tools._ErrorEnabled;
  10189. // Performances
  10190. Tools._PerformanceNoneLogLevel = 0;
  10191. Tools._PerformanceUserMarkLogLevel = 1;
  10192. Tools._PerformanceConsoleLogLevel = 2;
  10193. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10194. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10195. return Tools;
  10196. }());
  10197. BABYLON.Tools = Tools;
  10198. /**
  10199. * This class is used to track a performance counter which is number based.
  10200. * The user has access to many properties which give statistics of different nature
  10201. *
  10202. * The implementer can track two kinds of Performance Counter: time and count
  10203. * 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.
  10204. * 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.
  10205. */
  10206. var PerfCounter = /** @class */ (function () {
  10207. function PerfCounter() {
  10208. this._startMonitoringTime = 0;
  10209. this._min = 0;
  10210. this._max = 0;
  10211. this._average = 0;
  10212. this._lastSecAverage = 0;
  10213. this._current = 0;
  10214. this._totalValueCount = 0;
  10215. this._totalAccumulated = 0;
  10216. this._lastSecAccumulated = 0;
  10217. this._lastSecTime = 0;
  10218. this._lastSecValueCount = 0;
  10219. }
  10220. Object.defineProperty(PerfCounter.prototype, "min", {
  10221. /**
  10222. * Returns the smallest value ever
  10223. */
  10224. get: function () {
  10225. return this._min;
  10226. },
  10227. enumerable: true,
  10228. configurable: true
  10229. });
  10230. Object.defineProperty(PerfCounter.prototype, "max", {
  10231. /**
  10232. * Returns the biggest value ever
  10233. */
  10234. get: function () {
  10235. return this._max;
  10236. },
  10237. enumerable: true,
  10238. configurable: true
  10239. });
  10240. Object.defineProperty(PerfCounter.prototype, "average", {
  10241. /**
  10242. * Returns the average value since the performance counter is running
  10243. */
  10244. get: function () {
  10245. return this._average;
  10246. },
  10247. enumerable: true,
  10248. configurable: true
  10249. });
  10250. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10251. /**
  10252. * Returns the average value of the last second the counter was monitored
  10253. */
  10254. get: function () {
  10255. return this._lastSecAverage;
  10256. },
  10257. enumerable: true,
  10258. configurable: true
  10259. });
  10260. Object.defineProperty(PerfCounter.prototype, "current", {
  10261. /**
  10262. * Returns the current value
  10263. */
  10264. get: function () {
  10265. return this._current;
  10266. },
  10267. enumerable: true,
  10268. configurable: true
  10269. });
  10270. Object.defineProperty(PerfCounter.prototype, "total", {
  10271. get: function () {
  10272. return this._totalAccumulated;
  10273. },
  10274. enumerable: true,
  10275. configurable: true
  10276. });
  10277. Object.defineProperty(PerfCounter.prototype, "count", {
  10278. get: function () {
  10279. return this._totalValueCount;
  10280. },
  10281. enumerable: true,
  10282. configurable: true
  10283. });
  10284. /**
  10285. * Call this method to start monitoring a new frame.
  10286. * 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.
  10287. */
  10288. PerfCounter.prototype.fetchNewFrame = function () {
  10289. this._totalValueCount++;
  10290. this._current = 0;
  10291. this._lastSecValueCount++;
  10292. };
  10293. /**
  10294. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10295. * @param newCount the count value to add to the monitored count
  10296. * @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.
  10297. */
  10298. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10299. if (!PerfCounter.Enabled) {
  10300. return;
  10301. }
  10302. this._current += newCount;
  10303. if (fetchResult) {
  10304. this._fetchResult();
  10305. }
  10306. };
  10307. /**
  10308. * Start monitoring this performance counter
  10309. */
  10310. PerfCounter.prototype.beginMonitoring = function () {
  10311. if (!PerfCounter.Enabled) {
  10312. return;
  10313. }
  10314. this._startMonitoringTime = Tools.Now;
  10315. };
  10316. /**
  10317. * Compute the time lapsed since the previous beginMonitoring() call.
  10318. * @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
  10319. */
  10320. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10321. if (newFrame === void 0) { newFrame = true; }
  10322. if (!PerfCounter.Enabled) {
  10323. return;
  10324. }
  10325. if (newFrame) {
  10326. this.fetchNewFrame();
  10327. }
  10328. var currentTime = Tools.Now;
  10329. this._current = currentTime - this._startMonitoringTime;
  10330. if (newFrame) {
  10331. this._fetchResult();
  10332. }
  10333. };
  10334. PerfCounter.prototype._fetchResult = function () {
  10335. this._totalAccumulated += this._current;
  10336. this._lastSecAccumulated += this._current;
  10337. // Min/Max update
  10338. this._min = Math.min(this._min, this._current);
  10339. this._max = Math.max(this._max, this._current);
  10340. this._average = this._totalAccumulated / this._totalValueCount;
  10341. // Reset last sec?
  10342. var now = Tools.Now;
  10343. if ((now - this._lastSecTime) > 1000) {
  10344. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10345. this._lastSecTime = now;
  10346. this._lastSecAccumulated = 0;
  10347. this._lastSecValueCount = 0;
  10348. }
  10349. };
  10350. PerfCounter.Enabled = true;
  10351. return PerfCounter;
  10352. }());
  10353. BABYLON.PerfCounter = PerfCounter;
  10354. /**
  10355. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10356. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10357. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10358. * @param name The name of the class, case should be preserved
  10359. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10360. */
  10361. function className(name, module) {
  10362. return function (target) {
  10363. target["__bjsclassName__"] = name;
  10364. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10365. };
  10366. }
  10367. BABYLON.className = className;
  10368. /**
  10369. * An implementation of a loop for asynchronous functions.
  10370. */
  10371. var AsyncLoop = /** @class */ (function () {
  10372. /**
  10373. * Constroctor.
  10374. * @param iterations the number of iterations.
  10375. * @param _fn the function to run each iteration
  10376. * @param _successCallback the callback that will be called upon succesful execution
  10377. * @param offset starting offset.
  10378. */
  10379. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10380. if (offset === void 0) { offset = 0; }
  10381. this.iterations = iterations;
  10382. this._fn = _fn;
  10383. this._successCallback = _successCallback;
  10384. this.index = offset - 1;
  10385. this._done = false;
  10386. }
  10387. /**
  10388. * Execute the next iteration. Must be called after the last iteration was finished.
  10389. */
  10390. AsyncLoop.prototype.executeNext = function () {
  10391. if (!this._done) {
  10392. if (this.index + 1 < this.iterations) {
  10393. ++this.index;
  10394. this._fn(this);
  10395. }
  10396. else {
  10397. this.breakLoop();
  10398. }
  10399. }
  10400. };
  10401. /**
  10402. * Break the loop and run the success callback.
  10403. */
  10404. AsyncLoop.prototype.breakLoop = function () {
  10405. this._done = true;
  10406. this._successCallback();
  10407. };
  10408. /**
  10409. * Helper function
  10410. */
  10411. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10412. if (offset === void 0) { offset = 0; }
  10413. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10414. loop.executeNext();
  10415. return loop;
  10416. };
  10417. /**
  10418. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10419. * @param iterations total number of iterations
  10420. * @param syncedIterations number of synchronous iterations in each async iteration.
  10421. * @param fn the function to call each iteration.
  10422. * @param callback a success call back that will be called when iterating stops.
  10423. * @param breakFunction a break condition (optional)
  10424. * @param timeout timeout settings for the setTimeout function. default - 0.
  10425. * @constructor
  10426. */
  10427. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10428. if (timeout === void 0) { timeout = 0; }
  10429. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10430. if (breakFunction && breakFunction())
  10431. loop.breakLoop();
  10432. else {
  10433. setTimeout(function () {
  10434. for (var i = 0; i < syncedIterations; ++i) {
  10435. var iteration = (loop.index * syncedIterations) + i;
  10436. if (iteration >= iterations)
  10437. break;
  10438. fn(iteration);
  10439. if (breakFunction && breakFunction()) {
  10440. loop.breakLoop();
  10441. break;
  10442. }
  10443. }
  10444. loop.executeNext();
  10445. }, timeout);
  10446. }
  10447. }, callback);
  10448. };
  10449. return AsyncLoop;
  10450. }());
  10451. BABYLON.AsyncLoop = AsyncLoop;
  10452. })(BABYLON || (BABYLON = {}));
  10453. //# sourceMappingURL=babylon.tools.js.map
  10454. var BABYLON;
  10455. (function (BABYLON) {
  10456. var PromiseStates;
  10457. (function (PromiseStates) {
  10458. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10459. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10460. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10461. })(PromiseStates || (PromiseStates = {}));
  10462. var FulFillmentAgregator = /** @class */ (function () {
  10463. function FulFillmentAgregator() {
  10464. this.count = 0;
  10465. this.target = 0;
  10466. this.results = [];
  10467. }
  10468. return FulFillmentAgregator;
  10469. }());
  10470. var InternalPromise = /** @class */ (function () {
  10471. function InternalPromise(resolver) {
  10472. var _this = this;
  10473. this._state = PromiseStates.Pending;
  10474. this._children = new Array();
  10475. this._rejectWasConsumed = false;
  10476. if (!resolver) {
  10477. return;
  10478. }
  10479. try {
  10480. resolver(function (value) {
  10481. _this._resolve(value);
  10482. }, function (reason) {
  10483. _this._reject(reason);
  10484. });
  10485. }
  10486. catch (e) {
  10487. this._reject(e);
  10488. }
  10489. }
  10490. Object.defineProperty(InternalPromise.prototype, "_result", {
  10491. get: function () {
  10492. return this._resultValue;
  10493. },
  10494. set: function (value) {
  10495. this._resultValue = value;
  10496. if (this._parent && this._parent._result === undefined) {
  10497. this._parent._result = value;
  10498. }
  10499. },
  10500. enumerable: true,
  10501. configurable: true
  10502. });
  10503. InternalPromise.prototype.catch = function (onRejected) {
  10504. return this.then(undefined, onRejected);
  10505. };
  10506. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10507. var _this = this;
  10508. var newPromise = new InternalPromise();
  10509. newPromise._onFulfilled = onFulfilled;
  10510. newPromise._onRejected = onRejected;
  10511. // Composition
  10512. this._children.push(newPromise);
  10513. newPromise._parent = this;
  10514. if (this._state !== PromiseStates.Pending) {
  10515. BABYLON.Tools.SetImmediate(function () {
  10516. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10517. var returnedValue = newPromise._resolve(_this._result);
  10518. if (returnedValue !== undefined && returnedValue !== null) {
  10519. if (returnedValue._state !== undefined) {
  10520. var returnedPromise = returnedValue;
  10521. newPromise._children.push(returnedPromise);
  10522. returnedPromise._parent = newPromise;
  10523. newPromise = returnedPromise;
  10524. }
  10525. else {
  10526. newPromise._result = returnedValue;
  10527. }
  10528. }
  10529. }
  10530. else {
  10531. newPromise._reject(_this._reason);
  10532. }
  10533. });
  10534. }
  10535. return newPromise;
  10536. };
  10537. InternalPromise.prototype._moveChildren = function (children) {
  10538. var _this = this;
  10539. var _a;
  10540. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10541. this._children.forEach(function (child) {
  10542. child._parent = _this;
  10543. });
  10544. if (this._state === PromiseStates.Fulfilled) {
  10545. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10546. var child = _b[_i];
  10547. child._resolve(this._result);
  10548. }
  10549. }
  10550. else if (this._state === PromiseStates.Rejected) {
  10551. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10552. var child = _d[_c];
  10553. child._reject(this._reason);
  10554. }
  10555. }
  10556. };
  10557. InternalPromise.prototype._resolve = function (value) {
  10558. try {
  10559. this._state = PromiseStates.Fulfilled;
  10560. var returnedValue = null;
  10561. if (this._onFulfilled) {
  10562. returnedValue = this._onFulfilled(value);
  10563. }
  10564. if (returnedValue !== undefined && returnedValue !== null) {
  10565. if (returnedValue._state !== undefined) {
  10566. // Transmit children
  10567. var returnedPromise = returnedValue;
  10568. returnedPromise._parent = this;
  10569. returnedPromise._moveChildren(this._children);
  10570. value = returnedPromise._result;
  10571. }
  10572. else {
  10573. value = returnedValue;
  10574. }
  10575. }
  10576. this._result = value;
  10577. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10578. var child = _a[_i];
  10579. child._resolve(value);
  10580. }
  10581. this._children.length = 0;
  10582. delete this._onFulfilled;
  10583. delete this._onRejected;
  10584. }
  10585. catch (e) {
  10586. this._reject(e, true);
  10587. }
  10588. };
  10589. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10590. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10591. this._state = PromiseStates.Rejected;
  10592. this._reason = reason;
  10593. if (this._onRejected && !onLocalThrow) {
  10594. try {
  10595. this._onRejected(reason);
  10596. this._rejectWasConsumed = true;
  10597. }
  10598. catch (e) {
  10599. reason = e;
  10600. }
  10601. }
  10602. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10603. var child = _a[_i];
  10604. if (this._rejectWasConsumed) {
  10605. child._resolve(null);
  10606. }
  10607. else {
  10608. child._reject(reason);
  10609. }
  10610. }
  10611. this._children.length = 0;
  10612. delete this._onFulfilled;
  10613. delete this._onRejected;
  10614. };
  10615. InternalPromise.resolve = function (value) {
  10616. var newPromise = new InternalPromise();
  10617. newPromise._resolve(value);
  10618. return newPromise;
  10619. };
  10620. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10621. promise.then(function (value) {
  10622. agregator.results[index] = value;
  10623. agregator.count++;
  10624. if (agregator.count === agregator.target) {
  10625. agregator.rootPromise._resolve(agregator.results);
  10626. }
  10627. return null;
  10628. }, function (reason) {
  10629. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10630. agregator.rootPromise._reject(reason);
  10631. }
  10632. });
  10633. };
  10634. InternalPromise.all = function (promises) {
  10635. var newPromise = new InternalPromise();
  10636. var agregator = new FulFillmentAgregator();
  10637. agregator.target = promises.length;
  10638. agregator.rootPromise = newPromise;
  10639. if (promises.length) {
  10640. for (var index = 0; index < promises.length; index++) {
  10641. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10642. }
  10643. }
  10644. else {
  10645. newPromise._resolve([]);
  10646. }
  10647. return newPromise;
  10648. };
  10649. InternalPromise.race = function (promises) {
  10650. var newPromise = new InternalPromise();
  10651. if (promises.length) {
  10652. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10653. var promise = promises_1[_i];
  10654. promise.then(function (value) {
  10655. if (newPromise) {
  10656. newPromise._resolve(value);
  10657. newPromise = null;
  10658. }
  10659. return null;
  10660. }, function (reason) {
  10661. if (newPromise) {
  10662. newPromise._reject(reason);
  10663. newPromise = null;
  10664. }
  10665. });
  10666. }
  10667. }
  10668. return newPromise;
  10669. };
  10670. return InternalPromise;
  10671. }());
  10672. /**
  10673. * Helper class that provides a small promise polyfill
  10674. */
  10675. var PromisePolyfill = /** @class */ (function () {
  10676. function PromisePolyfill() {
  10677. }
  10678. /**
  10679. * Static function used to check if the polyfill is required
  10680. * If this is the case then the function will inject the polyfill to window.Promise
  10681. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10682. */
  10683. PromisePolyfill.Apply = function (force) {
  10684. if (force === void 0) { force = false; }
  10685. if (force || typeof Promise === 'undefined') {
  10686. var root = window;
  10687. root.Promise = InternalPromise;
  10688. }
  10689. };
  10690. return PromisePolyfill;
  10691. }());
  10692. BABYLON.PromisePolyfill = PromisePolyfill;
  10693. })(BABYLON || (BABYLON = {}));
  10694. //# sourceMappingURL=babylon.promise.js.map
  10695. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10696. var BABYLON;
  10697. (function (BABYLON) {
  10698. /**
  10699. * Helper class to push actions to a pool of workers.
  10700. */
  10701. var WorkerPool = /** @class */ (function () {
  10702. /**
  10703. * Constructor
  10704. * @param workers Array of workers to use for actions
  10705. */
  10706. function WorkerPool(workers) {
  10707. this._pendingActions = new Array();
  10708. this._workerInfos = workers.map(function (worker) { return ({
  10709. worker: worker,
  10710. active: false
  10711. }); });
  10712. }
  10713. /**
  10714. * Terminates all workers and clears any pending actions.
  10715. */
  10716. WorkerPool.prototype.dispose = function () {
  10717. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10718. var workerInfo = _a[_i];
  10719. workerInfo.worker.terminate();
  10720. }
  10721. delete this._workerInfos;
  10722. delete this._pendingActions;
  10723. };
  10724. /**
  10725. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10726. * pended until a worker has completed its action.
  10727. * @param action The action to perform. Call onComplete when the action is complete.
  10728. */
  10729. WorkerPool.prototype.push = function (action) {
  10730. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10731. var workerInfo = _a[_i];
  10732. if (!workerInfo.active) {
  10733. this._execute(workerInfo, action);
  10734. return;
  10735. }
  10736. }
  10737. this._pendingActions.push(action);
  10738. };
  10739. WorkerPool.prototype._execute = function (workerInfo, action) {
  10740. var _this = this;
  10741. workerInfo.active = true;
  10742. action(workerInfo.worker, function () {
  10743. workerInfo.active = false;
  10744. var nextAction = _this._pendingActions.shift();
  10745. if (nextAction) {
  10746. _this._execute(workerInfo, nextAction);
  10747. }
  10748. });
  10749. };
  10750. return WorkerPool;
  10751. }());
  10752. BABYLON.WorkerPool = WorkerPool;
  10753. })(BABYLON || (BABYLON = {}));
  10754. //# sourceMappingURL=babylon.workerPool.js.map
  10755. var BABYLON;
  10756. (function (BABYLON) {
  10757. /**
  10758. * @hidden
  10759. **/
  10760. var _AlphaState = /** @class */ (function () {
  10761. /**
  10762. * Initializes the state.
  10763. */
  10764. function _AlphaState() {
  10765. this._isAlphaBlendDirty = false;
  10766. this._isBlendFunctionParametersDirty = false;
  10767. this._isBlendEquationParametersDirty = false;
  10768. this._isBlendConstantsDirty = false;
  10769. this._alphaBlend = false;
  10770. this._blendFunctionParameters = new Array(4);
  10771. this._blendEquationParameters = new Array(2);
  10772. this._blendConstants = new Array(4);
  10773. this.reset();
  10774. }
  10775. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10776. get: function () {
  10777. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10778. },
  10779. enumerable: true,
  10780. configurable: true
  10781. });
  10782. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10783. get: function () {
  10784. return this._alphaBlend;
  10785. },
  10786. set: function (value) {
  10787. if (this._alphaBlend === value) {
  10788. return;
  10789. }
  10790. this._alphaBlend = value;
  10791. this._isAlphaBlendDirty = true;
  10792. },
  10793. enumerable: true,
  10794. configurable: true
  10795. });
  10796. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10797. if (this._blendConstants[0] === r &&
  10798. this._blendConstants[1] === g &&
  10799. this._blendConstants[2] === b &&
  10800. this._blendConstants[3] === a) {
  10801. return;
  10802. }
  10803. this._blendConstants[0] = r;
  10804. this._blendConstants[1] = g;
  10805. this._blendConstants[2] = b;
  10806. this._blendConstants[3] = a;
  10807. this._isBlendConstantsDirty = true;
  10808. };
  10809. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10810. if (this._blendFunctionParameters[0] === value0 &&
  10811. this._blendFunctionParameters[1] === value1 &&
  10812. this._blendFunctionParameters[2] === value2 &&
  10813. this._blendFunctionParameters[3] === value3) {
  10814. return;
  10815. }
  10816. this._blendFunctionParameters[0] = value0;
  10817. this._blendFunctionParameters[1] = value1;
  10818. this._blendFunctionParameters[2] = value2;
  10819. this._blendFunctionParameters[3] = value3;
  10820. this._isBlendFunctionParametersDirty = true;
  10821. };
  10822. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10823. if (this._blendEquationParameters[0] === rgb &&
  10824. this._blendEquationParameters[1] === alpha) {
  10825. return;
  10826. }
  10827. this._blendEquationParameters[0] = rgb;
  10828. this._blendEquationParameters[1] = alpha;
  10829. this._isBlendEquationParametersDirty = true;
  10830. };
  10831. _AlphaState.prototype.reset = function () {
  10832. this._alphaBlend = false;
  10833. this._blendFunctionParameters[0] = null;
  10834. this._blendFunctionParameters[1] = null;
  10835. this._blendFunctionParameters[2] = null;
  10836. this._blendFunctionParameters[3] = null;
  10837. this._blendEquationParameters[0] = null;
  10838. this._blendEquationParameters[1] = null;
  10839. this._blendConstants[0] = null;
  10840. this._blendConstants[1] = null;
  10841. this._blendConstants[2] = null;
  10842. this._blendConstants[3] = null;
  10843. this._isAlphaBlendDirty = true;
  10844. this._isBlendFunctionParametersDirty = false;
  10845. this._isBlendEquationParametersDirty = false;
  10846. this._isBlendConstantsDirty = false;
  10847. };
  10848. _AlphaState.prototype.apply = function (gl) {
  10849. if (!this.isDirty) {
  10850. return;
  10851. }
  10852. // Alpha blend
  10853. if (this._isAlphaBlendDirty) {
  10854. if (this._alphaBlend) {
  10855. gl.enable(gl.BLEND);
  10856. }
  10857. else {
  10858. gl.disable(gl.BLEND);
  10859. }
  10860. this._isAlphaBlendDirty = false;
  10861. }
  10862. // Alpha function
  10863. if (this._isBlendFunctionParametersDirty) {
  10864. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10865. this._isBlendFunctionParametersDirty = false;
  10866. }
  10867. // Alpha equation
  10868. if (this._isBlendEquationParametersDirty) {
  10869. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10870. this._isBlendEquationParametersDirty = false;
  10871. }
  10872. // Constants
  10873. if (this._isBlendConstantsDirty) {
  10874. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10875. this._isBlendConstantsDirty = false;
  10876. }
  10877. };
  10878. return _AlphaState;
  10879. }());
  10880. BABYLON._AlphaState = _AlphaState;
  10881. })(BABYLON || (BABYLON = {}));
  10882. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10883. var BABYLON;
  10884. (function (BABYLON) {
  10885. /**
  10886. * @hidden
  10887. **/
  10888. var _DepthCullingState = /** @class */ (function () {
  10889. /**
  10890. * Initializes the state.
  10891. */
  10892. function _DepthCullingState() {
  10893. this._isDepthTestDirty = false;
  10894. this._isDepthMaskDirty = false;
  10895. this._isDepthFuncDirty = false;
  10896. this._isCullFaceDirty = false;
  10897. this._isCullDirty = false;
  10898. this._isZOffsetDirty = false;
  10899. this._isFrontFaceDirty = false;
  10900. this.reset();
  10901. }
  10902. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10903. get: function () {
  10904. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10905. },
  10906. enumerable: true,
  10907. configurable: true
  10908. });
  10909. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10910. get: function () {
  10911. return this._zOffset;
  10912. },
  10913. set: function (value) {
  10914. if (this._zOffset === value) {
  10915. return;
  10916. }
  10917. this._zOffset = value;
  10918. this._isZOffsetDirty = true;
  10919. },
  10920. enumerable: true,
  10921. configurable: true
  10922. });
  10923. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10924. get: function () {
  10925. return this._cullFace;
  10926. },
  10927. set: function (value) {
  10928. if (this._cullFace === value) {
  10929. return;
  10930. }
  10931. this._cullFace = value;
  10932. this._isCullFaceDirty = true;
  10933. },
  10934. enumerable: true,
  10935. configurable: true
  10936. });
  10937. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10938. get: function () {
  10939. return this._cull;
  10940. },
  10941. set: function (value) {
  10942. if (this._cull === value) {
  10943. return;
  10944. }
  10945. this._cull = value;
  10946. this._isCullDirty = true;
  10947. },
  10948. enumerable: true,
  10949. configurable: true
  10950. });
  10951. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10952. get: function () {
  10953. return this._depthFunc;
  10954. },
  10955. set: function (value) {
  10956. if (this._depthFunc === value) {
  10957. return;
  10958. }
  10959. this._depthFunc = value;
  10960. this._isDepthFuncDirty = true;
  10961. },
  10962. enumerable: true,
  10963. configurable: true
  10964. });
  10965. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10966. get: function () {
  10967. return this._depthMask;
  10968. },
  10969. set: function (value) {
  10970. if (this._depthMask === value) {
  10971. return;
  10972. }
  10973. this._depthMask = value;
  10974. this._isDepthMaskDirty = true;
  10975. },
  10976. enumerable: true,
  10977. configurable: true
  10978. });
  10979. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10980. get: function () {
  10981. return this._depthTest;
  10982. },
  10983. set: function (value) {
  10984. if (this._depthTest === value) {
  10985. return;
  10986. }
  10987. this._depthTest = value;
  10988. this._isDepthTestDirty = true;
  10989. },
  10990. enumerable: true,
  10991. configurable: true
  10992. });
  10993. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10994. get: function () {
  10995. return this._frontFace;
  10996. },
  10997. set: function (value) {
  10998. if (this._frontFace === value) {
  10999. return;
  11000. }
  11001. this._frontFace = value;
  11002. this._isFrontFaceDirty = true;
  11003. },
  11004. enumerable: true,
  11005. configurable: true
  11006. });
  11007. _DepthCullingState.prototype.reset = function () {
  11008. this._depthMask = true;
  11009. this._depthTest = true;
  11010. this._depthFunc = null;
  11011. this._cullFace = null;
  11012. this._cull = null;
  11013. this._zOffset = 0;
  11014. this._frontFace = null;
  11015. this._isDepthTestDirty = true;
  11016. this._isDepthMaskDirty = true;
  11017. this._isDepthFuncDirty = false;
  11018. this._isCullFaceDirty = false;
  11019. this._isCullDirty = false;
  11020. this._isZOffsetDirty = false;
  11021. this._isFrontFaceDirty = false;
  11022. };
  11023. _DepthCullingState.prototype.apply = function (gl) {
  11024. if (!this.isDirty) {
  11025. return;
  11026. }
  11027. // Cull
  11028. if (this._isCullDirty) {
  11029. if (this.cull) {
  11030. gl.enable(gl.CULL_FACE);
  11031. }
  11032. else {
  11033. gl.disable(gl.CULL_FACE);
  11034. }
  11035. this._isCullDirty = false;
  11036. }
  11037. // Cull face
  11038. if (this._isCullFaceDirty) {
  11039. gl.cullFace(this.cullFace);
  11040. this._isCullFaceDirty = false;
  11041. }
  11042. // Depth mask
  11043. if (this._isDepthMaskDirty) {
  11044. gl.depthMask(this.depthMask);
  11045. this._isDepthMaskDirty = false;
  11046. }
  11047. // Depth test
  11048. if (this._isDepthTestDirty) {
  11049. if (this.depthTest) {
  11050. gl.enable(gl.DEPTH_TEST);
  11051. }
  11052. else {
  11053. gl.disable(gl.DEPTH_TEST);
  11054. }
  11055. this._isDepthTestDirty = false;
  11056. }
  11057. // Depth func
  11058. if (this._isDepthFuncDirty) {
  11059. gl.depthFunc(this.depthFunc);
  11060. this._isDepthFuncDirty = false;
  11061. }
  11062. // zOffset
  11063. if (this._isZOffsetDirty) {
  11064. if (this.zOffset) {
  11065. gl.enable(gl.POLYGON_OFFSET_FILL);
  11066. gl.polygonOffset(this.zOffset, 0);
  11067. }
  11068. else {
  11069. gl.disable(gl.POLYGON_OFFSET_FILL);
  11070. }
  11071. this._isZOffsetDirty = false;
  11072. }
  11073. // Front face
  11074. if (this._isFrontFaceDirty) {
  11075. gl.frontFace(this.frontFace);
  11076. this._isFrontFaceDirty = false;
  11077. }
  11078. };
  11079. return _DepthCullingState;
  11080. }());
  11081. BABYLON._DepthCullingState = _DepthCullingState;
  11082. })(BABYLON || (BABYLON = {}));
  11083. //# sourceMappingURL=babylon.depthCullingState.js.map
  11084. var BABYLON;
  11085. (function (BABYLON) {
  11086. /**
  11087. * @hidden
  11088. **/
  11089. var _StencilState = /** @class */ (function () {
  11090. function _StencilState() {
  11091. this._isStencilTestDirty = false;
  11092. this._isStencilMaskDirty = false;
  11093. this._isStencilFuncDirty = false;
  11094. this._isStencilOpDirty = false;
  11095. this.reset();
  11096. }
  11097. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11098. get: function () {
  11099. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11100. },
  11101. enumerable: true,
  11102. configurable: true
  11103. });
  11104. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11105. get: function () {
  11106. return this._stencilFunc;
  11107. },
  11108. set: function (value) {
  11109. if (this._stencilFunc === value) {
  11110. return;
  11111. }
  11112. this._stencilFunc = value;
  11113. this._isStencilFuncDirty = true;
  11114. },
  11115. enumerable: true,
  11116. configurable: true
  11117. });
  11118. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11119. get: function () {
  11120. return this._stencilFuncRef;
  11121. },
  11122. set: function (value) {
  11123. if (this._stencilFuncRef === value) {
  11124. return;
  11125. }
  11126. this._stencilFuncRef = value;
  11127. this._isStencilFuncDirty = true;
  11128. },
  11129. enumerable: true,
  11130. configurable: true
  11131. });
  11132. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11133. get: function () {
  11134. return this._stencilFuncMask;
  11135. },
  11136. set: function (value) {
  11137. if (this._stencilFuncMask === value) {
  11138. return;
  11139. }
  11140. this._stencilFuncMask = value;
  11141. this._isStencilFuncDirty = true;
  11142. },
  11143. enumerable: true,
  11144. configurable: true
  11145. });
  11146. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11147. get: function () {
  11148. return this._stencilOpStencilFail;
  11149. },
  11150. set: function (value) {
  11151. if (this._stencilOpStencilFail === value) {
  11152. return;
  11153. }
  11154. this._stencilOpStencilFail = value;
  11155. this._isStencilOpDirty = true;
  11156. },
  11157. enumerable: true,
  11158. configurable: true
  11159. });
  11160. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11161. get: function () {
  11162. return this._stencilOpDepthFail;
  11163. },
  11164. set: function (value) {
  11165. if (this._stencilOpDepthFail === value) {
  11166. return;
  11167. }
  11168. this._stencilOpDepthFail = value;
  11169. this._isStencilOpDirty = true;
  11170. },
  11171. enumerable: true,
  11172. configurable: true
  11173. });
  11174. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11175. get: function () {
  11176. return this._stencilOpStencilDepthPass;
  11177. },
  11178. set: function (value) {
  11179. if (this._stencilOpStencilDepthPass === value) {
  11180. return;
  11181. }
  11182. this._stencilOpStencilDepthPass = value;
  11183. this._isStencilOpDirty = true;
  11184. },
  11185. enumerable: true,
  11186. configurable: true
  11187. });
  11188. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11189. get: function () {
  11190. return this._stencilMask;
  11191. },
  11192. set: function (value) {
  11193. if (this._stencilMask === value) {
  11194. return;
  11195. }
  11196. this._stencilMask = value;
  11197. this._isStencilMaskDirty = true;
  11198. },
  11199. enumerable: true,
  11200. configurable: true
  11201. });
  11202. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11203. get: function () {
  11204. return this._stencilTest;
  11205. },
  11206. set: function (value) {
  11207. if (this._stencilTest === value) {
  11208. return;
  11209. }
  11210. this._stencilTest = value;
  11211. this._isStencilTestDirty = true;
  11212. },
  11213. enumerable: true,
  11214. configurable: true
  11215. });
  11216. _StencilState.prototype.reset = function () {
  11217. this._stencilTest = false;
  11218. this._stencilMask = 0xFF;
  11219. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11220. this._stencilFuncRef = 1;
  11221. this._stencilFuncMask = 0xFF;
  11222. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11223. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11224. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11225. this._isStencilTestDirty = true;
  11226. this._isStencilMaskDirty = true;
  11227. this._isStencilFuncDirty = true;
  11228. this._isStencilOpDirty = true;
  11229. };
  11230. _StencilState.prototype.apply = function (gl) {
  11231. if (!this.isDirty) {
  11232. return;
  11233. }
  11234. // Stencil test
  11235. if (this._isStencilTestDirty) {
  11236. if (this.stencilTest) {
  11237. gl.enable(gl.STENCIL_TEST);
  11238. }
  11239. else {
  11240. gl.disable(gl.STENCIL_TEST);
  11241. }
  11242. this._isStencilTestDirty = false;
  11243. }
  11244. // Stencil mask
  11245. if (this._isStencilMaskDirty) {
  11246. gl.stencilMask(this.stencilMask);
  11247. this._isStencilMaskDirty = false;
  11248. }
  11249. // Stencil func
  11250. if (this._isStencilFuncDirty) {
  11251. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11252. this._isStencilFuncDirty = false;
  11253. }
  11254. // Stencil op
  11255. if (this._isStencilOpDirty) {
  11256. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11257. this._isStencilOpDirty = false;
  11258. }
  11259. };
  11260. return _StencilState;
  11261. }());
  11262. BABYLON._StencilState = _StencilState;
  11263. })(BABYLON || (BABYLON = {}));
  11264. //# sourceMappingURL=babylon.stencilState.js.map
  11265. var __assign = (this && this.__assign) || function () {
  11266. __assign = Object.assign || function(t) {
  11267. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11268. s = arguments[i];
  11269. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11270. t[p] = s[p];
  11271. }
  11272. return t;
  11273. };
  11274. return __assign.apply(this, arguments);
  11275. };
  11276. var BABYLON;
  11277. (function (BABYLON) {
  11278. /**
  11279. * Keeps track of all the buffer info used in engine.
  11280. */
  11281. var BufferPointer = /** @class */ (function () {
  11282. function BufferPointer() {
  11283. }
  11284. return BufferPointer;
  11285. }());
  11286. /**
  11287. * Interface for attribute information associated with buffer instanciation
  11288. */
  11289. var InstancingAttributeInfo = /** @class */ (function () {
  11290. function InstancingAttributeInfo() {
  11291. }
  11292. return InstancingAttributeInfo;
  11293. }());
  11294. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11295. /**
  11296. * Define options used to create a render target texture
  11297. */
  11298. var RenderTargetCreationOptions = /** @class */ (function () {
  11299. function RenderTargetCreationOptions() {
  11300. }
  11301. return RenderTargetCreationOptions;
  11302. }());
  11303. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11304. /**
  11305. * Define options used to create a depth texture
  11306. */
  11307. var DepthTextureCreationOptions = /** @class */ (function () {
  11308. function DepthTextureCreationOptions() {
  11309. }
  11310. return DepthTextureCreationOptions;
  11311. }());
  11312. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11313. /**
  11314. * Class used to describe the capabilities of the engine relatively to the current browser
  11315. */
  11316. var EngineCapabilities = /** @class */ (function () {
  11317. function EngineCapabilities() {
  11318. }
  11319. return EngineCapabilities;
  11320. }());
  11321. BABYLON.EngineCapabilities = EngineCapabilities;
  11322. /**
  11323. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11324. */
  11325. var Engine = /** @class */ (function () {
  11326. /**
  11327. * Creates a new engine
  11328. * @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
  11329. * @param antialias defines enable antialiasing (default: false)
  11330. * @param options defines further options to be sent to the getContext() function
  11331. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11332. */
  11333. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11334. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11335. var _this = this;
  11336. // Public members
  11337. /**
  11338. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11339. */
  11340. this.forcePOTTextures = false;
  11341. /**
  11342. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11343. */
  11344. this.isFullscreen = false;
  11345. /**
  11346. * Gets a boolean indicating if the pointer is currently locked
  11347. */
  11348. this.isPointerLock = false;
  11349. /**
  11350. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11351. */
  11352. this.cullBackFaces = true;
  11353. /**
  11354. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11355. */
  11356. this.renderEvenInBackground = true;
  11357. /**
  11358. * Gets or sets a boolean indicating that cache can be kept between frames
  11359. */
  11360. this.preventCacheWipeBetweenFrames = false;
  11361. /**
  11362. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11363. **/
  11364. this.enableOfflineSupport = false;
  11365. /**
  11366. * 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)
  11367. **/
  11368. this.disableManifestCheck = false;
  11369. /**
  11370. * Gets the list of created scenes
  11371. */
  11372. this.scenes = new Array();
  11373. /**
  11374. * Gets the list of created postprocesses
  11375. */
  11376. this.postProcesses = new Array();
  11377. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11378. this.validateShaderPrograms = false;
  11379. // Observables
  11380. /**
  11381. * Observable event triggered each time the rendering canvas is resized
  11382. */
  11383. this.onResizeObservable = new BABYLON.Observable();
  11384. /**
  11385. * Observable event triggered each time the canvas loses focus
  11386. */
  11387. this.onCanvasBlurObservable = new BABYLON.Observable();
  11388. /**
  11389. * Observable event triggered each time the canvas gains focus
  11390. */
  11391. this.onCanvasFocusObservable = new BABYLON.Observable();
  11392. /**
  11393. * Observable event triggered each time the canvas receives pointerout event
  11394. */
  11395. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11396. /**
  11397. * Observable event triggered before each texture is initialized
  11398. */
  11399. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11400. //WebVR
  11401. this._vrDisplay = undefined;
  11402. this._vrSupported = false;
  11403. this._vrExclusivePointerMode = false;
  11404. // Uniform buffers list
  11405. /**
  11406. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11407. */
  11408. this.disableUniformBuffers = false;
  11409. /** @hidden */
  11410. this._uniformBuffers = new Array();
  11411. // Observables
  11412. /**
  11413. * Observable raised when the engine begins a new frame
  11414. */
  11415. this.onBeginFrameObservable = new BABYLON.Observable();
  11416. /**
  11417. * Observable raised when the engine ends the current frame
  11418. */
  11419. this.onEndFrameObservable = new BABYLON.Observable();
  11420. /**
  11421. * Observable raised when the engine is about to compile a shader
  11422. */
  11423. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11424. /**
  11425. * Observable raised when the engine has jsut compiled a shader
  11426. */
  11427. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11428. this._windowIsBackground = false;
  11429. this._webGLVersion = 1.0;
  11430. /** @hidden */
  11431. this._badOS = false;
  11432. /** @hidden */
  11433. this._badDesktopOS = false;
  11434. /**
  11435. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11436. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11437. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11438. */
  11439. this.disableTextureBindingOptimization = false;
  11440. /**
  11441. * Observable signaled when VR display mode changes
  11442. */
  11443. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11444. /**
  11445. * Observable signaled when VR request present is complete
  11446. */
  11447. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11448. /**
  11449. * Observable signaled when VR request present starts
  11450. */
  11451. this.onVRRequestPresentStart = new BABYLON.Observable();
  11452. this._colorWrite = true;
  11453. /** @hidden */
  11454. this._drawCalls = new BABYLON.PerfCounter();
  11455. /** @hidden */
  11456. this._textureCollisions = new BABYLON.PerfCounter();
  11457. this._renderingQueueLaunched = false;
  11458. this._activeRenderLoops = new Array();
  11459. // Deterministic lockstepMaxSteps
  11460. this._deterministicLockstep = false;
  11461. this._lockstepMaxSteps = 4;
  11462. // Lost context
  11463. /**
  11464. * Observable signaled when a context lost event is raised
  11465. */
  11466. this.onContextLostObservable = new BABYLON.Observable();
  11467. /**
  11468. * Observable signaled when a context restored event is raised
  11469. */
  11470. this.onContextRestoredObservable = new BABYLON.Observable();
  11471. this._contextWasLost = false;
  11472. this._doNotHandleContextLost = false;
  11473. // FPS
  11474. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11475. this._fps = 60;
  11476. this._deltaTime = 0;
  11477. /**
  11478. * Turn this value on if you want to pause FPS computation when in background
  11479. */
  11480. this.disablePerformanceMonitorInBackground = false;
  11481. // States
  11482. /** @hidden */
  11483. this._depthCullingState = new BABYLON._DepthCullingState();
  11484. /** @hidden */
  11485. this._stencilState = new BABYLON._StencilState();
  11486. /** @hidden */
  11487. this._alphaState = new BABYLON._AlphaState();
  11488. /** @hidden */
  11489. this._alphaMode = Engine.ALPHA_DISABLE;
  11490. // Cache
  11491. this._internalTexturesCache = new Array();
  11492. /** @hidden */
  11493. this._activeChannel = 0;
  11494. this._currentTextureChannel = -1;
  11495. /** @hidden */
  11496. this._boundTexturesCache = {};
  11497. this._compiledEffects = {};
  11498. this._vertexAttribArraysEnabled = [];
  11499. this._uintIndicesCurrentlySet = false;
  11500. this._currentBoundBuffer = new Array();
  11501. /** @hidden */
  11502. this._currentFramebuffer = null;
  11503. this._currentBufferPointers = new Array();
  11504. this._currentInstanceLocations = new Array();
  11505. this._currentInstanceBuffers = new Array();
  11506. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11507. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11508. this._vaoRecordInProgress = false;
  11509. this._mustWipeVertexAttributes = false;
  11510. this._nextFreeTextureSlots = new Array();
  11511. this._maxSimultaneousTextures = 0;
  11512. this._activeRequests = new Array();
  11513. // Hardware supported Compressed Textures
  11514. this._texturesSupported = new Array();
  11515. /**
  11516. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11517. */
  11518. this.premultipliedAlpha = true;
  11519. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11520. this._onVRFullScreenTriggered = function () {
  11521. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11522. //get the old size before we change
  11523. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11524. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11525. //get the width and height, change the render size
  11526. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11527. _this.setHardwareScalingLevel(1);
  11528. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11529. }
  11530. else {
  11531. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11532. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11533. }
  11534. };
  11535. this._unpackFlipYCached = null;
  11536. /**
  11537. * In case you are sharing the context with other applications, it might
  11538. * be interested to not cache the unpack flip y state to ensure a consistent
  11539. * value would be set.
  11540. */
  11541. this.enableUnpackFlipYCached = true;
  11542. this._boundUniforms = {};
  11543. // Register promises
  11544. BABYLON.PromisePolyfill.Apply();
  11545. var canvas = null;
  11546. Engine.Instances.push(this);
  11547. if (!canvasOrContext) {
  11548. return;
  11549. }
  11550. options = options || {};
  11551. if (canvasOrContext.getContext) {
  11552. canvas = canvasOrContext;
  11553. this._renderingCanvas = canvas;
  11554. if (antialias != null) {
  11555. options.antialias = antialias;
  11556. }
  11557. if (options.deterministicLockstep === undefined) {
  11558. options.deterministicLockstep = false;
  11559. }
  11560. if (options.lockstepMaxSteps === undefined) {
  11561. options.lockstepMaxSteps = 4;
  11562. }
  11563. if (options.preserveDrawingBuffer === undefined) {
  11564. options.preserveDrawingBuffer = false;
  11565. }
  11566. if (options.audioEngine === undefined) {
  11567. options.audioEngine = true;
  11568. }
  11569. if (options.stencil === undefined) {
  11570. options.stencil = true;
  11571. }
  11572. if (options.premultipliedAlpha === false) {
  11573. this.premultipliedAlpha = false;
  11574. }
  11575. this._deterministicLockstep = options.deterministicLockstep;
  11576. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11577. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11578. // Exceptions
  11579. if (navigator && navigator.userAgent) {
  11580. var ua = navigator.userAgent;
  11581. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11582. var exception = _a[_i];
  11583. var key = exception.key;
  11584. var targets = exception.targets;
  11585. if (ua.indexOf(key) > -1) {
  11586. if (exception.capture && exception.captureConstraint) {
  11587. var capture = exception.capture;
  11588. var constraint = exception.captureConstraint;
  11589. var regex = new RegExp(capture);
  11590. var matches = regex.exec(ua);
  11591. if (matches && matches.length > 0) {
  11592. var capturedValue = parseInt(matches[matches.length - 1]);
  11593. if (capturedValue >= constraint) {
  11594. continue;
  11595. }
  11596. }
  11597. }
  11598. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11599. var target = targets_1[_b];
  11600. switch (target) {
  11601. case "uniformBuffer":
  11602. this.disableUniformBuffers = true;
  11603. break;
  11604. case "textureBindingOptimization":
  11605. this.disableTextureBindingOptimization = true;
  11606. break;
  11607. }
  11608. }
  11609. }
  11610. }
  11611. }
  11612. // GL
  11613. if (!options.disableWebGL2Support) {
  11614. try {
  11615. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11616. if (this._gl) {
  11617. this._webGLVersion = 2.0;
  11618. }
  11619. }
  11620. catch (e) {
  11621. // Do nothing
  11622. }
  11623. }
  11624. if (!this._gl) {
  11625. if (!canvas) {
  11626. throw new Error("The provided canvas is null or undefined.");
  11627. }
  11628. try {
  11629. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11630. }
  11631. catch (e) {
  11632. throw new Error("WebGL not supported");
  11633. }
  11634. }
  11635. if (!this._gl) {
  11636. throw new Error("WebGL not supported");
  11637. }
  11638. this._onCanvasFocus = function () {
  11639. _this.onCanvasFocusObservable.notifyObservers(_this);
  11640. };
  11641. this._onCanvasBlur = function () {
  11642. _this.onCanvasBlurObservable.notifyObservers(_this);
  11643. };
  11644. canvas.addEventListener("focus", this._onCanvasFocus);
  11645. canvas.addEventListener("blur", this._onCanvasBlur);
  11646. this._onBlur = function () {
  11647. if (_this.disablePerformanceMonitorInBackground) {
  11648. _this._performanceMonitor.disable();
  11649. }
  11650. _this._windowIsBackground = true;
  11651. };
  11652. this._onFocus = function () {
  11653. if (_this.disablePerformanceMonitorInBackground) {
  11654. _this._performanceMonitor.enable();
  11655. }
  11656. _this._windowIsBackground = false;
  11657. };
  11658. this._onCanvasPointerOut = function (ev) {
  11659. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11660. };
  11661. window.addEventListener("blur", this._onBlur);
  11662. window.addEventListener("focus", this._onFocus);
  11663. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11664. // Context lost
  11665. if (!this._doNotHandleContextLost) {
  11666. this._onContextLost = function (evt) {
  11667. evt.preventDefault();
  11668. _this._contextWasLost = true;
  11669. BABYLON.Tools.Warn("WebGL context lost.");
  11670. _this.onContextLostObservable.notifyObservers(_this);
  11671. };
  11672. this._onContextRestored = function (evt) {
  11673. // Adding a timeout to avoid race condition at browser level
  11674. setTimeout(function () {
  11675. // Rebuild gl context
  11676. _this._initGLContext();
  11677. // Rebuild effects
  11678. _this._rebuildEffects();
  11679. // Rebuild textures
  11680. _this._rebuildInternalTextures();
  11681. // Rebuild buffers
  11682. _this._rebuildBuffers();
  11683. // Cache
  11684. _this.wipeCaches(true);
  11685. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11686. _this.onContextRestoredObservable.notifyObservers(_this);
  11687. _this._contextWasLost = false;
  11688. }, 0);
  11689. };
  11690. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11691. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11692. }
  11693. }
  11694. else {
  11695. this._gl = canvasOrContext;
  11696. this._renderingCanvas = this._gl.canvas;
  11697. if (this._gl.renderbufferStorageMultisample) {
  11698. this._webGLVersion = 2.0;
  11699. }
  11700. options.stencil = this._gl.getContextAttributes().stencil;
  11701. }
  11702. // Viewport
  11703. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11704. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11705. this.resize();
  11706. this._isStencilEnable = options.stencil ? true : false;
  11707. this._initGLContext();
  11708. if (canvas) {
  11709. // Fullscreen
  11710. this._onFullscreenChange = function () {
  11711. if (document.fullscreen !== undefined) {
  11712. _this.isFullscreen = document.fullscreen;
  11713. }
  11714. else if (document.mozFullScreen !== undefined) {
  11715. _this.isFullscreen = document.mozFullScreen;
  11716. }
  11717. else if (document.webkitIsFullScreen !== undefined) {
  11718. _this.isFullscreen = document.webkitIsFullScreen;
  11719. }
  11720. else if (document.msIsFullScreen !== undefined) {
  11721. _this.isFullscreen = document.msIsFullScreen;
  11722. }
  11723. // Pointer lock
  11724. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11725. canvas.requestPointerLock = canvas.requestPointerLock ||
  11726. canvas.msRequestPointerLock ||
  11727. canvas.mozRequestPointerLock ||
  11728. canvas.webkitRequestPointerLock;
  11729. if (canvas.requestPointerLock) {
  11730. canvas.requestPointerLock();
  11731. }
  11732. }
  11733. };
  11734. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11735. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11736. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11737. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11738. // Pointer lock
  11739. this._onPointerLockChange = function () {
  11740. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11741. document.webkitPointerLockElement === canvas ||
  11742. document.msPointerLockElement === canvas ||
  11743. document.pointerLockElement === canvas);
  11744. };
  11745. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11746. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11747. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11748. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11749. this._onVRDisplayPointerRestricted = function () {
  11750. if (canvas) {
  11751. canvas.requestPointerLock();
  11752. }
  11753. };
  11754. this._onVRDisplayPointerUnrestricted = function () {
  11755. document.exitPointerLock();
  11756. };
  11757. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11758. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11759. }
  11760. // Create Audio Engine if needed.
  11761. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  11762. Engine.audioEngine = Engine.AudioEngineFactory();
  11763. }
  11764. // Prepare buffer pointers
  11765. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11766. this._currentBufferPointers[i] = new BufferPointer();
  11767. }
  11768. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11769. // Load WebVR Devices
  11770. if (options.autoEnableWebVR) {
  11771. this.initWebVR();
  11772. }
  11773. // Detect if we are running on a faulty buggy OS.
  11774. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11775. // Detect if we are running on a faulty buggy desktop OS.
  11776. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11777. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11778. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11779. }
  11780. Object.defineProperty(Engine, "LastCreatedEngine", {
  11781. /**
  11782. * Gets the latest created engine
  11783. */
  11784. get: function () {
  11785. if (Engine.Instances.length === 0) {
  11786. return null;
  11787. }
  11788. return Engine.Instances[Engine.Instances.length - 1];
  11789. },
  11790. enumerable: true,
  11791. configurable: true
  11792. });
  11793. Object.defineProperty(Engine, "LastCreatedScene", {
  11794. /**
  11795. * Gets the latest created scene
  11796. */
  11797. get: function () {
  11798. var lastCreatedEngine = Engine.LastCreatedEngine;
  11799. if (!lastCreatedEngine) {
  11800. return null;
  11801. }
  11802. if (lastCreatedEngine.scenes.length === 0) {
  11803. return null;
  11804. }
  11805. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11806. },
  11807. enumerable: true,
  11808. configurable: true
  11809. });
  11810. /**
  11811. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11812. * @param flag defines which part of the materials must be marked as dirty
  11813. * @param predicate defines a predicate used to filter which materials should be affected
  11814. */
  11815. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11816. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11817. var engine = Engine.Instances[engineIndex];
  11818. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11819. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11820. }
  11821. }
  11822. };
  11823. Object.defineProperty(Engine, "Version", {
  11824. /**
  11825. * Returns the current version of the framework
  11826. */
  11827. get: function () {
  11828. return "3.3.0-beta.5";
  11829. },
  11830. enumerable: true,
  11831. configurable: true
  11832. });
  11833. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11834. /**
  11835. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11836. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11837. */
  11838. get: function () {
  11839. return this._vrExclusivePointerMode;
  11840. },
  11841. enumerable: true,
  11842. configurable: true
  11843. });
  11844. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11845. /**
  11846. * Gets a boolean indicating that the engine supports uniform buffers
  11847. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11848. */
  11849. get: function () {
  11850. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11851. },
  11852. enumerable: true,
  11853. configurable: true
  11854. });
  11855. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11856. /**
  11857. * Gets a boolean indicating that only power of 2 textures are supported
  11858. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11859. */
  11860. get: function () {
  11861. return this._webGLVersion < 2 || this.forcePOTTextures;
  11862. },
  11863. enumerable: true,
  11864. configurable: true
  11865. });
  11866. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11867. /**
  11868. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11869. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11870. */
  11871. get: function () {
  11872. return this._doNotHandleContextLost;
  11873. },
  11874. set: function (value) {
  11875. this._doNotHandleContextLost = value;
  11876. },
  11877. enumerable: true,
  11878. configurable: true
  11879. });
  11880. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11881. /**
  11882. * Gets the performance monitor attached to this engine
  11883. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11884. */
  11885. get: function () {
  11886. return this._performanceMonitor;
  11887. },
  11888. enumerable: true,
  11889. configurable: true
  11890. });
  11891. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11892. /**
  11893. * Gets the list of texture formats supported
  11894. */
  11895. get: function () {
  11896. return this._texturesSupported;
  11897. },
  11898. enumerable: true,
  11899. configurable: true
  11900. });
  11901. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11902. /**
  11903. * Gets the list of texture formats in use
  11904. */
  11905. get: function () {
  11906. return this._textureFormatInUse;
  11907. },
  11908. enumerable: true,
  11909. configurable: true
  11910. });
  11911. Object.defineProperty(Engine.prototype, "currentViewport", {
  11912. /**
  11913. * Gets the current viewport
  11914. */
  11915. get: function () {
  11916. return this._cachedViewport;
  11917. },
  11918. enumerable: true,
  11919. configurable: true
  11920. });
  11921. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11922. /**
  11923. * Gets the default empty texture
  11924. */
  11925. get: function () {
  11926. if (!this._emptyTexture) {
  11927. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11928. }
  11929. return this._emptyTexture;
  11930. },
  11931. enumerable: true,
  11932. configurable: true
  11933. });
  11934. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11935. /**
  11936. * Gets the default empty 3D texture
  11937. */
  11938. get: function () {
  11939. if (!this._emptyTexture3D) {
  11940. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11941. }
  11942. return this._emptyTexture3D;
  11943. },
  11944. enumerable: true,
  11945. configurable: true
  11946. });
  11947. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11948. /**
  11949. * Gets the default empty cube texture
  11950. */
  11951. get: function () {
  11952. if (!this._emptyCubeTexture) {
  11953. var faceData = new Uint8Array(4);
  11954. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11955. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11956. }
  11957. return this._emptyCubeTexture;
  11958. },
  11959. enumerable: true,
  11960. configurable: true
  11961. });
  11962. Engine.prototype._rebuildInternalTextures = function () {
  11963. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11964. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11965. var internalTexture = currentState_1[_i];
  11966. internalTexture._rebuild();
  11967. }
  11968. };
  11969. Engine.prototype._rebuildEffects = function () {
  11970. for (var key in this._compiledEffects) {
  11971. var effect = this._compiledEffects[key];
  11972. effect._prepareEffect();
  11973. }
  11974. BABYLON.Effect.ResetCache();
  11975. };
  11976. Engine.prototype._rebuildBuffers = function () {
  11977. // Index / Vertex
  11978. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11979. var scene = _a[_i];
  11980. scene.resetCachedMaterial();
  11981. scene._rebuildGeometries();
  11982. scene._rebuildTextures();
  11983. }
  11984. // Uniforms
  11985. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11986. var uniformBuffer = _c[_b];
  11987. uniformBuffer._rebuild();
  11988. }
  11989. };
  11990. Engine.prototype._initGLContext = function () {
  11991. // Caps
  11992. this._caps = new EngineCapabilities();
  11993. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11994. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11995. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11996. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11997. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11998. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11999. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12000. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12001. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12002. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12003. // Infos
  12004. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12005. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12006. if (rendererInfo != null) {
  12007. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12008. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12009. }
  12010. if (!this._glVendor) {
  12011. this._glVendor = "Unknown vendor";
  12012. }
  12013. if (!this._glRenderer) {
  12014. this._glRenderer = "Unknown renderer";
  12015. }
  12016. // Constants
  12017. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12018. if (this._gl.RGBA16F !== 0x881A) {
  12019. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12020. }
  12021. if (this._gl.RGBA32F !== 0x8814) {
  12022. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12023. }
  12024. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12025. this._gl.DEPTH24_STENCIL8 = 35056;
  12026. }
  12027. // Extensions
  12028. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12029. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12030. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12031. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12032. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12033. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12034. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12035. 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');
  12036. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12037. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12038. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12039. this._caps.highPrecisionShaderSupported = true;
  12040. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12041. if (this._caps.timerQuery) {
  12042. if (this._webGLVersion === 1) {
  12043. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12044. }
  12045. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12046. }
  12047. // Checks if some of the format renders first to allow the use of webgl inspector.
  12048. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12049. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12050. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12051. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12052. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12053. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12054. if (this._webGLVersion > 1) {
  12055. this._gl.HALF_FLOAT_OES = 0x140B;
  12056. }
  12057. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12058. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12059. // Draw buffers
  12060. if (this._webGLVersion > 1) {
  12061. this._caps.drawBuffersExtension = true;
  12062. }
  12063. else {
  12064. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12065. if (drawBuffersExtension !== null) {
  12066. this._caps.drawBuffersExtension = true;
  12067. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12068. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12069. for (var i = 0; i < 16; i++) {
  12070. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12071. }
  12072. }
  12073. else {
  12074. this._caps.drawBuffersExtension = false;
  12075. }
  12076. }
  12077. // Depth Texture
  12078. if (this._webGLVersion > 1) {
  12079. this._caps.depthTextureExtension = true;
  12080. }
  12081. else {
  12082. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12083. if (depthTextureExtension != null) {
  12084. this._caps.depthTextureExtension = true;
  12085. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12086. }
  12087. }
  12088. // Vertex array object
  12089. if (this._webGLVersion > 1) {
  12090. this._caps.vertexArrayObject = true;
  12091. }
  12092. else {
  12093. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12094. if (vertexArrayObjectExtension != null) {
  12095. this._caps.vertexArrayObject = true;
  12096. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12097. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12098. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12099. }
  12100. else {
  12101. this._caps.vertexArrayObject = false;
  12102. }
  12103. }
  12104. // Instances count
  12105. if (this._webGLVersion > 1) {
  12106. this._caps.instancedArrays = true;
  12107. }
  12108. else {
  12109. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12110. if (instanceExtension != null) {
  12111. this._caps.instancedArrays = true;
  12112. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12113. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12114. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12115. }
  12116. else {
  12117. this._caps.instancedArrays = false;
  12118. }
  12119. }
  12120. // Intelligently add supported compressed formats in order to check for.
  12121. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12122. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12123. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12124. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12125. if (this._caps.astc)
  12126. this.texturesSupported.push('-astc.ktx');
  12127. if (this._caps.s3tc)
  12128. this.texturesSupported.push('-dxt.ktx');
  12129. if (this._caps.pvrtc)
  12130. this.texturesSupported.push('-pvrtc.ktx');
  12131. if (this._caps.etc2)
  12132. this.texturesSupported.push('-etc2.ktx');
  12133. if (this._caps.etc1)
  12134. this.texturesSupported.push('-etc1.ktx');
  12135. if (this._gl.getShaderPrecisionFormat) {
  12136. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12137. if (highp) {
  12138. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12139. }
  12140. }
  12141. // Depth buffer
  12142. this.setDepthBuffer(true);
  12143. this.setDepthFunctionToLessOrEqual();
  12144. this.setDepthWrite(true);
  12145. // Texture maps
  12146. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12147. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12148. this._nextFreeTextureSlots.push(slot);
  12149. }
  12150. };
  12151. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12152. /**
  12153. * Gets version of the current webGL context
  12154. */
  12155. get: function () {
  12156. return this._webGLVersion;
  12157. },
  12158. enumerable: true,
  12159. configurable: true
  12160. });
  12161. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12162. /**
  12163. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12164. */
  12165. get: function () {
  12166. return this._isStencilEnable;
  12167. },
  12168. enumerable: true,
  12169. configurable: true
  12170. });
  12171. Engine.prototype._prepareWorkingCanvas = function () {
  12172. if (this._workingCanvas) {
  12173. return;
  12174. }
  12175. this._workingCanvas = document.createElement("canvas");
  12176. var context = this._workingCanvas.getContext("2d");
  12177. if (context) {
  12178. this._workingContext = context;
  12179. }
  12180. };
  12181. /**
  12182. * Reset the texture cache to empty state
  12183. */
  12184. Engine.prototype.resetTextureCache = function () {
  12185. for (var key in this._boundTexturesCache) {
  12186. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12187. continue;
  12188. }
  12189. var boundTexture = this._boundTexturesCache[key];
  12190. if (boundTexture) {
  12191. this._removeDesignatedSlot(boundTexture);
  12192. }
  12193. this._boundTexturesCache[key] = null;
  12194. }
  12195. if (!this.disableTextureBindingOptimization) {
  12196. this._nextFreeTextureSlots = [];
  12197. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12198. this._nextFreeTextureSlots.push(slot);
  12199. }
  12200. }
  12201. this._currentTextureChannel = -1;
  12202. };
  12203. /**
  12204. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12205. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12206. * @returns true if engine is in deterministic lock step mode
  12207. */
  12208. Engine.prototype.isDeterministicLockStep = function () {
  12209. return this._deterministicLockstep;
  12210. };
  12211. /**
  12212. * Gets the max steps when engine is running in deterministic lock step
  12213. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12214. * @returns the max steps
  12215. */
  12216. Engine.prototype.getLockstepMaxSteps = function () {
  12217. return this._lockstepMaxSteps;
  12218. };
  12219. /**
  12220. * Gets an object containing information about the current webGL context
  12221. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12222. */
  12223. Engine.prototype.getGlInfo = function () {
  12224. return {
  12225. vendor: this._glVendor,
  12226. renderer: this._glRenderer,
  12227. version: this._glVersion
  12228. };
  12229. };
  12230. /**
  12231. * Gets current aspect ratio
  12232. * @param camera defines the camera to use to get the aspect ratio
  12233. * @param useScreen defines if screen size must be used (or the current render target if any)
  12234. * @returns a number defining the aspect ratio
  12235. */
  12236. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12237. if (useScreen === void 0) { useScreen = false; }
  12238. var viewport = camera.viewport;
  12239. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12240. };
  12241. /**
  12242. * Gets current screen aspect ratio
  12243. * @returns a number defining the aspect ratio
  12244. */
  12245. Engine.prototype.getScreenAspectRatio = function () {
  12246. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12247. };
  12248. /**
  12249. * Gets the current render width
  12250. * @param useScreen defines if screen size must be used (or the current render target if any)
  12251. * @returns a number defining the current render width
  12252. */
  12253. Engine.prototype.getRenderWidth = function (useScreen) {
  12254. if (useScreen === void 0) { useScreen = false; }
  12255. if (!useScreen && this._currentRenderTarget) {
  12256. return this._currentRenderTarget.width;
  12257. }
  12258. return this._gl.drawingBufferWidth;
  12259. };
  12260. /**
  12261. * Gets the current render height
  12262. * @param useScreen defines if screen size must be used (or the current render target if any)
  12263. * @returns a number defining the current render height
  12264. */
  12265. Engine.prototype.getRenderHeight = function (useScreen) {
  12266. if (useScreen === void 0) { useScreen = false; }
  12267. if (!useScreen && this._currentRenderTarget) {
  12268. return this._currentRenderTarget.height;
  12269. }
  12270. return this._gl.drawingBufferHeight;
  12271. };
  12272. /**
  12273. * Gets the HTML canvas attached with the current webGL context
  12274. * @returns a HTML canvas
  12275. */
  12276. Engine.prototype.getRenderingCanvas = function () {
  12277. return this._renderingCanvas;
  12278. };
  12279. /**
  12280. * Gets the client rect of the HTML canvas attached with the current webGL context
  12281. * @returns a client rectanglee
  12282. */
  12283. Engine.prototype.getRenderingCanvasClientRect = function () {
  12284. if (!this._renderingCanvas) {
  12285. return null;
  12286. }
  12287. return this._renderingCanvas.getBoundingClientRect();
  12288. };
  12289. /**
  12290. * Defines the hardware scaling level.
  12291. * By default the hardware scaling level is computed from the window device ratio.
  12292. * 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.
  12293. * @param level defines the level to use
  12294. */
  12295. Engine.prototype.setHardwareScalingLevel = function (level) {
  12296. this._hardwareScalingLevel = level;
  12297. this.resize();
  12298. };
  12299. /**
  12300. * Gets the current hardware scaling level.
  12301. * By default the hardware scaling level is computed from the window device ratio.
  12302. * 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.
  12303. * @returns a number indicating the current hardware scaling level
  12304. */
  12305. Engine.prototype.getHardwareScalingLevel = function () {
  12306. return this._hardwareScalingLevel;
  12307. };
  12308. /**
  12309. * Gets the list of loaded textures
  12310. * @returns an array containing all loaded textures
  12311. */
  12312. Engine.prototype.getLoadedTexturesCache = function () {
  12313. return this._internalTexturesCache;
  12314. };
  12315. /**
  12316. * Gets the object containing all engine capabilities
  12317. * @returns the EngineCapabilities object
  12318. */
  12319. Engine.prototype.getCaps = function () {
  12320. return this._caps;
  12321. };
  12322. Object.defineProperty(Engine.prototype, "drawCalls", {
  12323. /** @hidden */
  12324. get: function () {
  12325. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12326. return 0;
  12327. },
  12328. enumerable: true,
  12329. configurable: true
  12330. });
  12331. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12332. /** @hidden */
  12333. get: function () {
  12334. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12335. return null;
  12336. },
  12337. enumerable: true,
  12338. configurable: true
  12339. });
  12340. /**
  12341. * Gets the current depth function
  12342. * @returns a number defining the depth function
  12343. */
  12344. Engine.prototype.getDepthFunction = function () {
  12345. return this._depthCullingState.depthFunc;
  12346. };
  12347. /**
  12348. * Sets the current depth function
  12349. * @param depthFunc defines the function to use
  12350. */
  12351. Engine.prototype.setDepthFunction = function (depthFunc) {
  12352. this._depthCullingState.depthFunc = depthFunc;
  12353. };
  12354. /**
  12355. * Sets the current depth function to GREATER
  12356. */
  12357. Engine.prototype.setDepthFunctionToGreater = function () {
  12358. this._depthCullingState.depthFunc = this._gl.GREATER;
  12359. };
  12360. /**
  12361. * Sets the current depth function to GEQUAL
  12362. */
  12363. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12364. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12365. };
  12366. /**
  12367. * Sets the current depth function to LESS
  12368. */
  12369. Engine.prototype.setDepthFunctionToLess = function () {
  12370. this._depthCullingState.depthFunc = this._gl.LESS;
  12371. };
  12372. /**
  12373. * Sets the current depth function to LEQUAL
  12374. */
  12375. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12376. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12377. };
  12378. /**
  12379. * Gets a boolean indicating if stencil buffer is enabled
  12380. * @returns the current stencil buffer state
  12381. */
  12382. Engine.prototype.getStencilBuffer = function () {
  12383. return this._stencilState.stencilTest;
  12384. };
  12385. /**
  12386. * Enable or disable the stencil buffer
  12387. * @param enable defines if the stencil buffer must be enabled or disabled
  12388. */
  12389. Engine.prototype.setStencilBuffer = function (enable) {
  12390. this._stencilState.stencilTest = enable;
  12391. };
  12392. /**
  12393. * Gets the current stencil mask
  12394. * @returns a number defining the new stencil mask to use
  12395. */
  12396. Engine.prototype.getStencilMask = function () {
  12397. return this._stencilState.stencilMask;
  12398. };
  12399. /**
  12400. * Sets the current stencil mask
  12401. * @param mask defines the new stencil mask to use
  12402. */
  12403. Engine.prototype.setStencilMask = function (mask) {
  12404. this._stencilState.stencilMask = mask;
  12405. };
  12406. /**
  12407. * Gets the current stencil function
  12408. * @returns a number defining the stencil function to use
  12409. */
  12410. Engine.prototype.getStencilFunction = function () {
  12411. return this._stencilState.stencilFunc;
  12412. };
  12413. /**
  12414. * Gets the current stencil reference value
  12415. * @returns a number defining the stencil reference value to use
  12416. */
  12417. Engine.prototype.getStencilFunctionReference = function () {
  12418. return this._stencilState.stencilFuncRef;
  12419. };
  12420. /**
  12421. * Gets the current stencil mask
  12422. * @returns a number defining the stencil mask to use
  12423. */
  12424. Engine.prototype.getStencilFunctionMask = function () {
  12425. return this._stencilState.stencilFuncMask;
  12426. };
  12427. /**
  12428. * Sets the current stencil function
  12429. * @param stencilFunc defines the new stencil function to use
  12430. */
  12431. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12432. this._stencilState.stencilFunc = stencilFunc;
  12433. };
  12434. /**
  12435. * Sets the current stencil reference
  12436. * @param reference defines the new stencil reference to use
  12437. */
  12438. Engine.prototype.setStencilFunctionReference = function (reference) {
  12439. this._stencilState.stencilFuncRef = reference;
  12440. };
  12441. /**
  12442. * Sets the current stencil mask
  12443. * @param mask defines the new stencil mask to use
  12444. */
  12445. Engine.prototype.setStencilFunctionMask = function (mask) {
  12446. this._stencilState.stencilFuncMask = mask;
  12447. };
  12448. /**
  12449. * Gets the current stencil operation when stencil fails
  12450. * @returns a number defining stencil operation to use when stencil fails
  12451. */
  12452. Engine.prototype.getStencilOperationFail = function () {
  12453. return this._stencilState.stencilOpStencilFail;
  12454. };
  12455. /**
  12456. * Gets the current stencil operation when depth fails
  12457. * @returns a number defining stencil operation to use when depth fails
  12458. */
  12459. Engine.prototype.getStencilOperationDepthFail = function () {
  12460. return this._stencilState.stencilOpDepthFail;
  12461. };
  12462. /**
  12463. * Gets the current stencil operation when stencil passes
  12464. * @returns a number defining stencil operation to use when stencil passes
  12465. */
  12466. Engine.prototype.getStencilOperationPass = function () {
  12467. return this._stencilState.stencilOpStencilDepthPass;
  12468. };
  12469. /**
  12470. * Sets the stencil operation to use when stencil fails
  12471. * @param operation defines the stencil operation to use when stencil fails
  12472. */
  12473. Engine.prototype.setStencilOperationFail = function (operation) {
  12474. this._stencilState.stencilOpStencilFail = operation;
  12475. };
  12476. /**
  12477. * Sets the stencil operation to use when depth fails
  12478. * @param operation defines the stencil operation to use when depth fails
  12479. */
  12480. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12481. this._stencilState.stencilOpDepthFail = operation;
  12482. };
  12483. /**
  12484. * Sets the stencil operation to use when stencil passes
  12485. * @param operation defines the stencil operation to use when stencil passes
  12486. */
  12487. Engine.prototype.setStencilOperationPass = function (operation) {
  12488. this._stencilState.stencilOpStencilDepthPass = operation;
  12489. };
  12490. /**
  12491. * Sets a boolean indicating if the dithering state is enabled or disabled
  12492. * @param value defines the dithering state
  12493. */
  12494. Engine.prototype.setDitheringState = function (value) {
  12495. if (value) {
  12496. this._gl.enable(this._gl.DITHER);
  12497. }
  12498. else {
  12499. this._gl.disable(this._gl.DITHER);
  12500. }
  12501. };
  12502. /**
  12503. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12504. * @param value defines the rasterizer state
  12505. */
  12506. Engine.prototype.setRasterizerState = function (value) {
  12507. if (value) {
  12508. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12509. }
  12510. else {
  12511. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12512. }
  12513. };
  12514. /**
  12515. * stop executing a render loop function and remove it from the execution array
  12516. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12517. */
  12518. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12519. if (!renderFunction) {
  12520. this._activeRenderLoops = [];
  12521. return;
  12522. }
  12523. var index = this._activeRenderLoops.indexOf(renderFunction);
  12524. if (index >= 0) {
  12525. this._activeRenderLoops.splice(index, 1);
  12526. }
  12527. };
  12528. /** @hidden */
  12529. Engine.prototype._renderLoop = function () {
  12530. if (!this._contextWasLost) {
  12531. var shouldRender = true;
  12532. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12533. shouldRender = false;
  12534. }
  12535. if (shouldRender) {
  12536. // Start new frame
  12537. this.beginFrame();
  12538. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12539. var renderFunction = this._activeRenderLoops[index];
  12540. renderFunction();
  12541. }
  12542. // Present
  12543. this.endFrame();
  12544. }
  12545. }
  12546. if (this._activeRenderLoops.length > 0) {
  12547. // Register new frame
  12548. var requester = null;
  12549. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12550. requester = this._vrDisplay;
  12551. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12552. }
  12553. else {
  12554. this._renderingQueueLaunched = false;
  12555. }
  12556. };
  12557. /**
  12558. * Register and execute a render loop. The engine can have more than one render function
  12559. * @param renderFunction defines the function to continuously execute
  12560. */
  12561. Engine.prototype.runRenderLoop = function (renderFunction) {
  12562. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12563. return;
  12564. }
  12565. this._activeRenderLoops.push(renderFunction);
  12566. if (!this._renderingQueueLaunched) {
  12567. this._renderingQueueLaunched = true;
  12568. this._bindedRenderFunction = this._renderLoop.bind(this);
  12569. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12570. }
  12571. };
  12572. /**
  12573. * Toggle full screen mode
  12574. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12575. * @param options defines an option object to be sent to the requestFullscreen function
  12576. */
  12577. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12578. if (this.isFullscreen) {
  12579. BABYLON.Tools.ExitFullscreen();
  12580. }
  12581. else {
  12582. this._pointerLockRequested = requestPointerLock;
  12583. if (this._renderingCanvas) {
  12584. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12585. }
  12586. }
  12587. };
  12588. /**
  12589. * Clear the current render buffer or the current render target (if any is set up)
  12590. * @param color defines the color to use
  12591. * @param backBuffer defines if the back buffer must be cleared
  12592. * @param depth defines if the depth buffer must be cleared
  12593. * @param stencil defines if the stencil buffer must be cleared
  12594. */
  12595. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12596. if (stencil === void 0) { stencil = false; }
  12597. this.applyStates();
  12598. var mode = 0;
  12599. if (backBuffer && color) {
  12600. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12601. mode |= this._gl.COLOR_BUFFER_BIT;
  12602. }
  12603. if (depth) {
  12604. this._gl.clearDepth(1.0);
  12605. mode |= this._gl.DEPTH_BUFFER_BIT;
  12606. }
  12607. if (stencil) {
  12608. this._gl.clearStencil(0);
  12609. mode |= this._gl.STENCIL_BUFFER_BIT;
  12610. }
  12611. this._gl.clear(mode);
  12612. };
  12613. /**
  12614. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12615. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12616. * @param y defines the y-coordinate of the corner of the clear rectangle
  12617. * @param width defines the width of the clear rectangle
  12618. * @param height defines the height of the clear rectangle
  12619. * @param clearColor defines the clear color
  12620. */
  12621. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12622. var gl = this._gl;
  12623. // Save state
  12624. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12625. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12626. // Change state
  12627. gl.enable(gl.SCISSOR_TEST);
  12628. gl.scissor(x, y, width, height);
  12629. // Clear
  12630. this.clear(clearColor, true, true, true);
  12631. // Restore state
  12632. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12633. if (curScissor === true) {
  12634. gl.enable(gl.SCISSOR_TEST);
  12635. }
  12636. else {
  12637. gl.disable(gl.SCISSOR_TEST);
  12638. }
  12639. };
  12640. /** @hidden */
  12641. Engine.prototype._viewport = function (x, y, width, height) {
  12642. if (x !== this._viewportCached.x ||
  12643. y !== this._viewportCached.y ||
  12644. width !== this._viewportCached.z ||
  12645. height !== this._viewportCached.w) {
  12646. this._viewportCached.x = x;
  12647. this._viewportCached.y = y;
  12648. this._viewportCached.z = width;
  12649. this._viewportCached.w = height;
  12650. this._gl.viewport(x, y, width, height);
  12651. }
  12652. };
  12653. /**
  12654. * Set the WebGL's viewport
  12655. * @param viewport defines the viewport element to be used
  12656. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12657. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12658. */
  12659. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12660. var width = requiredWidth || this.getRenderWidth();
  12661. var height = requiredHeight || this.getRenderHeight();
  12662. var x = viewport.x || 0;
  12663. var y = viewport.y || 0;
  12664. this._cachedViewport = viewport;
  12665. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12666. };
  12667. /**
  12668. * Directly set the WebGL Viewport
  12669. * @param x defines the x coordinate of the viewport (in screen space)
  12670. * @param y defines the y coordinate of the viewport (in screen space)
  12671. * @param width defines the width of the viewport (in screen space)
  12672. * @param height defines the height of the viewport (in screen space)
  12673. * @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
  12674. */
  12675. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12676. var currentViewport = this._cachedViewport;
  12677. this._cachedViewport = null;
  12678. this._viewport(x, y, width, height);
  12679. return currentViewport;
  12680. };
  12681. /**
  12682. * Begin a new frame
  12683. */
  12684. Engine.prototype.beginFrame = function () {
  12685. this.onBeginFrameObservable.notifyObservers(this);
  12686. this._measureFps();
  12687. };
  12688. /**
  12689. * Enf the current frame
  12690. */
  12691. Engine.prototype.endFrame = function () {
  12692. // Force a flush in case we are using a bad OS.
  12693. if (this._badOS) {
  12694. this.flushFramebuffer();
  12695. }
  12696. // Submit frame to the vr device, if enabled
  12697. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12698. // TODO: We should only submit the frame if we read frameData successfully.
  12699. this._vrDisplay.submitFrame();
  12700. }
  12701. this.onEndFrameObservable.notifyObservers(this);
  12702. };
  12703. /**
  12704. * Resize the view according to the canvas' size
  12705. */
  12706. Engine.prototype.resize = function () {
  12707. // We're not resizing the size of the canvas while in VR mode & presenting
  12708. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12709. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12710. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12711. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12712. }
  12713. };
  12714. /**
  12715. * Force a specific size of the canvas
  12716. * @param width defines the new canvas' width
  12717. * @param height defines the new canvas' height
  12718. */
  12719. Engine.prototype.setSize = function (width, height) {
  12720. if (!this._renderingCanvas) {
  12721. return;
  12722. }
  12723. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12724. return;
  12725. }
  12726. this._renderingCanvas.width = width;
  12727. this._renderingCanvas.height = height;
  12728. for (var index = 0; index < this.scenes.length; index++) {
  12729. var scene = this.scenes[index];
  12730. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12731. var cam = scene.cameras[camIndex];
  12732. cam._currentRenderId = 0;
  12733. }
  12734. }
  12735. if (this.onResizeObservable.hasObservers) {
  12736. this.onResizeObservable.notifyObservers(this);
  12737. }
  12738. };
  12739. // WebVR functions
  12740. /**
  12741. * Gets a boolean indicating if a webVR device was detected
  12742. * @returns true if a webVR device was detected
  12743. */
  12744. Engine.prototype.isVRDevicePresent = function () {
  12745. return !!this._vrDisplay;
  12746. };
  12747. /**
  12748. * Gets the current webVR device
  12749. * @returns the current webVR device (or null)
  12750. */
  12751. Engine.prototype.getVRDevice = function () {
  12752. return this._vrDisplay;
  12753. };
  12754. /**
  12755. * Initializes a webVR display and starts listening to display change events
  12756. * The onVRDisplayChangedObservable will be notified upon these changes
  12757. * @returns The onVRDisplayChangedObservable
  12758. */
  12759. Engine.prototype.initWebVR = function () {
  12760. this.initWebVRAsync();
  12761. return this.onVRDisplayChangedObservable;
  12762. };
  12763. /**
  12764. * Initializes a webVR display and starts listening to display change events
  12765. * The onVRDisplayChangedObservable will be notified upon these changes
  12766. * @returns A promise containing a VRDisplay and if vr is supported
  12767. */
  12768. Engine.prototype.initWebVRAsync = function () {
  12769. var _this = this;
  12770. var notifyObservers = function () {
  12771. var eventArgs = {
  12772. vrDisplay: _this._vrDisplay,
  12773. vrSupported: _this._vrSupported
  12774. };
  12775. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12776. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12777. };
  12778. if (!this._onVrDisplayConnect) {
  12779. this._onVrDisplayConnect = function (event) {
  12780. _this._vrDisplay = event.display;
  12781. notifyObservers();
  12782. };
  12783. this._onVrDisplayDisconnect = function () {
  12784. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12785. _this._vrDisplay = undefined;
  12786. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12787. notifyObservers();
  12788. };
  12789. this._onVrDisplayPresentChange = function () {
  12790. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12791. };
  12792. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12793. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12794. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12795. }
  12796. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12797. this._webVRInitPromise.then(notifyObservers);
  12798. return this._webVRInitPromise;
  12799. };
  12800. /**
  12801. * Call this function to switch to webVR mode
  12802. * Will do nothing if webVR is not supported or if there is no webVR device
  12803. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12804. */
  12805. Engine.prototype.enableVR = function () {
  12806. var _this = this;
  12807. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12808. var onResolved = function () {
  12809. _this.onVRRequestPresentComplete.notifyObservers(true);
  12810. _this._onVRFullScreenTriggered();
  12811. };
  12812. var onRejected = function () {
  12813. _this.onVRRequestPresentComplete.notifyObservers(false);
  12814. };
  12815. this.onVRRequestPresentStart.notifyObservers(this);
  12816. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12817. }
  12818. };
  12819. /**
  12820. * Call this function to leave webVR mode
  12821. * Will do nothing if webVR is not supported or if there is no webVR device
  12822. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12823. */
  12824. Engine.prototype.disableVR = function () {
  12825. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12826. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12827. }
  12828. };
  12829. Engine.prototype._getVRDisplaysAsync = function () {
  12830. var _this = this;
  12831. return new Promise(function (res, rej) {
  12832. if (navigator.getVRDisplays) {
  12833. navigator.getVRDisplays().then(function (devices) {
  12834. _this._vrSupported = true;
  12835. // note that devices may actually be an empty array. This is fine;
  12836. // we expect this._vrDisplay to be undefined in this case.
  12837. _this._vrDisplay = devices[0];
  12838. res({
  12839. vrDisplay: _this._vrDisplay,
  12840. vrSupported: _this._vrSupported
  12841. });
  12842. });
  12843. }
  12844. else {
  12845. _this._vrDisplay = undefined;
  12846. _this._vrSupported = false;
  12847. res({
  12848. vrDisplay: _this._vrDisplay,
  12849. vrSupported: _this._vrSupported
  12850. });
  12851. }
  12852. });
  12853. };
  12854. /**
  12855. * Binds the frame buffer to the specified texture.
  12856. * @param texture The texture to render to or null for the default canvas
  12857. * @param faceIndex The face of the texture to render to in case of cube texture
  12858. * @param requiredWidth The width of the target to render to
  12859. * @param requiredHeight The height of the target to render to
  12860. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12861. * @param depthStencilTexture The depth stencil texture to use to render
  12862. * @param lodLevel defines le lod level to bind to the frame buffer
  12863. */
  12864. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12865. if (lodLevel === void 0) { lodLevel = 0; }
  12866. if (this._currentRenderTarget) {
  12867. this.unBindFramebuffer(this._currentRenderTarget);
  12868. }
  12869. this._currentRenderTarget = texture;
  12870. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12871. var gl = this._gl;
  12872. if (texture.isCube) {
  12873. if (faceIndex === undefined) {
  12874. faceIndex = 0;
  12875. }
  12876. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12877. if (depthStencilTexture) {
  12878. if (depthStencilTexture._generateStencilBuffer) {
  12879. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12880. }
  12881. else {
  12882. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12883. }
  12884. }
  12885. }
  12886. if (this._cachedViewport && !forceFullscreenViewport) {
  12887. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12888. }
  12889. else {
  12890. if (!requiredWidth) {
  12891. requiredWidth = texture.width;
  12892. if (lodLevel) {
  12893. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12894. }
  12895. }
  12896. if (!requiredHeight) {
  12897. requiredHeight = texture.height;
  12898. if (lodLevel) {
  12899. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12900. }
  12901. }
  12902. this._viewport(0, 0, requiredWidth, requiredHeight);
  12903. }
  12904. this.wipeCaches();
  12905. };
  12906. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12907. if (this._currentFramebuffer !== framebuffer) {
  12908. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12909. this._currentFramebuffer = framebuffer;
  12910. }
  12911. };
  12912. /**
  12913. * Unbind the current render target texture from the webGL context
  12914. * @param texture defines the render target texture to unbind
  12915. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12916. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12917. */
  12918. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12919. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12920. this._currentRenderTarget = null;
  12921. // If MSAA, we need to bitblt back to main texture
  12922. var gl = this._gl;
  12923. if (texture._MSAAFramebuffer) {
  12924. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12925. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12926. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12927. }
  12928. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12929. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12930. gl.generateMipmap(gl.TEXTURE_2D);
  12931. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12932. }
  12933. if (onBeforeUnbind) {
  12934. if (texture._MSAAFramebuffer) {
  12935. // Bind the correct framebuffer
  12936. this.bindUnboundFramebuffer(texture._framebuffer);
  12937. }
  12938. onBeforeUnbind();
  12939. }
  12940. this.bindUnboundFramebuffer(null);
  12941. };
  12942. /**
  12943. * Unbind a list of render target textures from the webGL context
  12944. * This is used only when drawBuffer extension or webGL2 are active
  12945. * @param textures defines the render target textures to unbind
  12946. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12947. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12948. */
  12949. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12950. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12951. this._currentRenderTarget = null;
  12952. // If MSAA, we need to bitblt back to main texture
  12953. var gl = this._gl;
  12954. if (textures[0]._MSAAFramebuffer) {
  12955. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12956. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12957. var attachments = textures[0]._attachments;
  12958. if (!attachments) {
  12959. attachments = new Array(textures.length);
  12960. textures[0]._attachments = attachments;
  12961. }
  12962. for (var i = 0; i < textures.length; i++) {
  12963. var texture = textures[i];
  12964. for (var j = 0; j < attachments.length; j++) {
  12965. attachments[j] = gl.NONE;
  12966. }
  12967. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12968. gl.readBuffer(attachments[i]);
  12969. gl.drawBuffers(attachments);
  12970. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12971. }
  12972. for (var i = 0; i < attachments.length; i++) {
  12973. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12974. }
  12975. gl.drawBuffers(attachments);
  12976. }
  12977. for (var i = 0; i < textures.length; i++) {
  12978. var texture = textures[i];
  12979. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12980. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12981. gl.generateMipmap(gl.TEXTURE_2D);
  12982. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12983. }
  12984. }
  12985. if (onBeforeUnbind) {
  12986. if (textures[0]._MSAAFramebuffer) {
  12987. // Bind the correct framebuffer
  12988. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12989. }
  12990. onBeforeUnbind();
  12991. }
  12992. this.bindUnboundFramebuffer(null);
  12993. };
  12994. /**
  12995. * Force the mipmap generation for the given render target texture
  12996. * @param texture defines the render target texture to use
  12997. */
  12998. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12999. if (texture.generateMipMaps) {
  13000. var gl = this._gl;
  13001. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13002. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13003. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13004. }
  13005. };
  13006. /**
  13007. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13008. */
  13009. Engine.prototype.flushFramebuffer = function () {
  13010. this._gl.flush();
  13011. };
  13012. /**
  13013. * Unbind the current render target and bind the default framebuffer
  13014. */
  13015. Engine.prototype.restoreDefaultFramebuffer = function () {
  13016. if (this._currentRenderTarget) {
  13017. this.unBindFramebuffer(this._currentRenderTarget);
  13018. }
  13019. else {
  13020. this.bindUnboundFramebuffer(null);
  13021. }
  13022. if (this._cachedViewport) {
  13023. this.setViewport(this._cachedViewport);
  13024. }
  13025. this.wipeCaches();
  13026. };
  13027. // UBOs
  13028. /**
  13029. * Create an uniform buffer
  13030. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13031. * @param elements defines the content of the uniform buffer
  13032. * @returns the webGL uniform buffer
  13033. */
  13034. Engine.prototype.createUniformBuffer = function (elements) {
  13035. var ubo = this._gl.createBuffer();
  13036. if (!ubo) {
  13037. throw new Error("Unable to create uniform buffer");
  13038. }
  13039. this.bindUniformBuffer(ubo);
  13040. if (elements instanceof Float32Array) {
  13041. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13042. }
  13043. else {
  13044. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13045. }
  13046. this.bindUniformBuffer(null);
  13047. ubo.references = 1;
  13048. return ubo;
  13049. };
  13050. /**
  13051. * Create a dynamic uniform buffer
  13052. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13053. * @param elements defines the content of the uniform buffer
  13054. * @returns the webGL uniform buffer
  13055. */
  13056. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13057. var ubo = this._gl.createBuffer();
  13058. if (!ubo) {
  13059. throw new Error("Unable to create dynamic uniform buffer");
  13060. }
  13061. this.bindUniformBuffer(ubo);
  13062. if (elements instanceof Float32Array) {
  13063. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13064. }
  13065. else {
  13066. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13067. }
  13068. this.bindUniformBuffer(null);
  13069. ubo.references = 1;
  13070. return ubo;
  13071. };
  13072. /**
  13073. * Update an existing uniform buffer
  13074. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13075. * @param uniformBuffer defines the target uniform buffer
  13076. * @param elements defines the content to update
  13077. * @param offset defines the offset in the uniform buffer where update should start
  13078. * @param count defines the size of the data to update
  13079. */
  13080. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13081. this.bindUniformBuffer(uniformBuffer);
  13082. if (offset === undefined) {
  13083. offset = 0;
  13084. }
  13085. if (count === undefined) {
  13086. if (elements instanceof Float32Array) {
  13087. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13088. }
  13089. else {
  13090. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13091. }
  13092. }
  13093. else {
  13094. if (elements instanceof Float32Array) {
  13095. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13096. }
  13097. else {
  13098. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13099. }
  13100. }
  13101. this.bindUniformBuffer(null);
  13102. };
  13103. // VBOs
  13104. Engine.prototype._resetVertexBufferBinding = function () {
  13105. this.bindArrayBuffer(null);
  13106. this._cachedVertexBuffers = null;
  13107. };
  13108. /**
  13109. * Creates a vertex buffer
  13110. * @param data the data for the vertex buffer
  13111. * @returns the new WebGL static buffer
  13112. */
  13113. Engine.prototype.createVertexBuffer = function (data) {
  13114. var vbo = this._gl.createBuffer();
  13115. if (!vbo) {
  13116. throw new Error("Unable to create vertex buffer");
  13117. }
  13118. this.bindArrayBuffer(vbo);
  13119. if (data instanceof Array) {
  13120. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13121. }
  13122. else {
  13123. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13124. }
  13125. this._resetVertexBufferBinding();
  13126. vbo.references = 1;
  13127. return vbo;
  13128. };
  13129. /**
  13130. * Creates a dynamic vertex buffer
  13131. * @param data the data for the dynamic vertex buffer
  13132. * @returns the new WebGL dynamic buffer
  13133. */
  13134. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13135. var vbo = this._gl.createBuffer();
  13136. if (!vbo) {
  13137. throw new Error("Unable to create dynamic vertex buffer");
  13138. }
  13139. this.bindArrayBuffer(vbo);
  13140. if (data instanceof Array) {
  13141. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13142. }
  13143. else {
  13144. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13145. }
  13146. this._resetVertexBufferBinding();
  13147. vbo.references = 1;
  13148. return vbo;
  13149. };
  13150. /**
  13151. * Update a dynamic index buffer
  13152. * @param indexBuffer defines the target index buffer
  13153. * @param indices defines the data to update
  13154. * @param offset defines the offset in the target index buffer where update should start
  13155. */
  13156. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13157. if (offset === void 0) { offset = 0; }
  13158. // Force cache update
  13159. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13160. this.bindIndexBuffer(indexBuffer);
  13161. var arrayBuffer;
  13162. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13163. arrayBuffer = indices;
  13164. }
  13165. else {
  13166. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13167. }
  13168. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13169. this._resetIndexBufferBinding();
  13170. };
  13171. /**
  13172. * Updates a dynamic vertex buffer.
  13173. * @param vertexBuffer the vertex buffer to update
  13174. * @param data the data used to update the vertex buffer
  13175. * @param byteOffset the byte offset of the data
  13176. * @param byteLength the byte length of the data
  13177. */
  13178. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13179. this.bindArrayBuffer(vertexBuffer);
  13180. if (byteOffset === undefined) {
  13181. byteOffset = 0;
  13182. }
  13183. if (byteLength === undefined) {
  13184. if (data instanceof Array) {
  13185. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13186. }
  13187. else {
  13188. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13189. }
  13190. }
  13191. else {
  13192. if (data instanceof Array) {
  13193. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13194. }
  13195. else {
  13196. if (data instanceof ArrayBuffer) {
  13197. data = new Uint8Array(data, byteOffset, byteLength);
  13198. }
  13199. else {
  13200. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13201. }
  13202. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13203. }
  13204. }
  13205. this._resetVertexBufferBinding();
  13206. };
  13207. Engine.prototype._resetIndexBufferBinding = function () {
  13208. this.bindIndexBuffer(null);
  13209. this._cachedIndexBuffer = null;
  13210. };
  13211. /**
  13212. * Creates a new index buffer
  13213. * @param indices defines the content of the index buffer
  13214. * @param updatable defines if the index buffer must be updatable
  13215. * @returns a new webGL buffer
  13216. */
  13217. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13218. var vbo = this._gl.createBuffer();
  13219. if (!vbo) {
  13220. throw new Error("Unable to create index buffer");
  13221. }
  13222. this.bindIndexBuffer(vbo);
  13223. // Check for 32 bits indices
  13224. var arrayBuffer;
  13225. var need32Bits = false;
  13226. if (indices instanceof Uint16Array) {
  13227. arrayBuffer = indices;
  13228. }
  13229. else {
  13230. //check 32 bit support
  13231. if (this._caps.uintIndices) {
  13232. if (indices instanceof Uint32Array) {
  13233. arrayBuffer = indices;
  13234. need32Bits = true;
  13235. }
  13236. else {
  13237. //number[] or Int32Array, check if 32 bit is necessary
  13238. for (var index = 0; index < indices.length; index++) {
  13239. if (indices[index] > 65535) {
  13240. need32Bits = true;
  13241. break;
  13242. }
  13243. }
  13244. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13245. }
  13246. }
  13247. else {
  13248. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13249. arrayBuffer = new Uint16Array(indices);
  13250. }
  13251. }
  13252. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13253. this._resetIndexBufferBinding();
  13254. vbo.references = 1;
  13255. vbo.is32Bits = need32Bits;
  13256. return vbo;
  13257. };
  13258. /**
  13259. * Bind a webGL buffer to the webGL context
  13260. * @param buffer defines the buffer to bind
  13261. */
  13262. Engine.prototype.bindArrayBuffer = function (buffer) {
  13263. if (!this._vaoRecordInProgress) {
  13264. this._unbindVertexArrayObject();
  13265. }
  13266. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13267. };
  13268. /**
  13269. * Bind an uniform buffer to the current webGL context
  13270. * @param buffer defines the buffer to bind
  13271. */
  13272. Engine.prototype.bindUniformBuffer = function (buffer) {
  13273. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13274. };
  13275. /**
  13276. * Bind a buffer to the current webGL context at a given location
  13277. * @param buffer defines the buffer to bind
  13278. * @param location defines the index where to bind the buffer
  13279. */
  13280. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13281. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13282. };
  13283. /**
  13284. * Bind a specific block at a given index in a specific shader program
  13285. * @param shaderProgram defines the shader program
  13286. * @param blockName defines the block name
  13287. * @param index defines the index where to bind the block
  13288. */
  13289. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13290. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13291. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13292. };
  13293. ;
  13294. Engine.prototype.bindIndexBuffer = function (buffer) {
  13295. if (!this._vaoRecordInProgress) {
  13296. this._unbindVertexArrayObject();
  13297. }
  13298. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13299. };
  13300. Engine.prototype.bindBuffer = function (buffer, target) {
  13301. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13302. this._gl.bindBuffer(target, buffer);
  13303. this._currentBoundBuffer[target] = buffer;
  13304. }
  13305. };
  13306. /**
  13307. * update the bound buffer with the given data
  13308. * @param data defines the data to update
  13309. */
  13310. Engine.prototype.updateArrayBuffer = function (data) {
  13311. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13312. };
  13313. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13314. var pointer = this._currentBufferPointers[indx];
  13315. var changed = false;
  13316. if (!pointer.active) {
  13317. changed = true;
  13318. pointer.active = true;
  13319. pointer.index = indx;
  13320. pointer.size = size;
  13321. pointer.type = type;
  13322. pointer.normalized = normalized;
  13323. pointer.stride = stride;
  13324. pointer.offset = offset;
  13325. pointer.buffer = buffer;
  13326. }
  13327. else {
  13328. if (pointer.buffer !== buffer) {
  13329. pointer.buffer = buffer;
  13330. changed = true;
  13331. }
  13332. if (pointer.size !== size) {
  13333. pointer.size = size;
  13334. changed = true;
  13335. }
  13336. if (pointer.type !== type) {
  13337. pointer.type = type;
  13338. changed = true;
  13339. }
  13340. if (pointer.normalized !== normalized) {
  13341. pointer.normalized = normalized;
  13342. changed = true;
  13343. }
  13344. if (pointer.stride !== stride) {
  13345. pointer.stride = stride;
  13346. changed = true;
  13347. }
  13348. if (pointer.offset !== offset) {
  13349. pointer.offset = offset;
  13350. changed = true;
  13351. }
  13352. }
  13353. if (changed || this._vaoRecordInProgress) {
  13354. this.bindArrayBuffer(buffer);
  13355. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13356. }
  13357. };
  13358. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13359. if (indexBuffer == null) {
  13360. return;
  13361. }
  13362. if (this._cachedIndexBuffer !== indexBuffer) {
  13363. this._cachedIndexBuffer = indexBuffer;
  13364. this.bindIndexBuffer(indexBuffer);
  13365. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13366. }
  13367. };
  13368. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13369. var attributes = effect.getAttributesNames();
  13370. if (!this._vaoRecordInProgress) {
  13371. this._unbindVertexArrayObject();
  13372. }
  13373. this.unbindAllAttributes();
  13374. for (var index = 0; index < attributes.length; index++) {
  13375. var order = effect.getAttributeLocation(index);
  13376. if (order >= 0) {
  13377. var vertexBuffer = vertexBuffers[attributes[index]];
  13378. if (!vertexBuffer) {
  13379. continue;
  13380. }
  13381. this._gl.enableVertexAttribArray(order);
  13382. if (!this._vaoRecordInProgress) {
  13383. this._vertexAttribArraysEnabled[order] = true;
  13384. }
  13385. var buffer = vertexBuffer.getBuffer();
  13386. if (buffer) {
  13387. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13388. if (vertexBuffer.getIsInstanced()) {
  13389. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13390. if (!this._vaoRecordInProgress) {
  13391. this._currentInstanceLocations.push(order);
  13392. this._currentInstanceBuffers.push(buffer);
  13393. }
  13394. }
  13395. }
  13396. }
  13397. }
  13398. };
  13399. /**
  13400. * Records a vertex array object
  13401. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13402. * @param vertexBuffers defines the list of vertex buffers to store
  13403. * @param indexBuffer defines the index buffer to store
  13404. * @param effect defines the effect to store
  13405. * @returns the new vertex array object
  13406. */
  13407. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13408. var vao = this._gl.createVertexArray();
  13409. this._vaoRecordInProgress = true;
  13410. this._gl.bindVertexArray(vao);
  13411. this._mustWipeVertexAttributes = true;
  13412. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13413. this.bindIndexBuffer(indexBuffer);
  13414. this._vaoRecordInProgress = false;
  13415. this._gl.bindVertexArray(null);
  13416. return vao;
  13417. };
  13418. /**
  13419. * Bind a specific vertex array object
  13420. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13421. * @param vertexArrayObject defines the vertex array object to bind
  13422. * @param indexBuffer defines the index buffer to bind
  13423. */
  13424. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13425. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13426. this._cachedVertexArrayObject = vertexArrayObject;
  13427. this._gl.bindVertexArray(vertexArrayObject);
  13428. this._cachedVertexBuffers = null;
  13429. this._cachedIndexBuffer = null;
  13430. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13431. this._mustWipeVertexAttributes = true;
  13432. }
  13433. };
  13434. /**
  13435. * Bind webGl buffers directly to the webGL context
  13436. * @param vertexBuffer defines the vertex buffer to bind
  13437. * @param indexBuffer defines the index buffer to bind
  13438. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13439. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13440. * @param effect defines the effect associated with the vertex buffer
  13441. */
  13442. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13443. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13444. this._cachedVertexBuffers = vertexBuffer;
  13445. this._cachedEffectForVertexBuffers = effect;
  13446. var attributesCount = effect.getAttributesCount();
  13447. this._unbindVertexArrayObject();
  13448. this.unbindAllAttributes();
  13449. var offset = 0;
  13450. for (var index = 0; index < attributesCount; index++) {
  13451. if (index < vertexDeclaration.length) {
  13452. var order = effect.getAttributeLocation(index);
  13453. if (order >= 0) {
  13454. this._gl.enableVertexAttribArray(order);
  13455. this._vertexAttribArraysEnabled[order] = true;
  13456. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13457. }
  13458. offset += vertexDeclaration[index] * 4;
  13459. }
  13460. }
  13461. }
  13462. this._bindIndexBufferWithCache(indexBuffer);
  13463. };
  13464. Engine.prototype._unbindVertexArrayObject = function () {
  13465. if (!this._cachedVertexArrayObject) {
  13466. return;
  13467. }
  13468. this._cachedVertexArrayObject = null;
  13469. this._gl.bindVertexArray(null);
  13470. };
  13471. /**
  13472. * Bind a list of vertex buffers to the webGL context
  13473. * @param vertexBuffers defines the list of vertex buffers to bind
  13474. * @param indexBuffer defines the index buffer to bind
  13475. * @param effect defines the effect associated with the vertex buffers
  13476. */
  13477. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13478. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13479. this._cachedVertexBuffers = vertexBuffers;
  13480. this._cachedEffectForVertexBuffers = effect;
  13481. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13482. }
  13483. this._bindIndexBufferWithCache(indexBuffer);
  13484. };
  13485. /**
  13486. * Unbind all instance attributes
  13487. */
  13488. Engine.prototype.unbindInstanceAttributes = function () {
  13489. var boundBuffer;
  13490. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13491. var instancesBuffer = this._currentInstanceBuffers[i];
  13492. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13493. boundBuffer = instancesBuffer;
  13494. this.bindArrayBuffer(instancesBuffer);
  13495. }
  13496. var offsetLocation = this._currentInstanceLocations[i];
  13497. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13498. }
  13499. this._currentInstanceBuffers.length = 0;
  13500. this._currentInstanceLocations.length = 0;
  13501. };
  13502. /**
  13503. * Release and free the memory of a vertex array object
  13504. * @param vao defines the vertex array object to delete
  13505. */
  13506. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13507. this._gl.deleteVertexArray(vao);
  13508. };
  13509. /** @hidden */
  13510. Engine.prototype._releaseBuffer = function (buffer) {
  13511. buffer.references--;
  13512. if (buffer.references === 0) {
  13513. this._gl.deleteBuffer(buffer);
  13514. return true;
  13515. }
  13516. return false;
  13517. };
  13518. /**
  13519. * Creates a webGL buffer to use with instanciation
  13520. * @param capacity defines the size of the buffer
  13521. * @returns the webGL buffer
  13522. */
  13523. Engine.prototype.createInstancesBuffer = function (capacity) {
  13524. var buffer = this._gl.createBuffer();
  13525. if (!buffer) {
  13526. throw new Error("Unable to create instance buffer");
  13527. }
  13528. buffer.capacity = capacity;
  13529. this.bindArrayBuffer(buffer);
  13530. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13531. return buffer;
  13532. };
  13533. /**
  13534. * Delete a webGL buffer used with instanciation
  13535. * @param buffer defines the webGL buffer to delete
  13536. */
  13537. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13538. this._gl.deleteBuffer(buffer);
  13539. };
  13540. /**
  13541. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13542. * @param instancesBuffer defines the webGL buffer to update and bind
  13543. * @param data defines the data to store in the buffer
  13544. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13545. */
  13546. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13547. this.bindArrayBuffer(instancesBuffer);
  13548. if (data) {
  13549. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13550. }
  13551. if (offsetLocations[0].index !== undefined) {
  13552. var stride = 0;
  13553. for (var i = 0; i < offsetLocations.length; i++) {
  13554. var ai = offsetLocations[i];
  13555. stride += ai.attributeSize * 4;
  13556. }
  13557. for (var i = 0; i < offsetLocations.length; i++) {
  13558. var ai = offsetLocations[i];
  13559. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13560. this._gl.enableVertexAttribArray(ai.index);
  13561. this._vertexAttribArraysEnabled[ai.index] = true;
  13562. }
  13563. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13564. this._gl.vertexAttribDivisor(ai.index, 1);
  13565. this._currentInstanceLocations.push(ai.index);
  13566. this._currentInstanceBuffers.push(instancesBuffer);
  13567. }
  13568. }
  13569. else {
  13570. for (var index = 0; index < 4; index++) {
  13571. var offsetLocation = offsetLocations[index];
  13572. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13573. this._gl.enableVertexAttribArray(offsetLocation);
  13574. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13575. }
  13576. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13577. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13578. this._currentInstanceLocations.push(offsetLocation);
  13579. this._currentInstanceBuffers.push(instancesBuffer);
  13580. }
  13581. }
  13582. };
  13583. /**
  13584. * Apply all cached states (depth, culling, stencil and alpha)
  13585. */
  13586. Engine.prototype.applyStates = function () {
  13587. this._depthCullingState.apply(this._gl);
  13588. this._stencilState.apply(this._gl);
  13589. this._alphaState.apply(this._gl);
  13590. };
  13591. /**
  13592. * Send a draw order
  13593. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13594. * @param indexStart defines the starting index
  13595. * @param indexCount defines the number of index to draw
  13596. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13597. */
  13598. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13599. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13600. };
  13601. /**
  13602. * Draw a list of points
  13603. * @param verticesStart defines the index of first vertex to draw
  13604. * @param verticesCount defines the count of vertices to draw
  13605. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13606. */
  13607. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13608. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13609. };
  13610. /**
  13611. * Draw a list of unindexed primitives
  13612. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13613. * @param verticesStart defines the index of first vertex to draw
  13614. * @param verticesCount defines the count of vertices to draw
  13615. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13616. */
  13617. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13618. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13619. };
  13620. /**
  13621. * Draw a list of indexed primitives
  13622. * @param fillMode defines the primitive to use
  13623. * @param indexStart defines the starting index
  13624. * @param indexCount defines the number of index to draw
  13625. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13626. */
  13627. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13628. // Apply states
  13629. this.applyStates();
  13630. this._drawCalls.addCount(1, false);
  13631. // Render
  13632. var drawMode = this._drawMode(fillMode);
  13633. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13634. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13635. if (instancesCount) {
  13636. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13637. }
  13638. else {
  13639. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13640. }
  13641. };
  13642. /**
  13643. * Draw a list of unindexed primitives
  13644. * @param fillMode defines the primitive to use
  13645. * @param verticesStart defines the index of first vertex to draw
  13646. * @param verticesCount defines the count of vertices to draw
  13647. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13648. */
  13649. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13650. // Apply states
  13651. this.applyStates();
  13652. this._drawCalls.addCount(1, false);
  13653. var drawMode = this._drawMode(fillMode);
  13654. if (instancesCount) {
  13655. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13656. }
  13657. else {
  13658. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13659. }
  13660. };
  13661. Engine.prototype._drawMode = function (fillMode) {
  13662. switch (fillMode) {
  13663. // Triangle views
  13664. case BABYLON.Material.TriangleFillMode:
  13665. return this._gl.TRIANGLES;
  13666. case BABYLON.Material.PointFillMode:
  13667. return this._gl.POINTS;
  13668. case BABYLON.Material.WireFrameFillMode:
  13669. return this._gl.LINES;
  13670. // Draw modes
  13671. case BABYLON.Material.PointListDrawMode:
  13672. return this._gl.POINTS;
  13673. case BABYLON.Material.LineListDrawMode:
  13674. return this._gl.LINES;
  13675. case BABYLON.Material.LineLoopDrawMode:
  13676. return this._gl.LINE_LOOP;
  13677. case BABYLON.Material.LineStripDrawMode:
  13678. return this._gl.LINE_STRIP;
  13679. case BABYLON.Material.TriangleStripDrawMode:
  13680. return this._gl.TRIANGLE_STRIP;
  13681. case BABYLON.Material.TriangleFanDrawMode:
  13682. return this._gl.TRIANGLE_FAN;
  13683. default:
  13684. return this._gl.TRIANGLES;
  13685. }
  13686. };
  13687. // Shaders
  13688. /** @hidden */
  13689. Engine.prototype._releaseEffect = function (effect) {
  13690. if (this._compiledEffects[effect._key]) {
  13691. delete this._compiledEffects[effect._key];
  13692. this._deleteProgram(effect.getProgram());
  13693. }
  13694. };
  13695. /** @hidden */
  13696. Engine.prototype._deleteProgram = function (program) {
  13697. if (program) {
  13698. program.__SPECTOR_rebuildProgram = null;
  13699. if (program.transformFeedback) {
  13700. this.deleteTransformFeedback(program.transformFeedback);
  13701. program.transformFeedback = null;
  13702. }
  13703. this._gl.deleteProgram(program);
  13704. }
  13705. };
  13706. /**
  13707. * Create a new effect (used to store vertex/fragment shaders)
  13708. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13709. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13710. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13711. * @param samplers defines an array of string used to represent textures
  13712. * @param defines defines the string containing the defines to use to compile the shaders
  13713. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13714. * @param onCompiled defines a function to call when the effect creation is successful
  13715. * @param onError defines a function to call when the effect creation has failed
  13716. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13717. * @returns the new Effect
  13718. */
  13719. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13720. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13721. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13722. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13723. if (this._compiledEffects[name]) {
  13724. var compiledEffect = this._compiledEffects[name];
  13725. if (onCompiled && compiledEffect.isReady()) {
  13726. onCompiled(compiledEffect);
  13727. }
  13728. return compiledEffect;
  13729. }
  13730. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13731. effect._key = name;
  13732. this._compiledEffects[name] = effect;
  13733. return effect;
  13734. };
  13735. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13736. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13737. };
  13738. ;
  13739. Engine.prototype._compileRawShader = function (source, type) {
  13740. var gl = this._gl;
  13741. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13742. gl.shaderSource(shader, source);
  13743. gl.compileShader(shader);
  13744. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13745. var log = gl.getShaderInfoLog(shader);
  13746. if (log) {
  13747. throw new Error(log);
  13748. }
  13749. }
  13750. if (!shader) {
  13751. throw new Error("Something went wrong while compile the shader.");
  13752. }
  13753. return shader;
  13754. };
  13755. ;
  13756. /**
  13757. * Directly creates a webGL program
  13758. * @param vertexCode defines the vertex shader code to use
  13759. * @param fragmentCode defines the fragment shader code to use
  13760. * @param context defines the webGL context to use (if not set, the current one will be used)
  13761. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13762. * @returns the new webGL program
  13763. */
  13764. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13765. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13766. context = context || this._gl;
  13767. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13768. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13769. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13770. };
  13771. /**
  13772. * Creates a webGL program
  13773. * @param vertexCode defines the vertex shader code to use
  13774. * @param fragmentCode defines the fragment shader code to use
  13775. * @param defines defines the string containing the defines to use to compile the shaders
  13776. * @param context defines the webGL context to use (if not set, the current one will be used)
  13777. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13778. * @returns the new webGL program
  13779. */
  13780. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13781. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13782. context = context || this._gl;
  13783. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13784. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13785. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13786. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13787. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13788. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13789. return program;
  13790. };
  13791. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13792. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13793. var shaderProgram = context.createProgram();
  13794. if (!shaderProgram) {
  13795. throw new Error("Unable to create program");
  13796. }
  13797. context.attachShader(shaderProgram, vertexShader);
  13798. context.attachShader(shaderProgram, fragmentShader);
  13799. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13800. var transformFeedback = this.createTransformFeedback();
  13801. this.bindTransformFeedback(transformFeedback);
  13802. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13803. shaderProgram.transformFeedback = transformFeedback;
  13804. }
  13805. context.linkProgram(shaderProgram);
  13806. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13807. this.bindTransformFeedback(null);
  13808. }
  13809. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13810. if (!linked) {
  13811. var error = context.getProgramInfoLog(shaderProgram);
  13812. if (error) {
  13813. throw new Error(error);
  13814. }
  13815. }
  13816. if (this.validateShaderPrograms) {
  13817. context.validateProgram(shaderProgram);
  13818. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13819. if (!validated) {
  13820. var error = context.getProgramInfoLog(shaderProgram);
  13821. if (error) {
  13822. throw new Error(error);
  13823. }
  13824. }
  13825. }
  13826. context.deleteShader(vertexShader);
  13827. context.deleteShader(fragmentShader);
  13828. return shaderProgram;
  13829. };
  13830. /**
  13831. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13832. * @param shaderProgram defines the webGL program to use
  13833. * @param uniformsNames defines the list of uniform names
  13834. * @returns an array of webGL uniform locations
  13835. */
  13836. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13837. var results = new Array();
  13838. for (var index = 0; index < uniformsNames.length; index++) {
  13839. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13840. }
  13841. return results;
  13842. };
  13843. /**
  13844. * Gets the lsit of active attributes for a given webGL program
  13845. * @param shaderProgram defines the webGL program to use
  13846. * @param attributesNames defines the list of attribute names to get
  13847. * @returns an array of indices indicating the offset of each attribute
  13848. */
  13849. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13850. var results = [];
  13851. for (var index = 0; index < attributesNames.length; index++) {
  13852. try {
  13853. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13854. }
  13855. catch (e) {
  13856. results.push(-1);
  13857. }
  13858. }
  13859. return results;
  13860. };
  13861. /**
  13862. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13863. * @param effect defines the effect to activate
  13864. */
  13865. Engine.prototype.enableEffect = function (effect) {
  13866. if (!effect || effect === this._currentEffect) {
  13867. return;
  13868. }
  13869. // Use program
  13870. this.bindSamplers(effect);
  13871. this._currentEffect = effect;
  13872. if (effect.onBind) {
  13873. effect.onBind(effect);
  13874. }
  13875. if (effect._onBindObservable) {
  13876. effect._onBindObservable.notifyObservers(effect);
  13877. }
  13878. };
  13879. /**
  13880. * Set the value of an uniform to an array of int32
  13881. * @param uniform defines the webGL uniform location where to store the value
  13882. * @param array defines the array of int32 to store
  13883. */
  13884. Engine.prototype.setIntArray = function (uniform, array) {
  13885. if (!uniform)
  13886. return;
  13887. this._gl.uniform1iv(uniform, array);
  13888. };
  13889. /**
  13890. * Set the value of an uniform to an array of int32 (stored as vec2)
  13891. * @param uniform defines the webGL uniform location where to store the value
  13892. * @param array defines the array of int32 to store
  13893. */
  13894. Engine.prototype.setIntArray2 = function (uniform, array) {
  13895. if (!uniform || array.length % 2 !== 0)
  13896. return;
  13897. this._gl.uniform2iv(uniform, array);
  13898. };
  13899. /**
  13900. * Set the value of an uniform to an array of int32 (stored as vec3)
  13901. * @param uniform defines the webGL uniform location where to store the value
  13902. * @param array defines the array of int32 to store
  13903. */
  13904. Engine.prototype.setIntArray3 = function (uniform, array) {
  13905. if (!uniform || array.length % 3 !== 0)
  13906. return;
  13907. this._gl.uniform3iv(uniform, array);
  13908. };
  13909. /**
  13910. * Set the value of an uniform to an array of int32 (stored as vec4)
  13911. * @param uniform defines the webGL uniform location where to store the value
  13912. * @param array defines the array of int32 to store
  13913. */
  13914. Engine.prototype.setIntArray4 = function (uniform, array) {
  13915. if (!uniform || array.length % 4 !== 0)
  13916. return;
  13917. this._gl.uniform4iv(uniform, array);
  13918. };
  13919. /**
  13920. * Set the value of an uniform to an array of float32
  13921. * @param uniform defines the webGL uniform location where to store the value
  13922. * @param array defines the array of float32 to store
  13923. */
  13924. Engine.prototype.setFloatArray = function (uniform, array) {
  13925. if (!uniform)
  13926. return;
  13927. this._gl.uniform1fv(uniform, array);
  13928. };
  13929. /**
  13930. * Set the value of an uniform to an array of float32 (stored as vec2)
  13931. * @param uniform defines the webGL uniform location where to store the value
  13932. * @param array defines the array of float32 to store
  13933. */
  13934. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13935. if (!uniform || array.length % 2 !== 0)
  13936. return;
  13937. this._gl.uniform2fv(uniform, array);
  13938. };
  13939. /**
  13940. * Set the value of an uniform to an array of float32 (stored as vec3)
  13941. * @param uniform defines the webGL uniform location where to store the value
  13942. * @param array defines the array of float32 to store
  13943. */
  13944. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13945. if (!uniform || array.length % 3 !== 0)
  13946. return;
  13947. this._gl.uniform3fv(uniform, array);
  13948. };
  13949. /**
  13950. * Set the value of an uniform to an array of float32 (stored as vec4)
  13951. * @param uniform defines the webGL uniform location where to store the value
  13952. * @param array defines the array of float32 to store
  13953. */
  13954. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13955. if (!uniform || array.length % 4 !== 0)
  13956. return;
  13957. this._gl.uniform4fv(uniform, array);
  13958. };
  13959. /**
  13960. * Set the value of an uniform to an array of number
  13961. * @param uniform defines the webGL uniform location where to store the value
  13962. * @param array defines the array of number to store
  13963. */
  13964. Engine.prototype.setArray = function (uniform, array) {
  13965. if (!uniform)
  13966. return;
  13967. this._gl.uniform1fv(uniform, array);
  13968. };
  13969. /**
  13970. * Set the value of an uniform to an array of number (stored as vec2)
  13971. * @param uniform defines the webGL uniform location where to store the value
  13972. * @param array defines the array of number to store
  13973. */
  13974. Engine.prototype.setArray2 = function (uniform, array) {
  13975. if (!uniform || array.length % 2 !== 0)
  13976. return;
  13977. this._gl.uniform2fv(uniform, array);
  13978. };
  13979. /**
  13980. * Set the value of an uniform to an array of number (stored as vec3)
  13981. * @param uniform defines the webGL uniform location where to store the value
  13982. * @param array defines the array of number to store
  13983. */
  13984. Engine.prototype.setArray3 = function (uniform, array) {
  13985. if (!uniform || array.length % 3 !== 0)
  13986. return;
  13987. this._gl.uniform3fv(uniform, array);
  13988. };
  13989. /**
  13990. * Set the value of an uniform to an array of number (stored as vec4)
  13991. * @param uniform defines the webGL uniform location where to store the value
  13992. * @param array defines the array of number to store
  13993. */
  13994. Engine.prototype.setArray4 = function (uniform, array) {
  13995. if (!uniform || array.length % 4 !== 0)
  13996. return;
  13997. this._gl.uniform4fv(uniform, array);
  13998. };
  13999. /**
  14000. * Set the value of an uniform to an array of float32 (stored as matrices)
  14001. * @param uniform defines the webGL uniform location where to store the value
  14002. * @param matrices defines the array of float32 to store
  14003. */
  14004. Engine.prototype.setMatrices = function (uniform, matrices) {
  14005. if (!uniform)
  14006. return;
  14007. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14008. };
  14009. /**
  14010. * Set the value of an uniform to a matrix
  14011. * @param uniform defines the webGL uniform location where to store the value
  14012. * @param matrix defines the matrix to store
  14013. */
  14014. Engine.prototype.setMatrix = function (uniform, matrix) {
  14015. if (!uniform)
  14016. return;
  14017. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14018. };
  14019. /**
  14020. * Set the value of an uniform to a matrix (3x3)
  14021. * @param uniform defines the webGL uniform location where to store the value
  14022. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14023. */
  14024. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14025. if (!uniform)
  14026. return;
  14027. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14028. };
  14029. /**
  14030. * Set the value of an uniform to a matrix (2x2)
  14031. * @param uniform defines the webGL uniform location where to store the value
  14032. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14033. */
  14034. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14035. if (!uniform)
  14036. return;
  14037. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14038. };
  14039. /**
  14040. * Set the value of an uniform to a number (int)
  14041. * @param uniform defines the webGL uniform location where to store the value
  14042. * @param value defines the int number to store
  14043. */
  14044. Engine.prototype.setInt = function (uniform, value) {
  14045. if (!uniform)
  14046. return;
  14047. this._gl.uniform1i(uniform, value);
  14048. };
  14049. /**
  14050. * Set the value of an uniform to a number (float)
  14051. * @param uniform defines the webGL uniform location where to store the value
  14052. * @param value defines the float number to store
  14053. */
  14054. Engine.prototype.setFloat = function (uniform, value) {
  14055. if (!uniform)
  14056. return;
  14057. this._gl.uniform1f(uniform, value);
  14058. };
  14059. /**
  14060. * Set the value of an uniform to a vec2
  14061. * @param uniform defines the webGL uniform location where to store the value
  14062. * @param x defines the 1st component of the value
  14063. * @param y defines the 2nd component of the value
  14064. */
  14065. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14066. if (!uniform)
  14067. return;
  14068. this._gl.uniform2f(uniform, x, y);
  14069. };
  14070. /**
  14071. * Set the value of an uniform to a vec3
  14072. * @param uniform defines the webGL uniform location where to store the value
  14073. * @param x defines the 1st component of the value
  14074. * @param y defines the 2nd component of the value
  14075. * @param z defines the 3rd component of the value
  14076. */
  14077. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14078. if (!uniform)
  14079. return;
  14080. this._gl.uniform3f(uniform, x, y, z);
  14081. };
  14082. /**
  14083. * Set the value of an uniform to a boolean
  14084. * @param uniform defines the webGL uniform location where to store the value
  14085. * @param bool defines the boolean to store
  14086. */
  14087. Engine.prototype.setBool = function (uniform, bool) {
  14088. if (!uniform)
  14089. return;
  14090. this._gl.uniform1i(uniform, bool);
  14091. };
  14092. /**
  14093. * Set the value of an uniform to a vec4
  14094. * @param uniform defines the webGL uniform location where to store the value
  14095. * @param x defines the 1st component of the value
  14096. * @param y defines the 2nd component of the value
  14097. * @param z defines the 3rd component of the value
  14098. * @param w defines the 4th component of the value
  14099. */
  14100. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14101. if (!uniform)
  14102. return;
  14103. this._gl.uniform4f(uniform, x, y, z, w);
  14104. };
  14105. /**
  14106. * Set the value of an uniform to a Color3
  14107. * @param uniform defines the webGL uniform location where to store the value
  14108. * @param color3 defines the color to store
  14109. */
  14110. Engine.prototype.setColor3 = function (uniform, color3) {
  14111. if (!uniform)
  14112. return;
  14113. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14114. };
  14115. /**
  14116. * Set the value of an uniform to a Color3 and an alpha value
  14117. * @param uniform defines the webGL uniform location where to store the value
  14118. * @param color3 defines the color to store
  14119. * @param alpha defines the alpha component to store
  14120. */
  14121. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14122. if (!uniform)
  14123. return;
  14124. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14125. };
  14126. /**
  14127. * Sets a Color4 on a uniform variable
  14128. * @param uniform defines the uniform location
  14129. * @param color4 defines the value to be set
  14130. */
  14131. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14132. if (!uniform)
  14133. return;
  14134. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14135. };
  14136. // States
  14137. /**
  14138. * Set various states to the webGL context
  14139. * @param culling defines backface culling state
  14140. * @param zOffset defines the value to apply to zOffset (0 by default)
  14141. * @param force defines if states must be applied even if cache is up to date
  14142. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14143. */
  14144. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14145. if (zOffset === void 0) { zOffset = 0; }
  14146. if (reverseSide === void 0) { reverseSide = false; }
  14147. // Culling
  14148. if (this._depthCullingState.cull !== culling || force) {
  14149. this._depthCullingState.cull = culling;
  14150. }
  14151. // Cull face
  14152. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14153. if (this._depthCullingState.cullFace !== cullFace || force) {
  14154. this._depthCullingState.cullFace = cullFace;
  14155. }
  14156. // Z offset
  14157. this.setZOffset(zOffset);
  14158. // Front face
  14159. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14160. if (this._depthCullingState.frontFace !== frontFace || force) {
  14161. this._depthCullingState.frontFace = frontFace;
  14162. }
  14163. };
  14164. /**
  14165. * Set the z offset to apply to current rendering
  14166. * @param value defines the offset to apply
  14167. */
  14168. Engine.prototype.setZOffset = function (value) {
  14169. this._depthCullingState.zOffset = value;
  14170. };
  14171. /**
  14172. * Gets the current value of the zOffset
  14173. * @returns the current zOffset state
  14174. */
  14175. Engine.prototype.getZOffset = function () {
  14176. return this._depthCullingState.zOffset;
  14177. };
  14178. /**
  14179. * Enable or disable depth buffering
  14180. * @param enable defines the state to set
  14181. */
  14182. Engine.prototype.setDepthBuffer = function (enable) {
  14183. this._depthCullingState.depthTest = enable;
  14184. };
  14185. /**
  14186. * Gets a boolean indicating if depth writing is enabled
  14187. * @returns the current depth writing state
  14188. */
  14189. Engine.prototype.getDepthWrite = function () {
  14190. return this._depthCullingState.depthMask;
  14191. };
  14192. /**
  14193. * Enable or disable depth writing
  14194. * @param enable defines the state to set
  14195. */
  14196. Engine.prototype.setDepthWrite = function (enable) {
  14197. this._depthCullingState.depthMask = enable;
  14198. };
  14199. /**
  14200. * Enable or disable color writing
  14201. * @param enable defines the state to set
  14202. */
  14203. Engine.prototype.setColorWrite = function (enable) {
  14204. this._gl.colorMask(enable, enable, enable, enable);
  14205. this._colorWrite = enable;
  14206. };
  14207. /**
  14208. * Gets a boolean indicating if color writing is enabled
  14209. * @returns the current color writing state
  14210. */
  14211. Engine.prototype.getColorWrite = function () {
  14212. return this._colorWrite;
  14213. };
  14214. /**
  14215. * Sets alpha constants used by some alpha blending modes
  14216. * @param r defines the red component
  14217. * @param g defines the green component
  14218. * @param b defines the blue component
  14219. * @param a defines the alpha component
  14220. */
  14221. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14222. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14223. };
  14224. /**
  14225. * Sets the current alpha mode
  14226. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14227. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14228. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14229. */
  14230. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14231. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14232. if (this._alphaMode === mode) {
  14233. return;
  14234. }
  14235. switch (mode) {
  14236. case Engine.ALPHA_DISABLE:
  14237. this._alphaState.alphaBlend = false;
  14238. break;
  14239. case Engine.ALPHA_PREMULTIPLIED:
  14240. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14241. this._alphaState.alphaBlend = true;
  14242. break;
  14243. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14244. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14245. this._alphaState.alphaBlend = true;
  14246. break;
  14247. case Engine.ALPHA_COMBINE:
  14248. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14249. this._alphaState.alphaBlend = true;
  14250. break;
  14251. case Engine.ALPHA_ONEONE:
  14252. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14253. this._alphaState.alphaBlend = true;
  14254. break;
  14255. case Engine.ALPHA_ADD:
  14256. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14257. this._alphaState.alphaBlend = true;
  14258. break;
  14259. case Engine.ALPHA_SUBTRACT:
  14260. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14261. this._alphaState.alphaBlend = true;
  14262. break;
  14263. case Engine.ALPHA_MULTIPLY:
  14264. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14265. this._alphaState.alphaBlend = true;
  14266. break;
  14267. case Engine.ALPHA_MAXIMIZED:
  14268. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14269. this._alphaState.alphaBlend = true;
  14270. break;
  14271. case Engine.ALPHA_INTERPOLATE:
  14272. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14273. this._alphaState.alphaBlend = true;
  14274. break;
  14275. case Engine.ALPHA_SCREENMODE:
  14276. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14277. this._alphaState.alphaBlend = true;
  14278. break;
  14279. }
  14280. if (!noDepthWriteChange) {
  14281. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14282. }
  14283. this._alphaMode = mode;
  14284. };
  14285. /**
  14286. * Gets the current alpha mode
  14287. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14288. * @returns the current alpha mode
  14289. */
  14290. Engine.prototype.getAlphaMode = function () {
  14291. return this._alphaMode;
  14292. };
  14293. // Textures
  14294. /**
  14295. * Clears the list of texture accessible through engine.
  14296. * This can help preventing texture load conflict due to name collision.
  14297. */
  14298. Engine.prototype.clearInternalTexturesCache = function () {
  14299. this._internalTexturesCache = [];
  14300. };
  14301. /**
  14302. * Force the entire cache to be cleared
  14303. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14304. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14305. */
  14306. Engine.prototype.wipeCaches = function (bruteForce) {
  14307. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14308. return;
  14309. }
  14310. this._currentEffect = null;
  14311. this._viewportCached.x = 0;
  14312. this._viewportCached.y = 0;
  14313. this._viewportCached.z = 0;
  14314. this._viewportCached.w = 0;
  14315. if (bruteForce) {
  14316. this.resetTextureCache();
  14317. this._currentProgram = null;
  14318. this._stencilState.reset();
  14319. this._depthCullingState.reset();
  14320. this.setDepthFunctionToLessOrEqual();
  14321. this._alphaState.reset();
  14322. this._unpackFlipYCached = null;
  14323. }
  14324. this._resetVertexBufferBinding();
  14325. this._cachedIndexBuffer = null;
  14326. this._cachedEffectForVertexBuffers = null;
  14327. this._unbindVertexArrayObject();
  14328. this.bindIndexBuffer(null);
  14329. };
  14330. /**
  14331. * Set the compressed texture format to use, based on the formats you have, and the formats
  14332. * supported by the hardware / browser.
  14333. *
  14334. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14335. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14336. * to API arguments needed to compressed textures. This puts the burden on the container
  14337. * generator to house the arcane code for determining these for current & future formats.
  14338. *
  14339. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14340. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14341. *
  14342. * Note: The result of this call is not taken into account when a texture is base64.
  14343. *
  14344. * @param formatsAvailable defines the list of those format families you have created
  14345. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14346. *
  14347. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14348. * @returns The extension selected.
  14349. */
  14350. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14351. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14352. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14353. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14354. return this._textureFormatInUse = this._texturesSupported[i];
  14355. }
  14356. }
  14357. }
  14358. // actively set format to nothing, to allow this to be called more than once
  14359. // and possibly fail the 2nd time
  14360. this._textureFormatInUse = null;
  14361. return null;
  14362. };
  14363. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14364. var gl = this._gl;
  14365. var magFilter = gl.NEAREST;
  14366. var minFilter = gl.NEAREST;
  14367. switch (samplingMode) {
  14368. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14369. magFilter = gl.LINEAR;
  14370. if (generateMipMaps) {
  14371. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14372. }
  14373. else {
  14374. minFilter = gl.LINEAR;
  14375. }
  14376. break;
  14377. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14378. magFilter = gl.LINEAR;
  14379. if (generateMipMaps) {
  14380. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14381. }
  14382. else {
  14383. minFilter = gl.LINEAR;
  14384. }
  14385. break;
  14386. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14387. magFilter = gl.NEAREST;
  14388. if (generateMipMaps) {
  14389. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14390. }
  14391. else {
  14392. minFilter = gl.NEAREST;
  14393. }
  14394. break;
  14395. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14396. magFilter = gl.NEAREST;
  14397. if (generateMipMaps) {
  14398. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14399. }
  14400. else {
  14401. minFilter = gl.NEAREST;
  14402. }
  14403. break;
  14404. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14405. magFilter = gl.NEAREST;
  14406. if (generateMipMaps) {
  14407. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14408. }
  14409. else {
  14410. minFilter = gl.LINEAR;
  14411. }
  14412. break;
  14413. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14414. magFilter = gl.NEAREST;
  14415. if (generateMipMaps) {
  14416. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14417. }
  14418. else {
  14419. minFilter = gl.LINEAR;
  14420. }
  14421. break;
  14422. case Engine.TEXTURE_NEAREST_LINEAR:
  14423. magFilter = gl.NEAREST;
  14424. minFilter = gl.LINEAR;
  14425. break;
  14426. case Engine.TEXTURE_NEAREST_NEAREST:
  14427. magFilter = gl.NEAREST;
  14428. minFilter = gl.NEAREST;
  14429. break;
  14430. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14431. magFilter = gl.LINEAR;
  14432. if (generateMipMaps) {
  14433. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14434. }
  14435. else {
  14436. minFilter = gl.NEAREST;
  14437. }
  14438. break;
  14439. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14440. magFilter = gl.LINEAR;
  14441. if (generateMipMaps) {
  14442. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14443. }
  14444. else {
  14445. minFilter = gl.NEAREST;
  14446. }
  14447. break;
  14448. case Engine.TEXTURE_LINEAR_LINEAR:
  14449. magFilter = gl.LINEAR;
  14450. minFilter = gl.LINEAR;
  14451. break;
  14452. case Engine.TEXTURE_LINEAR_NEAREST:
  14453. magFilter = gl.LINEAR;
  14454. minFilter = gl.NEAREST;
  14455. break;
  14456. }
  14457. return {
  14458. min: minFilter,
  14459. mag: magFilter
  14460. };
  14461. };
  14462. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14463. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14464. var img;
  14465. var onload = function () {
  14466. loadedImages[index] = img;
  14467. loadedImages._internalCount++;
  14468. if (scene) {
  14469. scene._removePendingData(img);
  14470. }
  14471. if (loadedImages._internalCount === 6) {
  14472. onfinish(loadedImages);
  14473. }
  14474. };
  14475. var onerror = function (message, exception) {
  14476. if (scene) {
  14477. scene._removePendingData(img);
  14478. }
  14479. if (onErrorCallBack) {
  14480. onErrorCallBack(message, exception);
  14481. }
  14482. };
  14483. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14484. if (scene) {
  14485. scene._addPendingData(img);
  14486. }
  14487. };
  14488. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14489. if (onError === void 0) { onError = null; }
  14490. var loadedImages = [];
  14491. loadedImages._internalCount = 0;
  14492. for (var index = 0; index < 6; index++) {
  14493. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14494. }
  14495. };
  14496. ;
  14497. /** @hidden */
  14498. Engine.prototype._createTexture = function () {
  14499. var texture = this._gl.createTexture();
  14500. if (!texture) {
  14501. throw new Error("Unable to create texture");
  14502. }
  14503. return texture;
  14504. };
  14505. /**
  14506. * Usually called from BABYLON.Texture.ts.
  14507. * Passed information to create a WebGLTexture
  14508. * @param urlArg defines a value which contains one of the following:
  14509. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14510. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14511. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14512. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14513. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14514. * @param scene needed for loading to the correct scene
  14515. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14516. * @param onLoad optional callback to be called upon successful completion
  14517. * @param onError optional callback to be called upon failure
  14518. * @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
  14519. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14520. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14521. * @param forcedExtension defines the extension to use to pick the right loader
  14522. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14523. */
  14524. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14525. var _this = this;
  14526. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14527. if (onLoad === void 0) { onLoad = null; }
  14528. if (onError === void 0) { onError = null; }
  14529. if (buffer === void 0) { buffer = null; }
  14530. if (fallback === void 0) { fallback = null; }
  14531. if (format === void 0) { format = null; }
  14532. if (forcedExtension === void 0) { forcedExtension = null; }
  14533. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14534. var fromData = url.substr(0, 5) === "data:";
  14535. var fromBlob = url.substr(0, 5) === "blob:";
  14536. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14537. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14538. // establish the file extension, if possible
  14539. var lastDot = url.lastIndexOf('.');
  14540. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14541. var loader = null;
  14542. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14543. var availableLoader = _a[_i];
  14544. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14545. loader = availableLoader;
  14546. break;
  14547. }
  14548. }
  14549. if (loader) {
  14550. url = loader.transformUrl(url, this._textureFormatInUse);
  14551. }
  14552. if (scene) {
  14553. scene._addPendingData(texture);
  14554. }
  14555. texture.url = url;
  14556. texture.generateMipMaps = !noMipmap;
  14557. texture.samplingMode = samplingMode;
  14558. texture.invertY = invertY;
  14559. if (!this._doNotHandleContextLost) {
  14560. // Keep a link to the buffer only if we plan to handle context lost
  14561. texture._buffer = buffer;
  14562. }
  14563. var onLoadObserver = null;
  14564. if (onLoad && !fallback) {
  14565. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14566. }
  14567. if (!fallback)
  14568. this._internalTexturesCache.push(texture);
  14569. var onInternalError = function (message, exception) {
  14570. if (scene) {
  14571. scene._removePendingData(texture);
  14572. }
  14573. var customFallback = false;
  14574. if (loader) {
  14575. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14576. if (fallbackUrl) {
  14577. // Add Back
  14578. customFallback = true;
  14579. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14580. }
  14581. }
  14582. if (!customFallback) {
  14583. if (onLoadObserver) {
  14584. texture.onLoadedObservable.remove(onLoadObserver);
  14585. }
  14586. if (BABYLON.Tools.UseFallbackTexture) {
  14587. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14588. }
  14589. }
  14590. if (onError) {
  14591. onError(message || "Unknown error", exception);
  14592. }
  14593. };
  14594. // processing for non-image formats
  14595. if (loader) {
  14596. var callback = function (data) {
  14597. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14598. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14599. done();
  14600. return false;
  14601. }, samplingMode);
  14602. });
  14603. };
  14604. if (!buffer) {
  14605. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14606. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14607. });
  14608. }
  14609. else {
  14610. callback(buffer);
  14611. }
  14612. }
  14613. else {
  14614. var onload = function (img) {
  14615. if (fromBlob && !_this._doNotHandleContextLost) {
  14616. // We need to store the image if we need to rebuild the texture
  14617. // in case of a webgl context lost
  14618. texture._buffer = img;
  14619. }
  14620. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14621. var gl = _this._gl;
  14622. var isPot = (img.width === potWidth && img.height === potHeight);
  14623. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14624. if (isPot) {
  14625. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14626. return false;
  14627. }
  14628. var maxTextureSize = _this._caps.maxTextureSize;
  14629. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14630. _this._prepareWorkingCanvas();
  14631. if (!_this._workingCanvas || !_this._workingContext) {
  14632. return false;
  14633. }
  14634. _this._workingCanvas.width = potWidth;
  14635. _this._workingCanvas.height = potHeight;
  14636. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14637. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14638. texture.width = potWidth;
  14639. texture.height = potHeight;
  14640. return false;
  14641. }
  14642. else {
  14643. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14644. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14645. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14646. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14647. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14648. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14649. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14650. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14651. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14652. _this._releaseTexture(source_1);
  14653. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14654. continuationCallback();
  14655. });
  14656. }
  14657. return true;
  14658. }, samplingMode);
  14659. };
  14660. if (!fromData || isBase64) {
  14661. if (buffer instanceof HTMLImageElement) {
  14662. onload(buffer);
  14663. }
  14664. else {
  14665. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14666. }
  14667. }
  14668. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14669. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14670. }
  14671. else {
  14672. onload(buffer);
  14673. }
  14674. }
  14675. return texture;
  14676. };
  14677. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14678. var _this = this;
  14679. var rtt = this.createRenderTargetTexture({
  14680. width: destination.width,
  14681. height: destination.height,
  14682. }, {
  14683. generateMipMaps: false,
  14684. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14685. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14686. generateDepthBuffer: false,
  14687. generateStencilBuffer: false
  14688. });
  14689. if (!this._rescalePostProcess) {
  14690. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14691. }
  14692. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14693. _this._rescalePostProcess.onApply = function (effect) {
  14694. effect._bindTexture("textureSampler", source);
  14695. };
  14696. var hostingScene = scene;
  14697. if (!hostingScene) {
  14698. hostingScene = _this.scenes[_this.scenes.length - 1];
  14699. }
  14700. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14701. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14702. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14703. _this.unBindFramebuffer(rtt);
  14704. _this._releaseTexture(rtt);
  14705. if (onComplete) {
  14706. onComplete();
  14707. }
  14708. });
  14709. };
  14710. /**
  14711. * Update a raw texture
  14712. * @param texture defines the texture to update
  14713. * @param data defines the data to store in the texture
  14714. * @param format defines the format of the data
  14715. * @param invertY defines if data must be stored with Y axis inverted
  14716. * @param compression defines the compression used (null by default)
  14717. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14718. */
  14719. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14720. if (compression === void 0) { compression = null; }
  14721. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14722. if (!texture) {
  14723. return;
  14724. }
  14725. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14726. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14727. // babylon's internalFormat but gl's texImage2D format
  14728. var internalFormat = this._getInternalFormat(format);
  14729. var textureType = this._getWebGLTextureType(type);
  14730. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14731. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14732. if (!this._doNotHandleContextLost) {
  14733. texture._bufferView = data;
  14734. texture.format = format;
  14735. texture.type = type;
  14736. texture.invertY = invertY;
  14737. texture._compression = compression;
  14738. }
  14739. if (texture.width % 4 !== 0) {
  14740. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14741. }
  14742. if (compression && data) {
  14743. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14744. }
  14745. else {
  14746. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14747. }
  14748. if (texture.generateMipMaps) {
  14749. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14750. }
  14751. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14752. // this.resetTextureCache();
  14753. texture.isReady = true;
  14754. };
  14755. /**
  14756. * Creates a raw texture
  14757. * @param data defines the data to store in the texture
  14758. * @param width defines the width of the texture
  14759. * @param height defines the height of the texture
  14760. * @param format defines the format of the data
  14761. * @param generateMipMaps defines if the engine should generate the mip levels
  14762. * @param invertY defines if data must be stored with Y axis inverted
  14763. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14764. * @param compression defines the compression used (null by default)
  14765. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14766. * @returns the raw texture inside an InternalTexture
  14767. */
  14768. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14769. if (compression === void 0) { compression = null; }
  14770. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14771. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14772. texture.baseWidth = width;
  14773. texture.baseHeight = height;
  14774. texture.width = width;
  14775. texture.height = height;
  14776. texture.format = format;
  14777. texture.generateMipMaps = generateMipMaps;
  14778. texture.samplingMode = samplingMode;
  14779. texture.invertY = invertY;
  14780. texture._compression = compression;
  14781. texture.type = type;
  14782. if (!this._doNotHandleContextLost) {
  14783. texture._bufferView = data;
  14784. }
  14785. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14786. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14787. // Filters
  14788. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14789. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14790. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14791. if (generateMipMaps) {
  14792. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14793. }
  14794. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14795. this._internalTexturesCache.push(texture);
  14796. return texture;
  14797. };
  14798. /** @hidden */
  14799. Engine.prototype._unpackFlipY = function (value) {
  14800. if (this._unpackFlipYCached !== value) {
  14801. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14802. if (this.enableUnpackFlipYCached) {
  14803. this._unpackFlipYCached = value;
  14804. }
  14805. }
  14806. };
  14807. /** @hidden */
  14808. Engine.prototype._getUnpackAlignement = function () {
  14809. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14810. };
  14811. /**
  14812. * Creates a dynamic texture
  14813. * @param width defines the width of the texture
  14814. * @param height defines the height of the texture
  14815. * @param generateMipMaps defines if the engine should generate the mip levels
  14816. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14817. * @returns the dynamic texture inside an InternalTexture
  14818. */
  14819. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14820. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14821. texture.baseWidth = width;
  14822. texture.baseHeight = height;
  14823. if (generateMipMaps) {
  14824. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14825. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14826. }
  14827. // this.resetTextureCache();
  14828. texture.width = width;
  14829. texture.height = height;
  14830. texture.isReady = false;
  14831. texture.generateMipMaps = generateMipMaps;
  14832. texture.samplingMode = samplingMode;
  14833. this.updateTextureSamplingMode(samplingMode, texture);
  14834. this._internalTexturesCache.push(texture);
  14835. return texture;
  14836. };
  14837. /**
  14838. * Update the sampling mode of a given texture
  14839. * @param samplingMode defines the required sampling mode
  14840. * @param texture defines the texture to update
  14841. */
  14842. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14843. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14844. if (texture.isCube) {
  14845. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14846. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14847. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14848. }
  14849. else if (texture.is3D) {
  14850. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14851. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14852. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14853. }
  14854. else {
  14855. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14856. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14857. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14858. }
  14859. texture.samplingMode = samplingMode;
  14860. };
  14861. /**
  14862. * Update the content of a dynamic texture
  14863. * @param texture defines the texture to update
  14864. * @param canvas defines the canvas containing the source
  14865. * @param invertY defines if data must be stored with Y axis inverted
  14866. * @param premulAlpha defines if alpha is stored as premultiplied
  14867. * @param format defines the format of the data
  14868. */
  14869. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14870. if (premulAlpha === void 0) { premulAlpha = false; }
  14871. if (!texture) {
  14872. return;
  14873. }
  14874. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14875. this._unpackFlipY(invertY);
  14876. if (premulAlpha) {
  14877. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14878. }
  14879. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14880. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14881. if (texture.generateMipMaps) {
  14882. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14883. }
  14884. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14885. if (premulAlpha) {
  14886. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14887. }
  14888. texture.isReady = true;
  14889. };
  14890. /**
  14891. * Update a video texture
  14892. * @param texture defines the texture to update
  14893. * @param video defines the video element to use
  14894. * @param invertY defines if data must be stored with Y axis inverted
  14895. */
  14896. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14897. if (!texture || texture._isDisabled) {
  14898. return;
  14899. }
  14900. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14901. this._unpackFlipY(!invertY); // Video are upside down by default
  14902. try {
  14903. // Testing video texture support
  14904. if (this._videoTextureSupported === undefined) {
  14905. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14906. if (this._gl.getError() !== 0) {
  14907. this._videoTextureSupported = false;
  14908. }
  14909. else {
  14910. this._videoTextureSupported = true;
  14911. }
  14912. }
  14913. // Copy video through the current working canvas if video texture is not supported
  14914. if (!this._videoTextureSupported) {
  14915. if (!texture._workingCanvas) {
  14916. texture._workingCanvas = document.createElement("canvas");
  14917. var context = texture._workingCanvas.getContext("2d");
  14918. if (!context) {
  14919. throw new Error("Unable to get 2d context");
  14920. }
  14921. texture._workingContext = context;
  14922. texture._workingCanvas.width = texture.width;
  14923. texture._workingCanvas.height = texture.height;
  14924. }
  14925. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14926. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14927. }
  14928. else {
  14929. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14930. }
  14931. if (texture.generateMipMaps) {
  14932. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14933. }
  14934. if (!wasPreviouslyBound) {
  14935. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14936. }
  14937. // this.resetTextureCache();
  14938. texture.isReady = true;
  14939. }
  14940. catch (ex) {
  14941. // Something unexpected
  14942. // Let's disable the texture
  14943. texture._isDisabled = true;
  14944. }
  14945. };
  14946. /**
  14947. * Updates a depth texture Comparison Mode and Function.
  14948. * If the comparison Function is equal to 0, the mode will be set to none.
  14949. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14950. * @param texture The texture to set the comparison function for
  14951. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14952. */
  14953. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14954. if (this.webGLVersion === 1) {
  14955. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14956. return;
  14957. }
  14958. var gl = this._gl;
  14959. if (texture.isCube) {
  14960. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14961. if (comparisonFunction === 0) {
  14962. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14963. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14964. }
  14965. else {
  14966. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14967. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14968. }
  14969. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14970. }
  14971. else {
  14972. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14973. if (comparisonFunction === 0) {
  14974. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14975. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14976. }
  14977. else {
  14978. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14979. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14980. }
  14981. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14982. }
  14983. texture._comparisonFunction = comparisonFunction;
  14984. };
  14985. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14986. var width = size.width || size;
  14987. var height = size.height || size;
  14988. internalTexture.baseWidth = width;
  14989. internalTexture.baseHeight = height;
  14990. internalTexture.width = width;
  14991. internalTexture.height = height;
  14992. internalTexture.isReady = true;
  14993. internalTexture.samples = 1;
  14994. internalTexture.generateMipMaps = false;
  14995. internalTexture._generateDepthBuffer = true;
  14996. internalTexture._generateStencilBuffer = generateStencil;
  14997. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14998. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14999. internalTexture._comparisonFunction = comparisonFunction;
  15000. var gl = this._gl;
  15001. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15002. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15003. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15004. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15005. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15006. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15007. if (comparisonFunction === 0) {
  15008. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15009. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15010. }
  15011. else {
  15012. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15013. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15014. }
  15015. };
  15016. /**
  15017. * Creates a depth stencil texture.
  15018. * This is only available in WebGL 2 or with the depth texture extension available.
  15019. * @param size The size of face edge in the texture.
  15020. * @param options The options defining the texture.
  15021. * @returns The texture
  15022. */
  15023. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15024. if (options.isCube) {
  15025. var width = size.width || size;
  15026. return this._createDepthStencilCubeTexture(width, options);
  15027. }
  15028. else {
  15029. return this._createDepthStencilTexture(size, options);
  15030. }
  15031. };
  15032. /**
  15033. * Creates a depth stencil texture.
  15034. * This is only available in WebGL 2 or with the depth texture extension available.
  15035. * @param size The size of face edge in the texture.
  15036. * @param options The options defining the texture.
  15037. * @returns The texture
  15038. */
  15039. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15040. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15041. if (!this._caps.depthTextureExtension) {
  15042. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15043. return internalTexture;
  15044. }
  15045. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15046. var gl = this._gl;
  15047. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15048. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15049. if (this.webGLVersion > 1) {
  15050. if (internalOptions.generateStencil) {
  15051. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15052. }
  15053. else {
  15054. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15055. }
  15056. }
  15057. else {
  15058. if (internalOptions.generateStencil) {
  15059. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15060. }
  15061. else {
  15062. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15063. }
  15064. }
  15065. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15066. return internalTexture;
  15067. };
  15068. /**
  15069. * Creates a depth stencil cube texture.
  15070. * This is only available in WebGL 2.
  15071. * @param size The size of face edge in the cube texture.
  15072. * @param options The options defining the cube texture.
  15073. * @returns The cube texture
  15074. */
  15075. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15076. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15077. internalTexture.isCube = true;
  15078. if (this.webGLVersion === 1) {
  15079. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15080. return internalTexture;
  15081. }
  15082. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15083. var gl = this._gl;
  15084. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15085. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15086. // Create the depth/stencil buffer
  15087. for (var face = 0; face < 6; face++) {
  15088. if (internalOptions.generateStencil) {
  15089. 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);
  15090. }
  15091. else {
  15092. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15093. }
  15094. }
  15095. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15096. return internalTexture;
  15097. };
  15098. /**
  15099. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15100. * @param renderTarget The render target to set the frame buffer for
  15101. */
  15102. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15103. // Create the framebuffer
  15104. var internalTexture = renderTarget.getInternalTexture();
  15105. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15106. return;
  15107. }
  15108. var gl = this._gl;
  15109. var depthStencilTexture = renderTarget.depthStencilTexture;
  15110. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15111. if (depthStencilTexture.isCube) {
  15112. if (depthStencilTexture._generateStencilBuffer) {
  15113. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15114. }
  15115. else {
  15116. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15117. }
  15118. }
  15119. else {
  15120. if (depthStencilTexture._generateStencilBuffer) {
  15121. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15122. }
  15123. else {
  15124. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15125. }
  15126. }
  15127. this.bindUnboundFramebuffer(null);
  15128. };
  15129. /**
  15130. * Creates a new render target texture
  15131. * @param size defines the size of the texture
  15132. * @param options defines the options used to create the texture
  15133. * @returns a new render target texture stored in an InternalTexture
  15134. */
  15135. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15136. var fullOptions = new RenderTargetCreationOptions();
  15137. if (options !== undefined && typeof options === "object") {
  15138. fullOptions.generateMipMaps = options.generateMipMaps;
  15139. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15140. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15141. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15142. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15143. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15144. }
  15145. else {
  15146. fullOptions.generateMipMaps = options;
  15147. fullOptions.generateDepthBuffer = true;
  15148. fullOptions.generateStencilBuffer = false;
  15149. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15150. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15151. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15152. }
  15153. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15154. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15155. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15156. }
  15157. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15158. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15159. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15160. }
  15161. var gl = this._gl;
  15162. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15163. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15164. var width = size.width || size;
  15165. var height = size.height || size;
  15166. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15167. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15168. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15169. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15170. }
  15171. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15172. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15173. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15174. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15175. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15176. // Create the framebuffer
  15177. var currentFrameBuffer = this._currentFramebuffer;
  15178. var framebuffer = gl.createFramebuffer();
  15179. this.bindUnboundFramebuffer(framebuffer);
  15180. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15181. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15182. if (fullOptions.generateMipMaps) {
  15183. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15184. }
  15185. // Unbind
  15186. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15187. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15188. this.bindUnboundFramebuffer(currentFrameBuffer);
  15189. texture._framebuffer = framebuffer;
  15190. texture.baseWidth = width;
  15191. texture.baseHeight = height;
  15192. texture.width = width;
  15193. texture.height = height;
  15194. texture.isReady = true;
  15195. texture.samples = 1;
  15196. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15197. texture.samplingMode = fullOptions.samplingMode;
  15198. texture.type = fullOptions.type;
  15199. texture.format = fullOptions.format;
  15200. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15201. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15202. // this.resetTextureCache();
  15203. this._internalTexturesCache.push(texture);
  15204. return texture;
  15205. };
  15206. /**
  15207. * Create a multi render target texture
  15208. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15209. * @param size defines the size of the texture
  15210. * @param options defines the creation options
  15211. * @returns the cube texture as an InternalTexture
  15212. */
  15213. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15214. var generateMipMaps = false;
  15215. var generateDepthBuffer = true;
  15216. var generateStencilBuffer = false;
  15217. var generateDepthTexture = false;
  15218. var textureCount = 1;
  15219. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15220. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15221. var types = new Array();
  15222. var samplingModes = new Array();
  15223. if (options !== undefined) {
  15224. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15225. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15226. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15227. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15228. textureCount = options.textureCount || 1;
  15229. if (options.types) {
  15230. types = options.types;
  15231. }
  15232. if (options.samplingModes) {
  15233. samplingModes = options.samplingModes;
  15234. }
  15235. }
  15236. var gl = this._gl;
  15237. // Create the framebuffer
  15238. var framebuffer = gl.createFramebuffer();
  15239. this.bindUnboundFramebuffer(framebuffer);
  15240. var width = size.width || size;
  15241. var height = size.height || size;
  15242. var textures = [];
  15243. var attachments = [];
  15244. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15245. for (var i = 0; i < textureCount; i++) {
  15246. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15247. var type = types[i] || defaultType;
  15248. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15249. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15250. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15251. }
  15252. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15253. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15254. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15255. }
  15256. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15257. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15258. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15259. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15260. }
  15261. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15262. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15263. textures.push(texture);
  15264. attachments.push(attachment);
  15265. gl.activeTexture(gl["TEXTURE" + i]);
  15266. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15267. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15268. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15269. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15270. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15271. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15272. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15273. if (generateMipMaps) {
  15274. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15275. }
  15276. // Unbind
  15277. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15278. texture._framebuffer = framebuffer;
  15279. texture._depthStencilBuffer = depthStencilBuffer;
  15280. texture.baseWidth = width;
  15281. texture.baseHeight = height;
  15282. texture.width = width;
  15283. texture.height = height;
  15284. texture.isReady = true;
  15285. texture.samples = 1;
  15286. texture.generateMipMaps = generateMipMaps;
  15287. texture.samplingMode = samplingMode;
  15288. texture.type = type;
  15289. texture._generateDepthBuffer = generateDepthBuffer;
  15290. texture._generateStencilBuffer = generateStencilBuffer;
  15291. texture._attachments = attachments;
  15292. this._internalTexturesCache.push(texture);
  15293. }
  15294. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15295. // Depth texture
  15296. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15297. gl.activeTexture(gl.TEXTURE0);
  15298. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15299. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15300. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15301. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15302. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15303. 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);
  15304. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15305. depthTexture._framebuffer = framebuffer;
  15306. depthTexture.baseWidth = width;
  15307. depthTexture.baseHeight = height;
  15308. depthTexture.width = width;
  15309. depthTexture.height = height;
  15310. depthTexture.isReady = true;
  15311. depthTexture.samples = 1;
  15312. depthTexture.generateMipMaps = generateMipMaps;
  15313. depthTexture.samplingMode = gl.NEAREST;
  15314. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15315. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15316. textures.push(depthTexture);
  15317. this._internalTexturesCache.push(depthTexture);
  15318. }
  15319. gl.drawBuffers(attachments);
  15320. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15321. this.bindUnboundFramebuffer(null);
  15322. this.resetTextureCache();
  15323. return textures;
  15324. };
  15325. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15326. if (samples === void 0) { samples = 1; }
  15327. var depthStencilBuffer = null;
  15328. var gl = this._gl;
  15329. // Create the depth/stencil buffer
  15330. if (generateStencilBuffer) {
  15331. depthStencilBuffer = gl.createRenderbuffer();
  15332. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15333. if (samples > 1) {
  15334. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15335. }
  15336. else {
  15337. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15338. }
  15339. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15340. }
  15341. else if (generateDepthBuffer) {
  15342. depthStencilBuffer = gl.createRenderbuffer();
  15343. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15344. if (samples > 1) {
  15345. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15346. }
  15347. else {
  15348. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15349. }
  15350. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15351. }
  15352. return depthStencilBuffer;
  15353. };
  15354. /**
  15355. * Updates the sample count of a render target texture
  15356. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15357. * @param texture defines the texture to update
  15358. * @param samples defines the sample count to set
  15359. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15360. */
  15361. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15362. if (this.webGLVersion < 2 || !texture) {
  15363. return 1;
  15364. }
  15365. if (texture.samples === samples) {
  15366. return samples;
  15367. }
  15368. var gl = this._gl;
  15369. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15370. // Dispose previous render buffers
  15371. if (texture._depthStencilBuffer) {
  15372. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15373. texture._depthStencilBuffer = null;
  15374. }
  15375. if (texture._MSAAFramebuffer) {
  15376. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15377. texture._MSAAFramebuffer = null;
  15378. }
  15379. if (texture._MSAARenderBuffer) {
  15380. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15381. texture._MSAARenderBuffer = null;
  15382. }
  15383. if (samples > 1) {
  15384. var framebuffer = gl.createFramebuffer();
  15385. if (!framebuffer) {
  15386. throw new Error("Unable to create multi sampled framebuffer");
  15387. }
  15388. texture._MSAAFramebuffer = framebuffer;
  15389. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15390. var colorRenderbuffer = gl.createRenderbuffer();
  15391. if (!colorRenderbuffer) {
  15392. throw new Error("Unable to create multi sampled framebuffer");
  15393. }
  15394. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15395. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15396. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15397. texture._MSAARenderBuffer = colorRenderbuffer;
  15398. }
  15399. else {
  15400. this.bindUnboundFramebuffer(texture._framebuffer);
  15401. }
  15402. texture.samples = samples;
  15403. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15404. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15405. this.bindUnboundFramebuffer(null);
  15406. return samples;
  15407. };
  15408. /**
  15409. * Update the sample count for a given multiple render target texture
  15410. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15411. * @param textures defines the textures to update
  15412. * @param samples defines the sample count to set
  15413. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15414. */
  15415. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15416. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15417. return 1;
  15418. }
  15419. if (textures[0].samples === samples) {
  15420. return samples;
  15421. }
  15422. var gl = this._gl;
  15423. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15424. // Dispose previous render buffers
  15425. if (textures[0]._depthStencilBuffer) {
  15426. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15427. textures[0]._depthStencilBuffer = null;
  15428. }
  15429. if (textures[0]._MSAAFramebuffer) {
  15430. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15431. textures[0]._MSAAFramebuffer = null;
  15432. }
  15433. for (var i = 0; i < textures.length; i++) {
  15434. if (textures[i]._MSAARenderBuffer) {
  15435. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15436. textures[i]._MSAARenderBuffer = null;
  15437. }
  15438. }
  15439. if (samples > 1) {
  15440. var framebuffer = gl.createFramebuffer();
  15441. if (!framebuffer) {
  15442. throw new Error("Unable to create multi sampled framebuffer");
  15443. }
  15444. this.bindUnboundFramebuffer(framebuffer);
  15445. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15446. var attachments = [];
  15447. for (var i = 0; i < textures.length; i++) {
  15448. var texture = textures[i];
  15449. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15450. var colorRenderbuffer = gl.createRenderbuffer();
  15451. if (!colorRenderbuffer) {
  15452. throw new Error("Unable to create multi sampled framebuffer");
  15453. }
  15454. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15455. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15456. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15457. texture._MSAAFramebuffer = framebuffer;
  15458. texture._MSAARenderBuffer = colorRenderbuffer;
  15459. texture.samples = samples;
  15460. texture._depthStencilBuffer = depthStencilBuffer;
  15461. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15462. attachments.push(attachment);
  15463. }
  15464. gl.drawBuffers(attachments);
  15465. }
  15466. else {
  15467. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15468. }
  15469. this.bindUnboundFramebuffer(null);
  15470. return samples;
  15471. };
  15472. /** @hidden */
  15473. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15474. if (faceIndex === void 0) { faceIndex = 0; }
  15475. if (lod === void 0) { lod = 0; }
  15476. var gl = this._gl;
  15477. var target = gl.TEXTURE_2D;
  15478. if (texture.isCube) {
  15479. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15480. }
  15481. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15482. };
  15483. /** @hidden */
  15484. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15485. if (faceIndex === void 0) { faceIndex = 0; }
  15486. if (lod === void 0) { lod = 0; }
  15487. var gl = this._gl;
  15488. var textureType = this._getWebGLTextureType(texture.type);
  15489. var format = this._getInternalFormat(texture.format);
  15490. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15491. this._unpackFlipY(texture.invertY);
  15492. var target = gl.TEXTURE_2D;
  15493. if (texture.isCube) {
  15494. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15495. }
  15496. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15497. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15498. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15499. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15500. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15501. };
  15502. /** @hidden */
  15503. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15504. if (faceIndex === void 0) { faceIndex = 0; }
  15505. if (lod === void 0) { lod = 0; }
  15506. var gl = this._gl;
  15507. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15508. this._bindTextureDirectly(bindTarget, texture, true);
  15509. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15510. this._bindTextureDirectly(bindTarget, null, true);
  15511. };
  15512. /** @hidden */
  15513. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15514. if (faceIndex === void 0) { faceIndex = 0; }
  15515. if (lod === void 0) { lod = 0; }
  15516. var gl = this._gl;
  15517. var textureType = this._getWebGLTextureType(texture.type);
  15518. var format = this._getInternalFormat(texture.format);
  15519. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15520. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15521. this._bindTextureDirectly(bindTarget, texture, true);
  15522. this._unpackFlipY(texture.invertY);
  15523. var target = gl.TEXTURE_2D;
  15524. if (texture.isCube) {
  15525. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15526. }
  15527. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15528. this._bindTextureDirectly(bindTarget, null, true);
  15529. };
  15530. /**
  15531. * Creates a new render target cube texture
  15532. * @param size defines the size of the texture
  15533. * @param options defines the options used to create the texture
  15534. * @returns a new render target cube texture stored in an InternalTexture
  15535. */
  15536. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15537. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15538. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15539. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15540. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15541. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15542. }
  15543. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15544. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15545. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15546. }
  15547. var gl = this._gl;
  15548. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15549. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15550. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15551. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15552. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15553. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15554. }
  15555. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15556. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15557. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15558. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15559. for (var face = 0; face < 6; face++) {
  15560. 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);
  15561. }
  15562. // Create the framebuffer
  15563. var framebuffer = gl.createFramebuffer();
  15564. this.bindUnboundFramebuffer(framebuffer);
  15565. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15566. // MipMaps
  15567. if (fullOptions.generateMipMaps) {
  15568. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15569. }
  15570. // Unbind
  15571. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15572. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15573. this.bindUnboundFramebuffer(null);
  15574. texture._framebuffer = framebuffer;
  15575. texture.width = size;
  15576. texture.height = size;
  15577. texture.isReady = true;
  15578. texture.isCube = true;
  15579. texture.samples = 1;
  15580. texture.generateMipMaps = fullOptions.generateMipMaps;
  15581. texture.samplingMode = fullOptions.samplingMode;
  15582. texture.type = fullOptions.type;
  15583. texture.format = fullOptions.format;
  15584. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15585. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15586. this._internalTexturesCache.push(texture);
  15587. return texture;
  15588. };
  15589. /**
  15590. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15591. * @param rootUrl defines the url where the file to load is located
  15592. * @param scene defines the current scene
  15593. * @param lodScale defines scale to apply to the mip map selection
  15594. * @param lodOffset defines offset to apply to the mip map selection
  15595. * @param onLoad defines an optional callback raised when the texture is loaded
  15596. * @param onError defines an optional callback raised if there is an issue to load the texture
  15597. * @param format defines the format of the data
  15598. * @param forcedExtension defines the extension to use to pick the right loader
  15599. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15600. * @returns the cube texture as an InternalTexture
  15601. */
  15602. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15603. var _this = this;
  15604. if (onLoad === void 0) { onLoad = null; }
  15605. if (onError === void 0) { onError = null; }
  15606. if (forcedExtension === void 0) { forcedExtension = null; }
  15607. if (createPolynomials === void 0) { createPolynomials = true; }
  15608. var callback = function (loadData) {
  15609. if (!loadData) {
  15610. if (onLoad) {
  15611. onLoad(null);
  15612. }
  15613. return;
  15614. }
  15615. var texture = loadData.texture;
  15616. if (!createPolynomials) {
  15617. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15618. }
  15619. else if (loadData.info.sphericalPolynomial) {
  15620. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15621. }
  15622. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15623. if (_this._caps.textureLOD) {
  15624. // Do not add extra process if texture lod is supported.
  15625. if (onLoad) {
  15626. onLoad(texture);
  15627. }
  15628. return;
  15629. }
  15630. var mipSlices = 3;
  15631. var gl = _this._gl;
  15632. var width = loadData.width;
  15633. if (!width) {
  15634. return;
  15635. }
  15636. var textures = [];
  15637. for (var i = 0; i < mipSlices; i++) {
  15638. //compute LOD from even spacing in smoothness (matching shader calculation)
  15639. var smoothness = i / (mipSlices - 1);
  15640. var roughness = 1 - smoothness;
  15641. var minLODIndex = lodOffset; // roughness = 0
  15642. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15643. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15644. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15645. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15646. glTextureFromLod.type = texture.type;
  15647. glTextureFromLod.format = texture.format;
  15648. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15649. glTextureFromLod.height = glTextureFromLod.width;
  15650. glTextureFromLod.isCube = true;
  15651. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15652. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15653. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15654. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15655. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15656. if (loadData.isDDS) {
  15657. var info = loadData.info;
  15658. var data = loadData.data;
  15659. _this._unpackFlipY(info.isCompressed);
  15660. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15661. }
  15662. else {
  15663. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15664. }
  15665. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15666. // Wrap in a base texture for easy binding.
  15667. var lodTexture = new BABYLON.BaseTexture(scene);
  15668. lodTexture.isCube = true;
  15669. lodTexture._texture = glTextureFromLod;
  15670. glTextureFromLod.isReady = true;
  15671. textures.push(lodTexture);
  15672. }
  15673. texture._lodTextureHigh = textures[2];
  15674. texture._lodTextureMid = textures[1];
  15675. texture._lodTextureLow = textures[0];
  15676. if (onLoad) {
  15677. onLoad(texture);
  15678. }
  15679. };
  15680. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15681. };
  15682. /**
  15683. * Creates a cube texture
  15684. * @param rootUrl defines the url where the files to load is located
  15685. * @param scene defines the current scene
  15686. * @param files defines the list of files to load (1 per face)
  15687. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15688. * @param onLoad defines an optional callback raised when the texture is loaded
  15689. * @param onError defines an optional callback raised if there is an issue to load the texture
  15690. * @param format defines the format of the data
  15691. * @param forcedExtension defines the extension to use to pick the right loader
  15692. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15693. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15694. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15695. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15696. * @returns the cube texture as an InternalTexture
  15697. */
  15698. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15699. var _this = this;
  15700. if (onLoad === void 0) { onLoad = null; }
  15701. if (onError === void 0) { onError = null; }
  15702. if (forcedExtension === void 0) { forcedExtension = null; }
  15703. if (createPolynomials === void 0) { createPolynomials = false; }
  15704. if (lodScale === void 0) { lodScale = 0; }
  15705. if (lodOffset === void 0) { lodOffset = 0; }
  15706. if (fallback === void 0) { fallback = null; }
  15707. var gl = this._gl;
  15708. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15709. texture.isCube = true;
  15710. texture.url = rootUrl;
  15711. texture.generateMipMaps = !noMipmap;
  15712. texture._lodGenerationScale = lodScale;
  15713. texture._lodGenerationOffset = lodOffset;
  15714. if (!this._doNotHandleContextLost) {
  15715. texture._extension = forcedExtension;
  15716. texture._files = files;
  15717. }
  15718. var lastDot = rootUrl.lastIndexOf('.');
  15719. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15720. var loader = null;
  15721. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15722. var availableLoader = _a[_i];
  15723. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15724. loader = availableLoader;
  15725. break;
  15726. }
  15727. }
  15728. var onInternalError = function (request, exception) {
  15729. if (loader) {
  15730. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15731. if (fallbackUrl) {
  15732. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15733. }
  15734. }
  15735. if (onError && request) {
  15736. onError(request.status + " " + request.statusText, exception);
  15737. }
  15738. };
  15739. if (loader) {
  15740. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15741. var onloaddata = function (data) {
  15742. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15743. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15744. };
  15745. if (files && files.length === 6) {
  15746. if (loader.supportCascades) {
  15747. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15748. }
  15749. else if (onError) {
  15750. onError("Textures type does not support cascades.");
  15751. }
  15752. }
  15753. else {
  15754. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15755. }
  15756. }
  15757. else {
  15758. if (!files) {
  15759. throw new Error("Cannot load cubemap because files were not defined");
  15760. }
  15761. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15762. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15763. var height = width;
  15764. _this._prepareWorkingCanvas();
  15765. if (!_this._workingCanvas || !_this._workingContext) {
  15766. return;
  15767. }
  15768. _this._workingCanvas.width = width;
  15769. _this._workingCanvas.height = height;
  15770. var faces = [
  15771. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15772. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15773. ];
  15774. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15775. _this._unpackFlipY(false);
  15776. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15777. for (var index = 0; index < faces.length; index++) {
  15778. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15779. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15780. }
  15781. if (!noMipmap) {
  15782. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15783. }
  15784. _this._setCubeMapTextureParams(!noMipmap);
  15785. texture.width = width;
  15786. texture.height = height;
  15787. texture.isReady = true;
  15788. if (format) {
  15789. texture.format = format;
  15790. }
  15791. texture.onLoadedObservable.notifyObservers(texture);
  15792. texture.onLoadedObservable.clear();
  15793. if (onLoad) {
  15794. onLoad();
  15795. }
  15796. }, files, onError);
  15797. }
  15798. this._internalTexturesCache.push(texture);
  15799. return texture;
  15800. };
  15801. /**
  15802. * @hidden
  15803. */
  15804. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15805. var gl = this._gl;
  15806. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15807. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15808. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15809. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15810. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15811. // this.resetTextureCache();
  15812. };
  15813. /**
  15814. * Update a raw cube texture
  15815. * @param texture defines the texture to udpdate
  15816. * @param data defines the data to store
  15817. * @param format defines the data format
  15818. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15819. * @param invertY defines if data must be stored with Y axis inverted
  15820. * @param compression defines the compression used (null by default)
  15821. * @param level defines which level of the texture to update
  15822. */
  15823. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15824. if (compression === void 0) { compression = null; }
  15825. if (level === void 0) { level = 0; }
  15826. texture._bufferViewArray = data;
  15827. texture.format = format;
  15828. texture.type = type;
  15829. texture.invertY = invertY;
  15830. texture._compression = compression;
  15831. var gl = this._gl;
  15832. var textureType = this._getWebGLTextureType(type);
  15833. var internalFormat = this._getInternalFormat(format);
  15834. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15835. var needConversion = false;
  15836. if (internalFormat === gl.RGB) {
  15837. internalFormat = gl.RGBA;
  15838. needConversion = true;
  15839. }
  15840. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15841. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15842. if (texture.width % 4 !== 0) {
  15843. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15844. }
  15845. // Data are known to be in +X +Y +Z -X -Y -Z
  15846. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15847. var faceData = data[faceIndex];
  15848. if (compression) {
  15849. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15850. }
  15851. else {
  15852. if (needConversion) {
  15853. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15854. }
  15855. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15856. }
  15857. }
  15858. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15859. if (isPot && texture.generateMipMaps && level === 0) {
  15860. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15861. }
  15862. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15863. // this.resetTextureCache();
  15864. texture.isReady = true;
  15865. };
  15866. /**
  15867. * Creates a new raw cube texture
  15868. * @param data defines the array of data to use to create each face
  15869. * @param size defines the size of the textures
  15870. * @param format defines the format of the data
  15871. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15872. * @param generateMipMaps defines if the engine should generate the mip levels
  15873. * @param invertY defines if data must be stored with Y axis inverted
  15874. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15875. * @param compression defines the compression used (null by default)
  15876. * @returns the cube texture as an InternalTexture
  15877. */
  15878. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15879. if (compression === void 0) { compression = null; }
  15880. var gl = this._gl;
  15881. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15882. texture.isCube = true;
  15883. texture.format = format;
  15884. texture.type = type;
  15885. if (!this._doNotHandleContextLost) {
  15886. texture._bufferViewArray = data;
  15887. }
  15888. var textureType = this._getWebGLTextureType(type);
  15889. var internalFormat = this._getInternalFormat(format);
  15890. if (internalFormat === gl.RGB) {
  15891. internalFormat = gl.RGBA;
  15892. }
  15893. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15894. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15895. generateMipMaps = false;
  15896. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15897. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15898. }
  15899. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15900. generateMipMaps = false;
  15901. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15902. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15903. }
  15904. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15905. generateMipMaps = false;
  15906. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15907. }
  15908. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15909. generateMipMaps = false;
  15910. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15911. }
  15912. var width = size;
  15913. var height = width;
  15914. texture.width = width;
  15915. texture.height = height;
  15916. // Double check on POT to generate Mips.
  15917. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15918. if (!isPot) {
  15919. generateMipMaps = false;
  15920. }
  15921. // Upload data if needed. The texture won't be ready until then.
  15922. if (data) {
  15923. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15924. }
  15925. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15926. // Filters
  15927. if (data && generateMipMaps) {
  15928. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15929. }
  15930. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15931. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15932. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15933. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15934. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15935. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15936. texture.generateMipMaps = generateMipMaps;
  15937. return texture;
  15938. };
  15939. /**
  15940. * Creates a new raw cube texture from a specified url
  15941. * @param url defines the url where the data is located
  15942. * @param scene defines the current scene
  15943. * @param size defines the size of the textures
  15944. * @param format defines the format of the data
  15945. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15946. * @param noMipmap defines if the engine should avoid generating the mip levels
  15947. * @param callback defines a callback used to extract texture data from loaded data
  15948. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15949. * @param onLoad defines a callback called when texture is loaded
  15950. * @param onError defines a callback called if there is an error
  15951. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15952. * @param invertY defines if data must be stored with Y axis inverted
  15953. * @returns the cube texture as an InternalTexture
  15954. */
  15955. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15956. var _this = this;
  15957. if (onLoad === void 0) { onLoad = null; }
  15958. if (onError === void 0) { onError = null; }
  15959. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15960. if (invertY === void 0) { invertY = false; }
  15961. var gl = this._gl;
  15962. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15963. scene._addPendingData(texture);
  15964. texture.url = url;
  15965. this._internalTexturesCache.push(texture);
  15966. var onerror = function (request, exception) {
  15967. scene._removePendingData(texture);
  15968. if (onError && request) {
  15969. onError(request.status + " " + request.statusText, exception);
  15970. }
  15971. };
  15972. var internalCallback = function (data) {
  15973. var width = texture.width;
  15974. var faceDataArrays = callback(data);
  15975. if (!faceDataArrays) {
  15976. return;
  15977. }
  15978. if (mipmapGenerator) {
  15979. var textureType = _this._getWebGLTextureType(type);
  15980. var internalFormat = _this._getInternalFormat(format);
  15981. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15982. var needConversion = false;
  15983. if (internalFormat === gl.RGB) {
  15984. internalFormat = gl.RGBA;
  15985. needConversion = true;
  15986. }
  15987. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15988. _this._unpackFlipY(false);
  15989. var mipData = mipmapGenerator(faceDataArrays);
  15990. for (var level = 0; level < mipData.length; level++) {
  15991. var mipSize = width >> level;
  15992. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15993. var mipFaceData = mipData[level][faceIndex];
  15994. if (needConversion) {
  15995. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15996. }
  15997. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15998. }
  15999. }
  16000. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16001. }
  16002. else {
  16003. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16004. }
  16005. texture.isReady = true;
  16006. // this.resetTextureCache();
  16007. scene._removePendingData(texture);
  16008. if (onLoad) {
  16009. onLoad();
  16010. }
  16011. };
  16012. this._loadFile(url, function (data) {
  16013. internalCallback(data);
  16014. }, undefined, scene.database, true, onerror);
  16015. return texture;
  16016. };
  16017. ;
  16018. /**
  16019. * Update a raw 3D texture
  16020. * @param texture defines the texture to update
  16021. * @param data defines the data to store
  16022. * @param format defines the data format
  16023. * @param invertY defines if data must be stored with Y axis inverted
  16024. * @param compression defines the used compression (can be null)
  16025. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16026. */
  16027. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16028. if (compression === void 0) { compression = null; }
  16029. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16030. var internalType = this._getWebGLTextureType(textureType);
  16031. var internalFormat = this._getInternalFormat(format);
  16032. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16033. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16034. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16035. if (!this._doNotHandleContextLost) {
  16036. texture._bufferView = data;
  16037. texture.format = format;
  16038. texture.invertY = invertY;
  16039. texture._compression = compression;
  16040. }
  16041. if (texture.width % 4 !== 0) {
  16042. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16043. }
  16044. if (compression && data) {
  16045. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16046. }
  16047. else {
  16048. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16049. }
  16050. if (texture.generateMipMaps) {
  16051. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16052. }
  16053. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16054. // this.resetTextureCache();
  16055. texture.isReady = true;
  16056. };
  16057. /**
  16058. * Creates a new raw 3D texture
  16059. * @param data defines the data used to create the texture
  16060. * @param width defines the width of the texture
  16061. * @param height defines the height of the texture
  16062. * @param depth defines the depth of the texture
  16063. * @param format defines the format of the texture
  16064. * @param generateMipMaps defines if the engine must generate mip levels
  16065. * @param invertY defines if data must be stored with Y axis inverted
  16066. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16067. * @param compression defines the compressed used (can be null)
  16068. * @param textureType defines the compressed used (can be null)
  16069. * @returns a new raw 3D texture (stored in an InternalTexture)
  16070. */
  16071. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16072. if (compression === void 0) { compression = null; }
  16073. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16074. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16075. texture.baseWidth = width;
  16076. texture.baseHeight = height;
  16077. texture.baseDepth = depth;
  16078. texture.width = width;
  16079. texture.height = height;
  16080. texture.depth = depth;
  16081. texture.format = format;
  16082. texture.type = textureType;
  16083. texture.generateMipMaps = generateMipMaps;
  16084. texture.samplingMode = samplingMode;
  16085. texture.is3D = true;
  16086. if (!this._doNotHandleContextLost) {
  16087. texture._bufferView = data;
  16088. }
  16089. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16090. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16091. // Filters
  16092. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16093. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16094. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16095. if (generateMipMaps) {
  16096. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16097. }
  16098. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16099. this._internalTexturesCache.push(texture);
  16100. return texture;
  16101. };
  16102. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16103. var gl = this._gl;
  16104. if (!gl) {
  16105. return;
  16106. }
  16107. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16108. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16109. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16110. if (!noMipmap && !isCompressed) {
  16111. gl.generateMipmap(gl.TEXTURE_2D);
  16112. }
  16113. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16114. // this.resetTextureCache();
  16115. if (scene) {
  16116. scene._removePendingData(texture);
  16117. }
  16118. texture.onLoadedObservable.notifyObservers(texture);
  16119. texture.onLoadedObservable.clear();
  16120. };
  16121. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16122. var _this = this;
  16123. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16124. var maxTextureSize = this.getCaps().maxTextureSize;
  16125. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16126. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16127. var gl = this._gl;
  16128. if (!gl) {
  16129. return;
  16130. }
  16131. if (!texture._webGLTexture) {
  16132. // this.resetTextureCache();
  16133. if (scene) {
  16134. scene._removePendingData(texture);
  16135. }
  16136. return;
  16137. }
  16138. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16139. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16140. texture.baseWidth = width;
  16141. texture.baseHeight = height;
  16142. texture.width = potWidth;
  16143. texture.height = potHeight;
  16144. texture.isReady = true;
  16145. if (processFunction(potWidth, potHeight, function () {
  16146. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16147. })) {
  16148. // Returning as texture needs extra async steps
  16149. return;
  16150. }
  16151. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16152. };
  16153. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16154. // Create new RGBA data container.
  16155. var rgbaData;
  16156. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16157. rgbaData = new Float32Array(width * height * 4);
  16158. }
  16159. else {
  16160. rgbaData = new Uint32Array(width * height * 4);
  16161. }
  16162. // Convert each pixel.
  16163. for (var x = 0; x < width; x++) {
  16164. for (var y = 0; y < height; y++) {
  16165. var index = (y * width + x) * 3;
  16166. var newIndex = (y * width + x) * 4;
  16167. // Map Old Value to new value.
  16168. rgbaData[newIndex + 0] = rgbData[index + 0];
  16169. rgbaData[newIndex + 1] = rgbData[index + 1];
  16170. rgbaData[newIndex + 2] = rgbData[index + 2];
  16171. // Add fully opaque alpha channel.
  16172. rgbaData[newIndex + 3] = 1;
  16173. }
  16174. }
  16175. return rgbaData;
  16176. };
  16177. /** @hidden */
  16178. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16179. var gl = this._gl;
  16180. if (texture._framebuffer) {
  16181. gl.deleteFramebuffer(texture._framebuffer);
  16182. texture._framebuffer = null;
  16183. }
  16184. if (texture._depthStencilBuffer) {
  16185. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16186. texture._depthStencilBuffer = null;
  16187. }
  16188. if (texture._MSAAFramebuffer) {
  16189. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16190. texture._MSAAFramebuffer = null;
  16191. }
  16192. if (texture._MSAARenderBuffer) {
  16193. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16194. texture._MSAARenderBuffer = null;
  16195. }
  16196. };
  16197. /** @hidden */
  16198. Engine.prototype._releaseTexture = function (texture) {
  16199. var gl = this._gl;
  16200. this._releaseFramebufferObjects(texture);
  16201. gl.deleteTexture(texture._webGLTexture);
  16202. // Unbind channels
  16203. this.unbindAllTextures();
  16204. var index = this._internalTexturesCache.indexOf(texture);
  16205. if (index !== -1) {
  16206. this._internalTexturesCache.splice(index, 1);
  16207. }
  16208. // Integrated fixed lod samplers.
  16209. if (texture._lodTextureHigh) {
  16210. texture._lodTextureHigh.dispose();
  16211. }
  16212. if (texture._lodTextureMid) {
  16213. texture._lodTextureMid.dispose();
  16214. }
  16215. if (texture._lodTextureLow) {
  16216. texture._lodTextureLow.dispose();
  16217. }
  16218. // Set output texture of post process to null if the texture has been released/disposed
  16219. this.scenes.forEach(function (scene) {
  16220. scene.postProcesses.forEach(function (postProcess) {
  16221. if (postProcess._outputTexture == texture) {
  16222. postProcess._outputTexture = null;
  16223. }
  16224. });
  16225. scene.cameras.forEach(function (camera) {
  16226. camera._postProcesses.forEach(function (postProcess) {
  16227. if (postProcess) {
  16228. if (postProcess._outputTexture == texture) {
  16229. postProcess._outputTexture = null;
  16230. }
  16231. }
  16232. });
  16233. });
  16234. });
  16235. };
  16236. Engine.prototype.setProgram = function (program) {
  16237. if (this._currentProgram !== program) {
  16238. this._gl.useProgram(program);
  16239. this._currentProgram = program;
  16240. }
  16241. };
  16242. /**
  16243. * Binds an effect to the webGL context
  16244. * @param effect defines the effect to bind
  16245. */
  16246. Engine.prototype.bindSamplers = function (effect) {
  16247. this.setProgram(effect.getProgram());
  16248. var samplers = effect.getSamplers();
  16249. for (var index = 0; index < samplers.length; index++) {
  16250. var uniform = effect.getUniform(samplers[index]);
  16251. if (uniform) {
  16252. this._boundUniforms[index] = uniform;
  16253. }
  16254. }
  16255. this._currentEffect = null;
  16256. };
  16257. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16258. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16259. return;
  16260. }
  16261. // Remove
  16262. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16263. // Bind last to it
  16264. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16265. // Bind to dummy
  16266. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16267. };
  16268. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16269. if (!internalTexture) {
  16270. return -1;
  16271. }
  16272. internalTexture._initialSlot = channel;
  16273. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16274. if (channel !== internalTexture._designatedSlot) {
  16275. this._textureCollisions.addCount(1, false);
  16276. }
  16277. }
  16278. else {
  16279. if (channel !== internalTexture._designatedSlot) {
  16280. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16281. return internalTexture._designatedSlot;
  16282. }
  16283. else {
  16284. // No slot for this texture, let's pick a new one (if we find a free slot)
  16285. if (this._nextFreeTextureSlots.length) {
  16286. return this._nextFreeTextureSlots[0];
  16287. }
  16288. // We need to recycle the oldest bound texture, sorry.
  16289. this._textureCollisions.addCount(1, false);
  16290. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16291. }
  16292. }
  16293. }
  16294. return channel;
  16295. };
  16296. Engine.prototype._linkTrackers = function (previous, next) {
  16297. previous.next = next;
  16298. next.previous = previous;
  16299. };
  16300. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16301. var currentSlot = internalTexture._designatedSlot;
  16302. if (currentSlot === -1) {
  16303. return -1;
  16304. }
  16305. internalTexture._designatedSlot = -1;
  16306. if (this.disableTextureBindingOptimization) {
  16307. return -1;
  16308. }
  16309. // Remove from bound list
  16310. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16311. // Free the slot
  16312. this._boundTexturesCache[currentSlot] = null;
  16313. this._nextFreeTextureSlots.push(currentSlot);
  16314. return currentSlot;
  16315. };
  16316. Engine.prototype._activateCurrentTexture = function () {
  16317. if (this._currentTextureChannel !== this._activeChannel) {
  16318. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16319. this._currentTextureChannel = this._activeChannel;
  16320. }
  16321. };
  16322. /** @hidden */
  16323. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16324. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16325. if (force === void 0) { force = false; }
  16326. var wasPreviouslyBound = false;
  16327. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16328. this._activeChannel = texture._designatedSlot;
  16329. }
  16330. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16331. var isTextureForRendering = texture && texture._initialSlot > -1;
  16332. if (currentTextureBound !== texture || force) {
  16333. if (currentTextureBound) {
  16334. this._removeDesignatedSlot(currentTextureBound);
  16335. }
  16336. this._activateCurrentTexture();
  16337. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16338. this._boundTexturesCache[this._activeChannel] = texture;
  16339. if (texture) {
  16340. if (!this.disableTextureBindingOptimization) {
  16341. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16342. if (slotIndex > -1) {
  16343. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16344. }
  16345. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16346. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16347. }
  16348. texture._designatedSlot = this._activeChannel;
  16349. }
  16350. }
  16351. else if (forTextureDataUpdate) {
  16352. wasPreviouslyBound = true;
  16353. this._activateCurrentTexture();
  16354. }
  16355. if (isTextureForRendering && !forTextureDataUpdate) {
  16356. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16357. }
  16358. return wasPreviouslyBound;
  16359. };
  16360. /** @hidden */
  16361. Engine.prototype._bindTexture = function (channel, texture) {
  16362. if (channel < 0) {
  16363. return;
  16364. }
  16365. if (texture) {
  16366. channel = this._getCorrectTextureChannel(channel, texture);
  16367. }
  16368. this._activeChannel = channel;
  16369. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16370. };
  16371. /**
  16372. * Sets a texture to the webGL context from a postprocess
  16373. * @param channel defines the channel to use
  16374. * @param postProcess defines the source postprocess
  16375. */
  16376. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16377. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16378. };
  16379. /**
  16380. * Binds the output of the passed in post process to the texture channel specified
  16381. * @param channel The channel the texture should be bound to
  16382. * @param postProcess The post process which's output should be bound
  16383. */
  16384. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16385. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16386. };
  16387. /**
  16388. * Unbind all textures from the webGL context
  16389. */
  16390. Engine.prototype.unbindAllTextures = function () {
  16391. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16392. this._activeChannel = channel;
  16393. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16394. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16395. if (this.webGLVersion > 1) {
  16396. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16397. }
  16398. }
  16399. };
  16400. /**
  16401. * Sets a texture to the according uniform.
  16402. * @param channel The texture channel
  16403. * @param uniform The uniform to set
  16404. * @param texture The texture to apply
  16405. */
  16406. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16407. if (channel < 0) {
  16408. return;
  16409. }
  16410. if (uniform) {
  16411. this._boundUniforms[channel] = uniform;
  16412. }
  16413. this._setTexture(channel, texture);
  16414. };
  16415. /**
  16416. * Sets a depth stencil texture from a render target to the according uniform.
  16417. * @param channel The texture channel
  16418. * @param uniform The uniform to set
  16419. * @param texture The render target texture containing the depth stencil texture to apply
  16420. */
  16421. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16422. if (channel < 0) {
  16423. return;
  16424. }
  16425. if (uniform) {
  16426. this._boundUniforms[channel] = uniform;
  16427. }
  16428. if (!texture || !texture.depthStencilTexture) {
  16429. this._setTexture(channel, null);
  16430. }
  16431. else {
  16432. this._setTexture(channel, texture, false, true);
  16433. }
  16434. };
  16435. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16436. var uniform = this._boundUniforms[sourceSlot];
  16437. if (uniform._currentState === destination) {
  16438. return;
  16439. }
  16440. this._gl.uniform1i(uniform, destination);
  16441. uniform._currentState = destination;
  16442. };
  16443. Engine.prototype._getTextureWrapMode = function (mode) {
  16444. switch (mode) {
  16445. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16446. return this._gl.REPEAT;
  16447. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16448. return this._gl.CLAMP_TO_EDGE;
  16449. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16450. return this._gl.MIRRORED_REPEAT;
  16451. }
  16452. return this._gl.REPEAT;
  16453. };
  16454. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16455. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16456. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16457. // Not ready?
  16458. if (!texture) {
  16459. if (this._boundTexturesCache[channel] != null) {
  16460. this._activeChannel = channel;
  16461. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16462. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16463. if (this.webGLVersion > 1) {
  16464. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16465. }
  16466. }
  16467. return false;
  16468. }
  16469. // Video
  16470. if (texture.video) {
  16471. this._activeChannel = channel;
  16472. texture.update();
  16473. }
  16474. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16475. texture.delayLoad();
  16476. return false;
  16477. }
  16478. var internalTexture;
  16479. if (depthStencilTexture) {
  16480. internalTexture = texture.depthStencilTexture;
  16481. }
  16482. else if (texture.isReady()) {
  16483. internalTexture = texture.getInternalTexture();
  16484. }
  16485. else if (texture.isCube) {
  16486. internalTexture = this.emptyCubeTexture;
  16487. }
  16488. else if (texture.is3D) {
  16489. internalTexture = this.emptyTexture3D;
  16490. }
  16491. else {
  16492. internalTexture = this.emptyTexture;
  16493. }
  16494. if (!isPartOfTextureArray) {
  16495. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16496. }
  16497. var needToBind = true;
  16498. if (this._boundTexturesCache[channel] === internalTexture) {
  16499. this._moveBoundTextureOnTop(internalTexture);
  16500. if (!isPartOfTextureArray) {
  16501. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16502. }
  16503. needToBind = false;
  16504. }
  16505. this._activeChannel = channel;
  16506. if (internalTexture && internalTexture.is3D) {
  16507. if (needToBind) {
  16508. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16509. }
  16510. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16511. internalTexture._cachedWrapU = texture.wrapU;
  16512. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16513. }
  16514. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16515. internalTexture._cachedWrapV = texture.wrapV;
  16516. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16517. }
  16518. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16519. internalTexture._cachedWrapR = texture.wrapR;
  16520. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16521. }
  16522. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16523. }
  16524. else if (internalTexture && internalTexture.isCube) {
  16525. if (needToBind) {
  16526. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16527. }
  16528. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16529. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16530. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16531. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16532. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16533. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16534. }
  16535. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16536. }
  16537. else {
  16538. if (needToBind) {
  16539. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16540. }
  16541. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16542. internalTexture._cachedWrapU = texture.wrapU;
  16543. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16544. }
  16545. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16546. internalTexture._cachedWrapV = texture.wrapV;
  16547. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16548. }
  16549. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16550. }
  16551. return true;
  16552. };
  16553. /**
  16554. * Sets an array of texture to the webGL context
  16555. * @param channel defines the channel where the texture array must be set
  16556. * @param uniform defines the associated uniform location
  16557. * @param textures defines the array of textures to bind
  16558. */
  16559. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16560. if (channel < 0 || !uniform) {
  16561. return;
  16562. }
  16563. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16564. this._textureUnits = new Int32Array(textures.length);
  16565. }
  16566. for (var i = 0; i < textures.length; i++) {
  16567. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16568. }
  16569. this._gl.uniform1iv(uniform, this._textureUnits);
  16570. for (var index = 0; index < textures.length; index++) {
  16571. this._setTexture(this._textureUnits[index], textures[index], true);
  16572. }
  16573. };
  16574. /** @hidden */
  16575. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16576. var internalTexture = texture.getInternalTexture();
  16577. if (!internalTexture) {
  16578. return;
  16579. }
  16580. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16581. var value = texture.anisotropicFilteringLevel;
  16582. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16583. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16584. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16585. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16586. }
  16587. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16588. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16589. internalTexture._cachedAnisotropicFilteringLevel = value;
  16590. }
  16591. };
  16592. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16593. this._bindTextureDirectly(target, texture, true, true);
  16594. this._gl.texParameterf(target, parameter, value);
  16595. };
  16596. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16597. if (texture) {
  16598. this._bindTextureDirectly(target, texture, true, true);
  16599. }
  16600. this._gl.texParameteri(target, parameter, value);
  16601. };
  16602. /**
  16603. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16604. * @param x defines the x coordinate of the rectangle where pixels must be read
  16605. * @param y defines the y coordinate of the rectangle where pixels must be read
  16606. * @param width defines the width of the rectangle where pixels must be read
  16607. * @param height defines the height of the rectangle where pixels must be read
  16608. * @returns a Uint8Array containing RGBA colors
  16609. */
  16610. Engine.prototype.readPixels = function (x, y, width, height) {
  16611. var data = new Uint8Array(height * width * 4);
  16612. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16613. return data;
  16614. };
  16615. /**
  16616. * Add an externaly attached data from its key.
  16617. * This method call will fail and return false, if such key already exists.
  16618. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16619. * @param key the unique key that identifies the data
  16620. * @param data the data object to associate to the key for this Engine instance
  16621. * @return true if no such key were already present and the data was added successfully, false otherwise
  16622. */
  16623. Engine.prototype.addExternalData = function (key, data) {
  16624. if (!this._externalData) {
  16625. this._externalData = new BABYLON.StringDictionary();
  16626. }
  16627. return this._externalData.add(key, data);
  16628. };
  16629. /**
  16630. * Get an externaly attached data from its key
  16631. * @param key the unique key that identifies the data
  16632. * @return the associated data, if present (can be null), or undefined if not present
  16633. */
  16634. Engine.prototype.getExternalData = function (key) {
  16635. if (!this._externalData) {
  16636. this._externalData = new BABYLON.StringDictionary();
  16637. }
  16638. return this._externalData.get(key);
  16639. };
  16640. /**
  16641. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16642. * @param key the unique key that identifies the data
  16643. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16644. * @return the associated data, can be null if the factory returned null.
  16645. */
  16646. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16647. if (!this._externalData) {
  16648. this._externalData = new BABYLON.StringDictionary();
  16649. }
  16650. return this._externalData.getOrAddWithFactory(key, factory);
  16651. };
  16652. /**
  16653. * Remove an externaly attached data from the Engine instance
  16654. * @param key the unique key that identifies the data
  16655. * @return true if the data was successfully removed, false if it doesn't exist
  16656. */
  16657. Engine.prototype.removeExternalData = function (key) {
  16658. if (!this._externalData) {
  16659. this._externalData = new BABYLON.StringDictionary();
  16660. }
  16661. return this._externalData.remove(key);
  16662. };
  16663. /**
  16664. * Unbind all vertex attributes from the webGL context
  16665. */
  16666. Engine.prototype.unbindAllAttributes = function () {
  16667. if (this._mustWipeVertexAttributes) {
  16668. this._mustWipeVertexAttributes = false;
  16669. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16670. this._gl.disableVertexAttribArray(i);
  16671. this._vertexAttribArraysEnabled[i] = false;
  16672. this._currentBufferPointers[i].active = false;
  16673. }
  16674. return;
  16675. }
  16676. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16677. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16678. continue;
  16679. }
  16680. this._gl.disableVertexAttribArray(i);
  16681. this._vertexAttribArraysEnabled[i] = false;
  16682. this._currentBufferPointers[i].active = false;
  16683. }
  16684. };
  16685. /**
  16686. * 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
  16687. */
  16688. Engine.prototype.releaseEffects = function () {
  16689. for (var name in this._compiledEffects) {
  16690. this._deleteProgram(this._compiledEffects[name]._program);
  16691. }
  16692. this._compiledEffects = {};
  16693. };
  16694. /**
  16695. * Dispose and release all associated resources
  16696. */
  16697. Engine.prototype.dispose = function () {
  16698. this.hideLoadingUI();
  16699. this.stopRenderLoop();
  16700. // Release postProcesses
  16701. while (this.postProcesses.length) {
  16702. this.postProcesses[0].dispose();
  16703. }
  16704. // Empty texture
  16705. if (this._emptyTexture) {
  16706. this._releaseTexture(this._emptyTexture);
  16707. this._emptyTexture = null;
  16708. }
  16709. if (this._emptyCubeTexture) {
  16710. this._releaseTexture(this._emptyCubeTexture);
  16711. this._emptyCubeTexture = null;
  16712. }
  16713. // Rescale PP
  16714. if (this._rescalePostProcess) {
  16715. this._rescalePostProcess.dispose();
  16716. }
  16717. // Release scenes
  16718. while (this.scenes.length) {
  16719. this.scenes[0].dispose();
  16720. }
  16721. // Release audio engine
  16722. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  16723. Engine.audioEngine.dispose();
  16724. }
  16725. // Release effects
  16726. this.releaseEffects();
  16727. // Unbind
  16728. this.unbindAllAttributes();
  16729. this._boundUniforms = [];
  16730. if (this._dummyFramebuffer) {
  16731. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16732. }
  16733. //WebVR
  16734. this.disableVR();
  16735. // Events
  16736. if (BABYLON.Tools.IsWindowObjectExist()) {
  16737. window.removeEventListener("blur", this._onBlur);
  16738. window.removeEventListener("focus", this._onFocus);
  16739. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16740. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16741. if (this._renderingCanvas) {
  16742. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16743. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16744. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16745. if (!this._doNotHandleContextLost) {
  16746. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16747. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16748. }
  16749. }
  16750. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16751. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16752. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16753. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16754. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16755. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16756. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16757. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16758. if (this._onVrDisplayConnect) {
  16759. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16760. if (this._onVrDisplayDisconnect) {
  16761. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16762. }
  16763. if (this._onVrDisplayPresentChange) {
  16764. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16765. }
  16766. this._onVrDisplayConnect = null;
  16767. this._onVrDisplayDisconnect = null;
  16768. }
  16769. }
  16770. // Remove from Instances
  16771. var index = Engine.Instances.indexOf(this);
  16772. if (index >= 0) {
  16773. Engine.Instances.splice(index, 1);
  16774. }
  16775. this._workingCanvas = null;
  16776. this._workingContext = null;
  16777. this._currentBufferPointers = [];
  16778. this._renderingCanvas = null;
  16779. this._currentProgram = null;
  16780. this._bindedRenderFunction = null;
  16781. this.onResizeObservable.clear();
  16782. this.onCanvasBlurObservable.clear();
  16783. this.onCanvasFocusObservable.clear();
  16784. this.onCanvasPointerOutObservable.clear();
  16785. this.onBeginFrameObservable.clear();
  16786. this.onEndFrameObservable.clear();
  16787. BABYLON.Effect.ResetCache();
  16788. // Abort active requests
  16789. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16790. var request = _a[_i];
  16791. request.abort();
  16792. }
  16793. };
  16794. // Loading screen
  16795. /**
  16796. * Display the loading screen
  16797. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16798. */
  16799. Engine.prototype.displayLoadingUI = function () {
  16800. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16801. return;
  16802. }
  16803. var loadingScreen = this.loadingScreen;
  16804. if (loadingScreen) {
  16805. loadingScreen.displayLoadingUI();
  16806. }
  16807. };
  16808. /**
  16809. * Hide the loading screen
  16810. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16811. */
  16812. Engine.prototype.hideLoadingUI = function () {
  16813. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16814. return;
  16815. }
  16816. var loadingScreen = this.loadingScreen;
  16817. if (loadingScreen) {
  16818. loadingScreen.hideLoadingUI();
  16819. }
  16820. };
  16821. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16822. /**
  16823. * Gets the current loading screen object
  16824. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16825. */
  16826. get: function () {
  16827. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16828. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16829. return this._loadingScreen;
  16830. },
  16831. /**
  16832. * Sets the current loading screen object
  16833. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16834. */
  16835. set: function (loadingScreen) {
  16836. this._loadingScreen = loadingScreen;
  16837. },
  16838. enumerable: true,
  16839. configurable: true
  16840. });
  16841. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16842. /**
  16843. * Sets the current loading screen text
  16844. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16845. */
  16846. set: function (text) {
  16847. this.loadingScreen.loadingUIText = text;
  16848. },
  16849. enumerable: true,
  16850. configurable: true
  16851. });
  16852. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16853. /**
  16854. * Sets the current loading screen background color
  16855. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16856. */
  16857. set: function (color) {
  16858. this.loadingScreen.loadingUIBackgroundColor = color;
  16859. },
  16860. enumerable: true,
  16861. configurable: true
  16862. });
  16863. /**
  16864. * Attach a new callback raised when context lost event is fired
  16865. * @param callback defines the callback to call
  16866. */
  16867. Engine.prototype.attachContextLostEvent = function (callback) {
  16868. if (this._renderingCanvas) {
  16869. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16870. }
  16871. };
  16872. /**
  16873. * Attach a new callback raised when context restored event is fired
  16874. * @param callback defines the callback to call
  16875. */
  16876. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16877. if (this._renderingCanvas) {
  16878. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16879. }
  16880. };
  16881. /**
  16882. * Gets the source code of the vertex shader associated with a specific webGL program
  16883. * @param program defines the program to use
  16884. * @returns a string containing the source code of the vertex shader associated with the program
  16885. */
  16886. Engine.prototype.getVertexShaderSource = function (program) {
  16887. var shaders = this._gl.getAttachedShaders(program);
  16888. if (!shaders) {
  16889. return null;
  16890. }
  16891. return this._gl.getShaderSource(shaders[0]);
  16892. };
  16893. /**
  16894. * Gets the source code of the fragment shader associated with a specific webGL program
  16895. * @param program defines the program to use
  16896. * @returns a string containing the source code of the fragment shader associated with the program
  16897. */
  16898. Engine.prototype.getFragmentShaderSource = function (program) {
  16899. var shaders = this._gl.getAttachedShaders(program);
  16900. if (!shaders) {
  16901. return null;
  16902. }
  16903. return this._gl.getShaderSource(shaders[1]);
  16904. };
  16905. /**
  16906. * Get the current error code of the webGL context
  16907. * @returns the error code
  16908. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16909. */
  16910. Engine.prototype.getError = function () {
  16911. return this._gl.getError();
  16912. };
  16913. // FPS
  16914. /**
  16915. * Gets the current framerate
  16916. * @returns a number representing the framerate
  16917. */
  16918. Engine.prototype.getFps = function () {
  16919. return this._fps;
  16920. };
  16921. /**
  16922. * Gets the time spent between current and previous frame
  16923. * @returns a number representing the delta time in ms
  16924. */
  16925. Engine.prototype.getDeltaTime = function () {
  16926. return this._deltaTime;
  16927. };
  16928. Engine.prototype._measureFps = function () {
  16929. this._performanceMonitor.sampleFrame();
  16930. this._fps = this._performanceMonitor.averageFPS;
  16931. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16932. };
  16933. /** @hidden */
  16934. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  16935. if (faceIndex === void 0) { faceIndex = -1; }
  16936. if (level === void 0) { level = 0; }
  16937. if (buffer === void 0) { buffer = null; }
  16938. var gl = this._gl;
  16939. if (!this._dummyFramebuffer) {
  16940. var dummy = gl.createFramebuffer();
  16941. if (!dummy) {
  16942. throw new Error("Unable to create dummy framebuffer");
  16943. }
  16944. this._dummyFramebuffer = dummy;
  16945. }
  16946. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16947. if (faceIndex > -1) {
  16948. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16949. }
  16950. else {
  16951. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16952. }
  16953. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16954. switch (readType) {
  16955. case gl.UNSIGNED_BYTE:
  16956. if (!buffer) {
  16957. buffer = new Uint8Array(4 * width * height);
  16958. }
  16959. readType = gl.UNSIGNED_BYTE;
  16960. break;
  16961. default:
  16962. if (!buffer) {
  16963. buffer = new Float32Array(4 * width * height);
  16964. }
  16965. readType = gl.FLOAT;
  16966. break;
  16967. }
  16968. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16969. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16970. return buffer;
  16971. };
  16972. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16973. if (this._webGLVersion > 1) {
  16974. return this._caps.colorBufferFloat;
  16975. }
  16976. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16977. };
  16978. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16979. if (this._webGLVersion > 1) {
  16980. return this._caps.colorBufferFloat;
  16981. }
  16982. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16983. };
  16984. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16985. Engine.prototype._canRenderToFramebuffer = function (type) {
  16986. var gl = this._gl;
  16987. //clear existing errors
  16988. while (gl.getError() !== gl.NO_ERROR) { }
  16989. var successful = true;
  16990. var texture = gl.createTexture();
  16991. gl.bindTexture(gl.TEXTURE_2D, texture);
  16992. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16993. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16994. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16995. var fb = gl.createFramebuffer();
  16996. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16997. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16998. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16999. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17000. successful = successful && (gl.getError() === gl.NO_ERROR);
  17001. //try render by clearing frame buffer's color buffer
  17002. if (successful) {
  17003. gl.clear(gl.COLOR_BUFFER_BIT);
  17004. successful = successful && (gl.getError() === gl.NO_ERROR);
  17005. }
  17006. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17007. if (successful) {
  17008. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17009. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17010. var readFormat = gl.RGBA;
  17011. var readType = gl.UNSIGNED_BYTE;
  17012. var buffer = new Uint8Array(4);
  17013. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17014. successful = successful && (gl.getError() === gl.NO_ERROR);
  17015. }
  17016. //clean up
  17017. gl.deleteTexture(texture);
  17018. gl.deleteFramebuffer(fb);
  17019. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17020. //clear accumulated errors
  17021. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17022. return successful;
  17023. };
  17024. /** @hidden */
  17025. Engine.prototype._getWebGLTextureType = function (type) {
  17026. if (this._webGLVersion === 1) {
  17027. switch (type) {
  17028. case Engine.TEXTURETYPE_FLOAT:
  17029. return this._gl.FLOAT;
  17030. case Engine.TEXTURETYPE_HALF_FLOAT:
  17031. return this._gl.HALF_FLOAT_OES;
  17032. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17033. return this._gl.UNSIGNED_BYTE;
  17034. }
  17035. return this._gl.UNSIGNED_BYTE;
  17036. }
  17037. switch (type) {
  17038. case Engine.TEXTURETYPE_BYTE:
  17039. return this._gl.BYTE;
  17040. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17041. return this._gl.UNSIGNED_BYTE;
  17042. case Engine.TEXTURETYPE_SHORT:
  17043. return this._gl.SHORT;
  17044. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17045. return this._gl.UNSIGNED_SHORT;
  17046. case Engine.TEXTURETYPE_INT:
  17047. return this._gl.INT;
  17048. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17049. return this._gl.UNSIGNED_INT;
  17050. case Engine.TEXTURETYPE_FLOAT:
  17051. return this._gl.FLOAT;
  17052. case Engine.TEXTURETYPE_HALF_FLOAT:
  17053. return this._gl.HALF_FLOAT;
  17054. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17055. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17056. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17057. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17058. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17059. return this._gl.UNSIGNED_SHORT_5_6_5;
  17060. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17061. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17062. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17063. return this._gl.UNSIGNED_INT_24_8;
  17064. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17065. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17066. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17067. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17068. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17069. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17070. }
  17071. return this._gl.UNSIGNED_BYTE;
  17072. };
  17073. ;
  17074. Engine.prototype._getInternalFormat = function (format) {
  17075. var internalFormat = this._gl.RGBA;
  17076. switch (format) {
  17077. case Engine.TEXTUREFORMAT_ALPHA:
  17078. internalFormat = this._gl.ALPHA;
  17079. break;
  17080. case Engine.TEXTUREFORMAT_LUMINANCE:
  17081. internalFormat = this._gl.LUMINANCE;
  17082. break;
  17083. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17084. internalFormat = this._gl.LUMINANCE_ALPHA;
  17085. break;
  17086. case Engine.TEXTUREFORMAT_RED:
  17087. internalFormat = this._gl.RED;
  17088. break;
  17089. case Engine.TEXTUREFORMAT_RG:
  17090. internalFormat = this._gl.RG;
  17091. break;
  17092. case Engine.TEXTUREFORMAT_RGB:
  17093. internalFormat = this._gl.RGB;
  17094. break;
  17095. case Engine.TEXTUREFORMAT_RGBA:
  17096. internalFormat = this._gl.RGBA;
  17097. break;
  17098. }
  17099. if (this._webGLVersion > 1) {
  17100. switch (format) {
  17101. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17102. internalFormat = this._gl.RED_INTEGER;
  17103. break;
  17104. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17105. internalFormat = this._gl.RG_INTEGER;
  17106. break;
  17107. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17108. internalFormat = this._gl.RGB_INTEGER;
  17109. break;
  17110. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17111. internalFormat = this._gl.RGBA_INTEGER;
  17112. break;
  17113. }
  17114. }
  17115. return internalFormat;
  17116. };
  17117. /** @hidden */
  17118. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17119. if (this._webGLVersion === 1) {
  17120. if (format !== undefined) {
  17121. switch (format) {
  17122. case Engine.TEXTUREFORMAT_ALPHA:
  17123. return this._gl.ALPHA;
  17124. case Engine.TEXTUREFORMAT_LUMINANCE:
  17125. return this._gl.LUMINANCE;
  17126. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17127. return this._gl.LUMINANCE_ALPHA;
  17128. }
  17129. }
  17130. return this._gl.RGBA;
  17131. }
  17132. switch (type) {
  17133. case Engine.TEXTURETYPE_BYTE:
  17134. switch (format) {
  17135. case Engine.TEXTUREFORMAT_RED:
  17136. return this._gl.R8_SNORM;
  17137. case Engine.TEXTUREFORMAT_RG:
  17138. return this._gl.RG8_SNORM;
  17139. case Engine.TEXTUREFORMAT_RGB:
  17140. return this._gl.RGB8_SNORM;
  17141. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17142. return this._gl.R8I;
  17143. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17144. return this._gl.RG8I;
  17145. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17146. return this._gl.RGB8I;
  17147. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17148. return this._gl.RGBA8I;
  17149. default:
  17150. return this._gl.RGBA8_SNORM;
  17151. }
  17152. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17153. switch (format) {
  17154. case Engine.TEXTUREFORMAT_RED:
  17155. return this._gl.R8;
  17156. case Engine.TEXTUREFORMAT_RG:
  17157. return this._gl.RG8;
  17158. case Engine.TEXTUREFORMAT_RGB:
  17159. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17160. case Engine.TEXTUREFORMAT_RGBA:
  17161. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17162. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17163. return this._gl.R8UI;
  17164. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17165. return this._gl.RG8UI;
  17166. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17167. return this._gl.RGB8UI;
  17168. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17169. return this._gl.RGBA8UI;
  17170. default:
  17171. return this._gl.RGBA8;
  17172. }
  17173. case Engine.TEXTURETYPE_SHORT:
  17174. switch (format) {
  17175. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17176. return this._gl.R16I;
  17177. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17178. return this._gl.RG16I;
  17179. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17180. return this._gl.RGB16I;
  17181. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17182. return this._gl.RGBA16I;
  17183. default:
  17184. return this._gl.RGBA16I;
  17185. }
  17186. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17187. switch (format) {
  17188. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17189. return this._gl.R16UI;
  17190. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17191. return this._gl.RG16UI;
  17192. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17193. return this._gl.RGB16UI;
  17194. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17195. return this._gl.RGBA16UI;
  17196. default:
  17197. return this._gl.RGBA16UI;
  17198. }
  17199. case Engine.TEXTURETYPE_INT:
  17200. switch (format) {
  17201. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17202. return this._gl.R32I;
  17203. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17204. return this._gl.RG32I;
  17205. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17206. return this._gl.RGB32I;
  17207. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17208. return this._gl.RGBA32I;
  17209. default:
  17210. return this._gl.RGBA32I;
  17211. }
  17212. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17213. switch (format) {
  17214. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17215. return this._gl.R32UI;
  17216. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17217. return this._gl.RG32UI;
  17218. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17219. return this._gl.RGB32UI;
  17220. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17221. return this._gl.RGBA32UI;
  17222. default:
  17223. return this._gl.RGBA32UI;
  17224. }
  17225. case Engine.TEXTURETYPE_FLOAT:
  17226. switch (format) {
  17227. case Engine.TEXTUREFORMAT_RED:
  17228. return this._gl.R32F; // By default. Other possibility is R16F.
  17229. case Engine.TEXTUREFORMAT_RG:
  17230. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17231. case Engine.TEXTUREFORMAT_RGB:
  17232. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17233. case Engine.TEXTUREFORMAT_RGBA:
  17234. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17235. default:
  17236. return this._gl.RGBA32F;
  17237. }
  17238. case Engine.TEXTURETYPE_HALF_FLOAT:
  17239. switch (format) {
  17240. case Engine.TEXTUREFORMAT_RED:
  17241. return this._gl.R16F;
  17242. case Engine.TEXTUREFORMAT_RG:
  17243. return this._gl.RG16F;
  17244. case Engine.TEXTUREFORMAT_RGB:
  17245. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17246. case Engine.TEXTUREFORMAT_RGBA:
  17247. return this._gl.RGBA16F;
  17248. default:
  17249. return this._gl.RGBA16F;
  17250. }
  17251. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17252. return this._gl.RGB565;
  17253. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17254. return this._gl.R11F_G11F_B10F;
  17255. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17256. return this._gl.RGB9_E5;
  17257. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17258. return this._gl.RGBA4;
  17259. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17260. return this._gl.RGB5_A1;
  17261. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17262. switch (format) {
  17263. case Engine.TEXTUREFORMAT_RGBA:
  17264. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17265. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17266. return this._gl.RGB10_A2UI;
  17267. default:
  17268. return this._gl.RGB10_A2;
  17269. }
  17270. }
  17271. return this._gl.RGBA8;
  17272. };
  17273. ;
  17274. /** @hidden */
  17275. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17276. if (type === Engine.TEXTURETYPE_FLOAT) {
  17277. return this._gl.RGBA32F;
  17278. }
  17279. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17280. return this._gl.RGBA16F;
  17281. }
  17282. return this._gl.RGBA8;
  17283. };
  17284. ;
  17285. /** @hidden */
  17286. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17287. var _this = this;
  17288. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17289. this._activeRequests.push(request);
  17290. request.onCompleteObservable.add(function (request) {
  17291. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17292. });
  17293. return request;
  17294. };
  17295. /** @hidden */
  17296. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17297. var _this = this;
  17298. return new Promise(function (resolve, reject) {
  17299. _this._loadFile(url, function (data) {
  17300. resolve(data);
  17301. }, undefined, database, useArrayBuffer, function (request, exception) {
  17302. reject(exception);
  17303. });
  17304. });
  17305. };
  17306. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17307. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17308. var onload = function (data) {
  17309. loadedFiles[index] = data;
  17310. loadedFiles._internalCount++;
  17311. if (loadedFiles._internalCount === 6) {
  17312. onfinish(loadedFiles);
  17313. }
  17314. };
  17315. var onerror = function (request, exception) {
  17316. if (onErrorCallBack && request) {
  17317. onErrorCallBack(request.status + " " + request.statusText, exception);
  17318. }
  17319. };
  17320. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17321. };
  17322. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17323. if (onError === void 0) { onError = null; }
  17324. var loadedFiles = [];
  17325. loadedFiles._internalCount = 0;
  17326. for (var index = 0; index < 6; index++) {
  17327. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17328. }
  17329. };
  17330. // Statics
  17331. /**
  17332. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17333. * @returns true if the engine can be created
  17334. * @ignorenaming
  17335. */
  17336. Engine.isSupported = function () {
  17337. try {
  17338. var tempcanvas = document.createElement("canvas");
  17339. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17340. return gl != null && !!window.WebGLRenderingContext;
  17341. }
  17342. catch (e) {
  17343. return false;
  17344. }
  17345. };
  17346. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17347. Engine.ExceptionList = [
  17348. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17349. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17350. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17351. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17352. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17353. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17354. ];
  17355. /** Gets the list of created engines */
  17356. Engine.Instances = new Array();
  17357. /**
  17358. * Hidden
  17359. */
  17360. Engine._TextureLoaders = [];
  17361. // Const statics
  17362. /** Defines that alpha blending is disabled */
  17363. Engine.ALPHA_DISABLE = 0;
  17364. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17365. Engine.ALPHA_ADD = 1;
  17366. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17367. Engine.ALPHA_COMBINE = 2;
  17368. /** Defines that alpha blending to DEST - SRC * DEST */
  17369. Engine.ALPHA_SUBTRACT = 3;
  17370. /** Defines that alpha blending to SRC * DEST */
  17371. Engine.ALPHA_MULTIPLY = 4;
  17372. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17373. Engine.ALPHA_MAXIMIZED = 5;
  17374. /** Defines that alpha blending to SRC + DEST */
  17375. Engine.ALPHA_ONEONE = 6;
  17376. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17377. Engine.ALPHA_PREMULTIPLIED = 7;
  17378. /**
  17379. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17380. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17381. */
  17382. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17383. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17384. Engine.ALPHA_INTERPOLATE = 9;
  17385. /**
  17386. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17387. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17388. */
  17389. Engine.ALPHA_SCREENMODE = 10;
  17390. /** Defines that the ressource is not delayed*/
  17391. Engine.DELAYLOADSTATE_NONE = 0;
  17392. /** Defines that the ressource was successfully delay loaded */
  17393. Engine.DELAYLOADSTATE_LOADED = 1;
  17394. /** Defines that the ressource is currently delay loading */
  17395. Engine.DELAYLOADSTATE_LOADING = 2;
  17396. /** Defines that the ressource is delayed and has not started loading */
  17397. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17398. // Depht or Stencil test Constants.
  17399. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17400. Engine.NEVER = 0x0200;
  17401. /** 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 */
  17402. Engine.ALWAYS = 0x0207;
  17403. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17404. Engine.LESS = 0x0201;
  17405. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17406. Engine.EQUAL = 0x0202;
  17407. /** 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 */
  17408. Engine.LEQUAL = 0x0203;
  17409. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17410. Engine.GREATER = 0x0204;
  17411. /** 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 */
  17412. Engine.GEQUAL = 0x0206;
  17413. /** 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 */
  17414. Engine.NOTEQUAL = 0x0205;
  17415. // Stencil Actions Constants.
  17416. /** Passed to stencilOperation to specify that stencil value must be kept */
  17417. Engine.KEEP = 0x1E00;
  17418. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17419. Engine.REPLACE = 0x1E01;
  17420. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17421. Engine.INCR = 0x1E02;
  17422. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17423. Engine.DECR = 0x1E03;
  17424. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17425. Engine.INVERT = 0x150A;
  17426. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17427. Engine.INCR_WRAP = 0x8507;
  17428. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17429. Engine.DECR_WRAP = 0x8508;
  17430. /** Texture is not repeating outside of 0..1 UVs */
  17431. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17432. /** Texture is repeating outside of 0..1 UVs */
  17433. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17434. /** Texture is repeating and mirrored */
  17435. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17436. /** ALPHA */
  17437. Engine.TEXTUREFORMAT_ALPHA = 0;
  17438. /** LUMINANCE */
  17439. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17440. /** LUMINANCE_ALPHA */
  17441. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17442. /** RGB */
  17443. Engine.TEXTUREFORMAT_RGB = 4;
  17444. /** RGBA */
  17445. Engine.TEXTUREFORMAT_RGBA = 5;
  17446. /** RED */
  17447. Engine.TEXTUREFORMAT_RED = 6;
  17448. /** RED (2nd reference) */
  17449. Engine.TEXTUREFORMAT_R = 6;
  17450. /** RG */
  17451. Engine.TEXTUREFORMAT_RG = 7;
  17452. /** RED_INTEGER */
  17453. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17454. /** RED_INTEGER (2nd reference) */
  17455. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17456. /** RG_INTEGER */
  17457. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17458. /** RGB_INTEGER */
  17459. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17460. /** RGBA_INTEGER */
  17461. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17462. /** UNSIGNED_BYTE */
  17463. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17464. /** UNSIGNED_BYTE (2nd reference) */
  17465. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17466. /** FLOAT */
  17467. Engine.TEXTURETYPE_FLOAT = 1;
  17468. /** HALF_FLOAT */
  17469. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17470. /** BYTE */
  17471. Engine.TEXTURETYPE_BYTE = 3;
  17472. /** SHORT */
  17473. Engine.TEXTURETYPE_SHORT = 4;
  17474. /** UNSIGNED_SHORT */
  17475. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17476. /** INT */
  17477. Engine.TEXTURETYPE_INT = 6;
  17478. /** UNSIGNED_INT */
  17479. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17480. /** UNSIGNED_SHORT_4_4_4_4 */
  17481. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17482. /** UNSIGNED_SHORT_5_5_5_1 */
  17483. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17484. /** UNSIGNED_SHORT_5_6_5 */
  17485. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17486. /** UNSIGNED_INT_2_10_10_10_REV */
  17487. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17488. /** UNSIGNED_INT_24_8 */
  17489. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17490. /** UNSIGNED_INT_10F_11F_11F_REV */
  17491. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17492. /** UNSIGNED_INT_5_9_9_9_REV */
  17493. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17494. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17495. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17496. /** nearest is mag = nearest and min = nearest and mip = linear */
  17497. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17498. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17499. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17500. /** Trilinear is mag = linear and min = linear and mip = linear */
  17501. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17502. /** nearest is mag = nearest and min = nearest and mip = linear */
  17503. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17504. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17505. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17506. /** Trilinear is mag = linear and min = linear and mip = linear */
  17507. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17508. /** mag = nearest and min = nearest and mip = nearest */
  17509. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17510. /** mag = nearest and min = linear and mip = nearest */
  17511. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17512. /** mag = nearest and min = linear and mip = linear */
  17513. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17514. /** mag = nearest and min = linear and mip = none */
  17515. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17516. /** mag = nearest and min = nearest and mip = none */
  17517. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17518. /** mag = linear and min = nearest and mip = nearest */
  17519. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17520. /** mag = linear and min = nearest and mip = linear */
  17521. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17522. /** mag = linear and min = linear and mip = none */
  17523. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17524. /** mag = linear and min = nearest and mip = none */
  17525. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17526. /** Explicit coordinates mode */
  17527. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17528. /** Spherical coordinates mode */
  17529. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17530. /** Planar coordinates mode */
  17531. Engine.TEXTURE_PLANAR_MODE = 2;
  17532. /** Cubic coordinates mode */
  17533. Engine.TEXTURE_CUBIC_MODE = 3;
  17534. /** Projection coordinates mode */
  17535. Engine.TEXTURE_PROJECTION_MODE = 4;
  17536. /** Skybox coordinates mode */
  17537. Engine.TEXTURE_SKYBOX_MODE = 5;
  17538. /** Inverse Cubic coordinates mode */
  17539. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17540. /** Equirectangular coordinates mode */
  17541. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17542. /** Equirectangular Fixed coordinates mode */
  17543. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17544. /** Equirectangular Fixed Mirrored coordinates mode */
  17545. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17546. // Texture rescaling mode
  17547. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17548. Engine.SCALEMODE_FLOOR = 1;
  17549. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17550. Engine.SCALEMODE_NEAREST = 2;
  17551. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17552. Engine.SCALEMODE_CEILING = 3;
  17553. // Updatable statics so stick with vars here
  17554. /**
  17555. * Gets or sets the epsilon value used by collision engine
  17556. */
  17557. Engine.CollisionsEpsilon = 0.001;
  17558. /**
  17559. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17560. */
  17561. Engine.CodeRepository = "src/";
  17562. /**
  17563. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17564. */
  17565. Engine.ShadersRepository = "src/Shaders/";
  17566. return Engine;
  17567. }());
  17568. BABYLON.Engine = Engine;
  17569. })(BABYLON || (BABYLON = {}));
  17570. //# sourceMappingURL=babylon.engine.js.map
  17571. var BABYLON;
  17572. (function (BABYLON) {
  17573. /**
  17574. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17575. */
  17576. var Node = /** @class */ (function () {
  17577. /**
  17578. * Creates a new Node
  17579. * @param {string} name - the name and id to be given to this node
  17580. * @param {BABYLON.Scene} the scene this node will be added to
  17581. */
  17582. function Node(name, scene) {
  17583. if (scene === void 0) { scene = null; }
  17584. /**
  17585. * Gets or sets a string used to store user defined state for the node
  17586. */
  17587. this.state = "";
  17588. /**
  17589. * Gets or sets an object used to store user defined information for the node
  17590. */
  17591. this.metadata = null;
  17592. /**
  17593. * Gets or sets a boolean used to define if the node must be serialized
  17594. */
  17595. this.doNotSerialize = false;
  17596. /** @hidden */
  17597. this._isDisposed = false;
  17598. /**
  17599. * Gets a list of Animations associated with the node
  17600. */
  17601. this.animations = new Array();
  17602. this._ranges = {};
  17603. this._isEnabled = true;
  17604. this._isParentEnabled = true;
  17605. this._isReady = true;
  17606. /** @hidden */
  17607. this._currentRenderId = -1;
  17608. this._parentRenderId = -1;
  17609. this._childRenderId = -1;
  17610. /** @hidden */
  17611. this._worldMatrix = BABYLON.Matrix.Zero();
  17612. /** @hidden */
  17613. this._worldMatrixDeterminant = 0;
  17614. this._animationPropertiesOverride = null;
  17615. /**
  17616. * An event triggered when the mesh is disposed
  17617. */
  17618. this.onDisposeObservable = new BABYLON.Observable();
  17619. // Behaviors
  17620. this._behaviors = new Array();
  17621. this.name = name;
  17622. this.id = name;
  17623. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17624. this.uniqueId = this._scene.getUniqueId();
  17625. this._initCache();
  17626. this._scene.rootNodes.push(this);
  17627. }
  17628. /**
  17629. * Add a new node constructor
  17630. * @param type defines the type name of the node to construct
  17631. * @param constructorFunc defines the constructor function
  17632. */
  17633. Node.AddNodeConstructor = function (type, constructorFunc) {
  17634. this._NodeConstructors[type] = constructorFunc;
  17635. };
  17636. /**
  17637. * Returns a node constructor based on type name
  17638. * @param type defines the type name
  17639. * @param name defines the new node name
  17640. * @param scene defines the hosting scene
  17641. * @param options defines optional options to transmit to constructors
  17642. * @returns the new constructor or null
  17643. */
  17644. Node.Construct = function (type, name, scene, options) {
  17645. var constructorFunc = this._NodeConstructors[type];
  17646. if (!constructorFunc) {
  17647. return null;
  17648. }
  17649. return constructorFunc(name, scene, options);
  17650. };
  17651. /**
  17652. * Gets a boolean indicating if the node has been disposed
  17653. * @returns true if the node was disposed
  17654. */
  17655. Node.prototype.isDisposed = function () {
  17656. return this._isDisposed;
  17657. };
  17658. Object.defineProperty(Node.prototype, "parent", {
  17659. get: function () {
  17660. return this._parentNode;
  17661. },
  17662. /**
  17663. * Gets or sets the parent of the node
  17664. */
  17665. set: function (parent) {
  17666. if (this._parentNode === parent) {
  17667. return;
  17668. }
  17669. var previousParentNode = this._parentNode;
  17670. // Remove self from list of children of parent
  17671. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17672. var index = this._parentNode._children.indexOf(this);
  17673. if (index !== -1) {
  17674. this._parentNode._children.splice(index, 1);
  17675. }
  17676. if (!parent) {
  17677. // Need to add this node to the rootNodes
  17678. this._scene.rootNodes.push(this);
  17679. }
  17680. }
  17681. // Store new parent
  17682. this._parentNode = parent;
  17683. // Add as child to new parent
  17684. if (this._parentNode) {
  17685. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17686. this._parentNode._children = new Array();
  17687. }
  17688. this._parentNode._children.push(this);
  17689. if (!previousParentNode) {
  17690. // Need to remove from rootNodes
  17691. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  17692. if (rootNodeIndex > -1) {
  17693. this._scene.rootNodes.splice(rootNodeIndex, 1);
  17694. }
  17695. }
  17696. }
  17697. // Enabled state
  17698. this._syncParentEnabledState();
  17699. },
  17700. enumerable: true,
  17701. configurable: true
  17702. });
  17703. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17704. /**
  17705. * Gets or sets the animation properties override
  17706. */
  17707. get: function () {
  17708. if (!this._animationPropertiesOverride) {
  17709. return this._scene.animationPropertiesOverride;
  17710. }
  17711. return this._animationPropertiesOverride;
  17712. },
  17713. set: function (value) {
  17714. this._animationPropertiesOverride = value;
  17715. },
  17716. enumerable: true,
  17717. configurable: true
  17718. });
  17719. /**
  17720. * Gets a string idenfifying the name of the class
  17721. * @returns "Node" string
  17722. */
  17723. Node.prototype.getClassName = function () {
  17724. return "Node";
  17725. };
  17726. Object.defineProperty(Node.prototype, "onDispose", {
  17727. /**
  17728. * Sets a callback that will be raised when the node will be disposed
  17729. */
  17730. set: function (callback) {
  17731. if (this._onDisposeObserver) {
  17732. this.onDisposeObservable.remove(this._onDisposeObserver);
  17733. }
  17734. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17735. },
  17736. enumerable: true,
  17737. configurable: true
  17738. });
  17739. /**
  17740. * Gets the scene of the node
  17741. * @returns a {BABYLON.Scene}
  17742. */
  17743. Node.prototype.getScene = function () {
  17744. return this._scene;
  17745. };
  17746. /**
  17747. * Gets the engine of the node
  17748. * @returns a {BABYLON.Engine}
  17749. */
  17750. Node.prototype.getEngine = function () {
  17751. return this._scene.getEngine();
  17752. };
  17753. /**
  17754. * Attach a behavior to the node
  17755. * @see http://doc.babylonjs.com/features/behaviour
  17756. * @param behavior defines the behavior to attach
  17757. * @returns the current Node
  17758. */
  17759. Node.prototype.addBehavior = function (behavior) {
  17760. var _this = this;
  17761. var index = this._behaviors.indexOf(behavior);
  17762. if (index !== -1) {
  17763. return this;
  17764. }
  17765. behavior.init();
  17766. if (this._scene.isLoading) {
  17767. // We defer the attach when the scene will be loaded
  17768. this._scene.onDataLoadedObservable.addOnce(function () {
  17769. behavior.attach(_this);
  17770. });
  17771. }
  17772. else {
  17773. behavior.attach(this);
  17774. }
  17775. this._behaviors.push(behavior);
  17776. return this;
  17777. };
  17778. /**
  17779. * Remove an attached behavior
  17780. * @see http://doc.babylonjs.com/features/behaviour
  17781. * @param behavior defines the behavior to attach
  17782. * @returns the current Node
  17783. */
  17784. Node.prototype.removeBehavior = function (behavior) {
  17785. var index = this._behaviors.indexOf(behavior);
  17786. if (index === -1) {
  17787. return this;
  17788. }
  17789. this._behaviors[index].detach();
  17790. this._behaviors.splice(index, 1);
  17791. return this;
  17792. };
  17793. Object.defineProperty(Node.prototype, "behaviors", {
  17794. /**
  17795. * Gets the list of attached behaviors
  17796. * @see http://doc.babylonjs.com/features/behaviour
  17797. */
  17798. get: function () {
  17799. return this._behaviors;
  17800. },
  17801. enumerable: true,
  17802. configurable: true
  17803. });
  17804. /**
  17805. * Gets an attached behavior by name
  17806. * @param name defines the name of the behavior to look for
  17807. * @see http://doc.babylonjs.com/features/behaviour
  17808. * @returns null if behavior was not found else the requested behavior
  17809. */
  17810. Node.prototype.getBehaviorByName = function (name) {
  17811. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17812. var behavior = _a[_i];
  17813. if (behavior.name === name) {
  17814. return behavior;
  17815. }
  17816. }
  17817. return null;
  17818. };
  17819. /**
  17820. * Returns the latest update of the World matrix
  17821. * @returns a Matrix
  17822. */
  17823. Node.prototype.getWorldMatrix = function () {
  17824. if (this._currentRenderId !== this._scene.getRenderId()) {
  17825. this.computeWorldMatrix();
  17826. }
  17827. return this._worldMatrix;
  17828. };
  17829. /** @hidden */
  17830. Node.prototype._getWorldMatrixDeterminant = function () {
  17831. return this._worldMatrixDeterminant;
  17832. };
  17833. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  17834. /**
  17835. * Returns directly the latest state of the mesh World matrix.
  17836. * A Matrix is returned.
  17837. */
  17838. get: function () {
  17839. return this._worldMatrix;
  17840. },
  17841. enumerable: true,
  17842. configurable: true
  17843. });
  17844. // override it in derived class if you add new variables to the cache
  17845. // and call the parent class method
  17846. /** @hidden */
  17847. Node.prototype._initCache = function () {
  17848. this._cache = {};
  17849. this._cache.parent = undefined;
  17850. };
  17851. /** @hidden */
  17852. Node.prototype.updateCache = function (force) {
  17853. if (!force && this.isSynchronized())
  17854. return;
  17855. this._cache.parent = this.parent;
  17856. this._updateCache();
  17857. };
  17858. // override it in derived class if you add new variables to the cache
  17859. // and call the parent class method if !ignoreParentClass
  17860. /** @hidden */
  17861. Node.prototype._updateCache = function (ignoreParentClass) {
  17862. };
  17863. // override it in derived class if you add new variables to the cache
  17864. /** @hidden */
  17865. Node.prototype._isSynchronized = function () {
  17866. return true;
  17867. };
  17868. /** @hidden */
  17869. Node.prototype._markSyncedWithParent = function () {
  17870. if (this._parentNode) {
  17871. this._parentRenderId = this._parentNode._childRenderId;
  17872. }
  17873. };
  17874. /** @hidden */
  17875. Node.prototype.isSynchronizedWithParent = function () {
  17876. if (!this._parentNode) {
  17877. return true;
  17878. }
  17879. if (this._parentRenderId !== this._parentNode._childRenderId) {
  17880. return false;
  17881. }
  17882. return this._parentNode.isSynchronized();
  17883. };
  17884. /** @hidden */
  17885. Node.prototype.isSynchronized = function () {
  17886. if (this._cache.parent != this._parentNode) {
  17887. this._cache.parent = this._parentNode;
  17888. return false;
  17889. }
  17890. if (this._parentNode && !this.isSynchronizedWithParent()) {
  17891. return false;
  17892. }
  17893. return this._isSynchronized();
  17894. };
  17895. /**
  17896. * Is this node ready to be used/rendered
  17897. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17898. * @return true if the node is ready
  17899. */
  17900. Node.prototype.isReady = function (completeCheck) {
  17901. if (completeCheck === void 0) { completeCheck = false; }
  17902. return this._isReady;
  17903. };
  17904. /**
  17905. * Is this node enabled?
  17906. * 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
  17907. * @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
  17908. * @return whether this node (and its parent) is enabled
  17909. */
  17910. Node.prototype.isEnabled = function (checkAncestors) {
  17911. if (checkAncestors === void 0) { checkAncestors = true; }
  17912. if (checkAncestors === false) {
  17913. return this._isEnabled;
  17914. }
  17915. if (!this._isEnabled) {
  17916. return false;
  17917. }
  17918. return this._isParentEnabled;
  17919. };
  17920. /** @hidden */
  17921. Node.prototype._syncParentEnabledState = function () {
  17922. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  17923. if (this._children) {
  17924. this._children.forEach(function (c) {
  17925. c._syncParentEnabledState(); // Force children to update accordingly
  17926. });
  17927. }
  17928. };
  17929. /**
  17930. * Set the enabled state of this node
  17931. * @param value defines the new enabled state
  17932. */
  17933. Node.prototype.setEnabled = function (value) {
  17934. this._isEnabled = value;
  17935. this._syncParentEnabledState();
  17936. };
  17937. /**
  17938. * Is this node a descendant of the given node?
  17939. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17940. * @param ancestor defines the parent node to inspect
  17941. * @returns a boolean indicating if this node is a descendant of the given node
  17942. */
  17943. Node.prototype.isDescendantOf = function (ancestor) {
  17944. if (this.parent) {
  17945. if (this.parent === ancestor) {
  17946. return true;
  17947. }
  17948. return this.parent.isDescendantOf(ancestor);
  17949. }
  17950. return false;
  17951. };
  17952. /** @hidden */
  17953. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17954. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17955. if (!this._children) {
  17956. return;
  17957. }
  17958. for (var index = 0; index < this._children.length; index++) {
  17959. var item = this._children[index];
  17960. if (!predicate || predicate(item)) {
  17961. results.push(item);
  17962. }
  17963. if (!directDescendantsOnly) {
  17964. item._getDescendants(results, false, predicate);
  17965. }
  17966. }
  17967. };
  17968. /**
  17969. * Will return all nodes that have this node as ascendant
  17970. * @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
  17971. * @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
  17972. * @return all children nodes of all types
  17973. */
  17974. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17975. var results = new Array();
  17976. this._getDescendants(results, directDescendantsOnly, predicate);
  17977. return results;
  17978. };
  17979. /**
  17980. * Get all child-meshes of this node
  17981. * @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
  17982. * @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
  17983. * @returns an array of {BABYLON.AbstractMesh}
  17984. */
  17985. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17986. var results = [];
  17987. this._getDescendants(results, directDescendantsOnly, function (node) {
  17988. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17989. });
  17990. return results;
  17991. };
  17992. /**
  17993. * Get all child-transformNodes of this node
  17994. * @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
  17995. * @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
  17996. * @returns an array of {BABYLON.TransformNode}
  17997. */
  17998. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17999. var results = [];
  18000. this._getDescendants(results, directDescendantsOnly, function (node) {
  18001. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18002. });
  18003. return results;
  18004. };
  18005. /**
  18006. * Get all direct children of this node
  18007. * @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
  18008. * @returns an array of {BABYLON.Node}
  18009. */
  18010. Node.prototype.getChildren = function (predicate) {
  18011. if (!predicate) {
  18012. return this._children;
  18013. }
  18014. return this.getDescendants(true, predicate);
  18015. };
  18016. /** @hidden */
  18017. Node.prototype._setReady = function (state) {
  18018. if (state === this._isReady) {
  18019. return;
  18020. }
  18021. if (!state) {
  18022. this._isReady = false;
  18023. return;
  18024. }
  18025. if (this.onReady) {
  18026. this.onReady(this);
  18027. }
  18028. this._isReady = true;
  18029. };
  18030. /**
  18031. * Get an animation by name
  18032. * @param name defines the name of the animation to look for
  18033. * @returns null if not found else the requested animation
  18034. */
  18035. Node.prototype.getAnimationByName = function (name) {
  18036. for (var i = 0; i < this.animations.length; i++) {
  18037. var animation = this.animations[i];
  18038. if (animation.name === name) {
  18039. return animation;
  18040. }
  18041. }
  18042. return null;
  18043. };
  18044. /**
  18045. * Creates an animation range for this node
  18046. * @param name defines the name of the range
  18047. * @param from defines the starting key
  18048. * @param to defines the end key
  18049. */
  18050. Node.prototype.createAnimationRange = function (name, from, to) {
  18051. // check name not already in use
  18052. if (!this._ranges[name]) {
  18053. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18054. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18055. if (this.animations[i]) {
  18056. this.animations[i].createRange(name, from, to);
  18057. }
  18058. }
  18059. }
  18060. };
  18061. /**
  18062. * Delete a specific animation range
  18063. * @param name defines the name of the range to delete
  18064. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18065. */
  18066. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18067. if (deleteFrames === void 0) { deleteFrames = true; }
  18068. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18069. if (this.animations[i]) {
  18070. this.animations[i].deleteRange(name, deleteFrames);
  18071. }
  18072. }
  18073. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18074. };
  18075. /**
  18076. * Get an animation range by name
  18077. * @param name defines the name of the animation range to look for
  18078. * @returns null if not found else the requested animation range
  18079. */
  18080. Node.prototype.getAnimationRange = function (name) {
  18081. return this._ranges[name];
  18082. };
  18083. /**
  18084. * Will start the animation sequence
  18085. * @param name defines the range frames for animation sequence
  18086. * @param loop defines if the animation should loop (false by default)
  18087. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18088. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18089. * @returns the object created for this animation. If range does not exist, it will return null
  18090. */
  18091. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18092. var range = this.getAnimationRange(name);
  18093. if (!range) {
  18094. return null;
  18095. }
  18096. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18097. };
  18098. /**
  18099. * Serialize animation ranges into a JSON compatible object
  18100. * @returns serialization object
  18101. */
  18102. Node.prototype.serializeAnimationRanges = function () {
  18103. var serializationRanges = [];
  18104. for (var name in this._ranges) {
  18105. var localRange = this._ranges[name];
  18106. if (!localRange) {
  18107. continue;
  18108. }
  18109. var range = {};
  18110. range.name = name;
  18111. range.from = localRange.from;
  18112. range.to = localRange.to;
  18113. serializationRanges.push(range);
  18114. }
  18115. return serializationRanges;
  18116. };
  18117. /**
  18118. * Computes the world matrix of the node
  18119. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18120. * @returns the world matrix
  18121. */
  18122. Node.prototype.computeWorldMatrix = function (force) {
  18123. if (!this._worldMatrix) {
  18124. this._worldMatrix = BABYLON.Matrix.Identity();
  18125. }
  18126. return this._worldMatrix;
  18127. };
  18128. /**
  18129. * Releases resources associated with this node.
  18130. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18131. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18132. */
  18133. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18134. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18135. if (!doNotRecurse) {
  18136. var nodes = this.getDescendants(true);
  18137. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18138. var node = nodes_1[_i];
  18139. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18140. }
  18141. }
  18142. else {
  18143. var transformNodes = this.getChildTransformNodes(true);
  18144. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18145. var transformNode = transformNodes_1[_a];
  18146. transformNode.parent = null;
  18147. transformNode.computeWorldMatrix(true);
  18148. }
  18149. }
  18150. if (!this.parent) {
  18151. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18152. if (rootNodeIndex > -1) {
  18153. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18154. }
  18155. }
  18156. else {
  18157. this.parent = null;
  18158. }
  18159. // Callback
  18160. this.onDisposeObservable.notifyObservers(this);
  18161. this.onDisposeObservable.clear();
  18162. // Behaviors
  18163. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18164. var behavior = _c[_b];
  18165. behavior.detach();
  18166. }
  18167. this._behaviors = [];
  18168. this._isDisposed = true;
  18169. };
  18170. /**
  18171. * Parse animation range data from a serialization object and store them into a given node
  18172. * @param node defines where to store the animation ranges
  18173. * @param parsedNode defines the serialization object to read data from
  18174. * @param scene defines the hosting scene
  18175. */
  18176. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18177. if (parsedNode.ranges) {
  18178. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18179. var data = parsedNode.ranges[index];
  18180. node.createAnimationRange(data.name, data.from, data.to);
  18181. }
  18182. }
  18183. };
  18184. Node._NodeConstructors = {};
  18185. __decorate([
  18186. BABYLON.serialize()
  18187. ], Node.prototype, "name", void 0);
  18188. __decorate([
  18189. BABYLON.serialize()
  18190. ], Node.prototype, "id", void 0);
  18191. __decorate([
  18192. BABYLON.serialize()
  18193. ], Node.prototype, "uniqueId", void 0);
  18194. __decorate([
  18195. BABYLON.serialize()
  18196. ], Node.prototype, "state", void 0);
  18197. __decorate([
  18198. BABYLON.serialize()
  18199. ], Node.prototype, "metadata", void 0);
  18200. return Node;
  18201. }());
  18202. BABYLON.Node = Node;
  18203. })(BABYLON || (BABYLON = {}));
  18204. //# sourceMappingURL=babylon.node.js.map
  18205. var BABYLON;
  18206. (function (BABYLON) {
  18207. // This matrix is used as a value to reset the bounding box.
  18208. var _identityMatrix = BABYLON.Matrix.Identity();
  18209. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18210. var BoundingSphere = /** @class */ (function () {
  18211. /**
  18212. * Creates a new bounding sphere
  18213. * @param min defines the minimum vector (in local space)
  18214. * @param max defines the maximum vector (in local space)
  18215. */
  18216. function BoundingSphere(min, max) {
  18217. this.center = BABYLON.Vector3.Zero();
  18218. this.centerWorld = BABYLON.Vector3.Zero();
  18219. this.reConstruct(min, max);
  18220. }
  18221. /**
  18222. * Recreates the entire bounding sphere from scratch
  18223. * @param min defines the new minimum vector (in local space)
  18224. * @param max defines the new maximum vector (in local space)
  18225. */
  18226. BoundingSphere.prototype.reConstruct = function (min, max) {
  18227. this.minimum = min.clone();
  18228. this.maximum = max.clone();
  18229. var distance = BABYLON.Vector3.Distance(min, max);
  18230. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18231. this.radius = distance * 0.5;
  18232. this.centerWorld.set(0, 0, 0);
  18233. this._update(_identityMatrix);
  18234. };
  18235. /**
  18236. * Scale the current bounding sphere by applying a scale factor
  18237. * @param factor defines the scale factor to apply
  18238. * @returns the current bounding box
  18239. */
  18240. BoundingSphere.prototype.scale = function (factor) {
  18241. var newRadius = this.radius * factor;
  18242. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18243. var min = this.center.subtract(_tempRadiusVector);
  18244. var max = this.center.add(_tempRadiusVector);
  18245. this.reConstruct(min, max);
  18246. return this;
  18247. };
  18248. // Methods
  18249. /** @hidden */
  18250. BoundingSphere.prototype._update = function (world) {
  18251. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18252. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18253. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18254. };
  18255. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18256. for (var i = 0; i < 6; i++) {
  18257. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18258. return false;
  18259. }
  18260. return true;
  18261. };
  18262. BoundingSphere.prototype.intersectsPoint = function (point) {
  18263. var x = this.centerWorld.x - point.x;
  18264. var y = this.centerWorld.y - point.y;
  18265. var z = this.centerWorld.z - point.z;
  18266. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18267. if (this.radiusWorld < distance)
  18268. return false;
  18269. return true;
  18270. };
  18271. // Statics
  18272. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18273. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18274. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18275. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18276. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18277. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18278. return false;
  18279. return true;
  18280. };
  18281. return BoundingSphere;
  18282. }());
  18283. BABYLON.BoundingSphere = BoundingSphere;
  18284. })(BABYLON || (BABYLON = {}));
  18285. //# sourceMappingURL=babylon.boundingSphere.js.map
  18286. var BABYLON;
  18287. (function (BABYLON) {
  18288. var BoundingBox = /** @class */ (function () {
  18289. /**
  18290. * Creates a new bounding box
  18291. * @param min defines the minimum vector (in local space)
  18292. * @param max defines the maximum vector (in local space)
  18293. */
  18294. function BoundingBox(min, max) {
  18295. this.vectorsWorld = new Array();
  18296. this.reConstruct(min, max);
  18297. }
  18298. // Methods
  18299. /**
  18300. * Recreates the entire bounding box from scratch
  18301. * @param min defines the new minimum vector (in local space)
  18302. * @param max defines the new maximum vector (in local space)
  18303. */
  18304. BoundingBox.prototype.reConstruct = function (min, max) {
  18305. this.minimum = min.clone();
  18306. this.maximum = max.clone();
  18307. // Bounding vectors
  18308. this.vectors = [
  18309. this.minimum.clone(),
  18310. this.maximum.clone(),
  18311. this.minimum.clone(),
  18312. this.minimum.clone(),
  18313. this.minimum.clone(),
  18314. this.maximum.clone(),
  18315. this.maximum.clone(),
  18316. this.maximum.clone()
  18317. ];
  18318. this.vectors[2].x = this.maximum.x;
  18319. this.vectors[3].y = this.maximum.y;
  18320. this.vectors[4].z = this.maximum.z;
  18321. this.vectors[5].z = this.minimum.z;
  18322. this.vectors[6].x = this.minimum.x;
  18323. this.vectors[7].y = this.minimum.y;
  18324. // OBB
  18325. this.center = this.maximum.add(this.minimum).scale(0.5);
  18326. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18327. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18328. // World
  18329. for (var index = 0; index < this.vectors.length; index++) {
  18330. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18331. }
  18332. this.minimumWorld = BABYLON.Vector3.Zero();
  18333. this.maximumWorld = BABYLON.Vector3.Zero();
  18334. this.centerWorld = BABYLON.Vector3.Zero();
  18335. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18336. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18337. };
  18338. /**
  18339. * Scale the current bounding box by applying a scale factor
  18340. * @param factor defines the scale factor to apply
  18341. * @returns the current bounding box
  18342. */
  18343. BoundingBox.prototype.scale = function (factor) {
  18344. var diff = this.maximum.subtract(this.minimum);
  18345. var distance = diff.length() * factor;
  18346. diff.normalize();
  18347. var newRadius = diff.scale(distance / 2);
  18348. var min = this.center.subtract(newRadius);
  18349. var max = this.center.add(newRadius);
  18350. this.reConstruct(min, max);
  18351. return this;
  18352. };
  18353. BoundingBox.prototype.getWorldMatrix = function () {
  18354. return this._worldMatrix;
  18355. };
  18356. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18357. this._worldMatrix.copyFrom(matrix);
  18358. return this;
  18359. };
  18360. /** @hidden */
  18361. BoundingBox.prototype._update = function (world) {
  18362. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18363. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18364. for (var index = 0; index < this.vectors.length; index++) {
  18365. var v = this.vectorsWorld[index];
  18366. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18367. if (v.x < this.minimumWorld.x)
  18368. this.minimumWorld.x = v.x;
  18369. if (v.y < this.minimumWorld.y)
  18370. this.minimumWorld.y = v.y;
  18371. if (v.z < this.minimumWorld.z)
  18372. this.minimumWorld.z = v.z;
  18373. if (v.x > this.maximumWorld.x)
  18374. this.maximumWorld.x = v.x;
  18375. if (v.y > this.maximumWorld.y)
  18376. this.maximumWorld.y = v.y;
  18377. if (v.z > this.maximumWorld.z)
  18378. this.maximumWorld.z = v.z;
  18379. }
  18380. // Extend
  18381. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18382. this.extendSizeWorld.scaleInPlace(0.5);
  18383. // OBB
  18384. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18385. this.centerWorld.scaleInPlace(0.5);
  18386. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18387. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18388. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18389. this._worldMatrix = world;
  18390. };
  18391. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18392. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18393. };
  18394. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18395. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18396. };
  18397. BoundingBox.prototype.intersectsPoint = function (point) {
  18398. var delta = -BABYLON.Epsilon;
  18399. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18400. return false;
  18401. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18402. return false;
  18403. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18404. return false;
  18405. return true;
  18406. };
  18407. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18408. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18409. };
  18410. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18411. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18412. return false;
  18413. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18414. return false;
  18415. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18416. return false;
  18417. return true;
  18418. };
  18419. // Statics
  18420. BoundingBox.Intersects = function (box0, box1) {
  18421. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18422. return false;
  18423. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18424. return false;
  18425. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18426. return false;
  18427. return true;
  18428. };
  18429. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18430. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18431. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18432. return (num <= (sphereRadius * sphereRadius));
  18433. };
  18434. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18435. for (var p = 0; p < 6; p++) {
  18436. for (var i = 0; i < 8; i++) {
  18437. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18438. return false;
  18439. }
  18440. }
  18441. }
  18442. return true;
  18443. };
  18444. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18445. for (var p = 0; p < 6; p++) {
  18446. var inCount = 8;
  18447. for (var i = 0; i < 8; i++) {
  18448. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18449. --inCount;
  18450. }
  18451. else {
  18452. break;
  18453. }
  18454. }
  18455. if (inCount === 0)
  18456. return false;
  18457. }
  18458. return true;
  18459. };
  18460. return BoundingBox;
  18461. }());
  18462. BABYLON.BoundingBox = BoundingBox;
  18463. })(BABYLON || (BABYLON = {}));
  18464. //# sourceMappingURL=babylon.boundingBox.js.map
  18465. var BABYLON;
  18466. (function (BABYLON) {
  18467. var computeBoxExtents = function (axis, box) {
  18468. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18469. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18470. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18471. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18472. var r = r0 + r1 + r2;
  18473. return {
  18474. min: p - r,
  18475. max: p + r
  18476. };
  18477. };
  18478. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18479. var axisOverlap = function (axis, box0, box1) {
  18480. var result0 = computeBoxExtents(axis, box0);
  18481. var result1 = computeBoxExtents(axis, box1);
  18482. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18483. };
  18484. var BoundingInfo = /** @class */ (function () {
  18485. function BoundingInfo(minimum, maximum) {
  18486. this.minimum = minimum;
  18487. this.maximum = maximum;
  18488. this._isLocked = false;
  18489. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18490. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18491. }
  18492. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18493. get: function () {
  18494. return this._isLocked;
  18495. },
  18496. set: function (value) {
  18497. this._isLocked = value;
  18498. },
  18499. enumerable: true,
  18500. configurable: true
  18501. });
  18502. // Methods
  18503. BoundingInfo.prototype.update = function (world) {
  18504. if (this._isLocked) {
  18505. return;
  18506. }
  18507. this.boundingBox._update(world);
  18508. this.boundingSphere._update(world);
  18509. };
  18510. /**
  18511. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18512. * @param center New center of the bounding info
  18513. * @param extend New extend of the bounding info
  18514. */
  18515. BoundingInfo.prototype.centerOn = function (center, extend) {
  18516. this.minimum = center.subtract(extend);
  18517. this.maximum = center.add(extend);
  18518. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18519. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18520. return this;
  18521. };
  18522. /**
  18523. * Scale the current bounding info by applying a scale factor
  18524. * @param factor defines the scale factor to apply
  18525. * @returns the current bounding info
  18526. */
  18527. BoundingInfo.prototype.scale = function (factor) {
  18528. this.boundingBox.scale(factor);
  18529. this.boundingSphere.scale(factor);
  18530. return this;
  18531. };
  18532. /**
  18533. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18534. * @param frustumPlanes defines the frustum to test
  18535. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18536. * @returns true if the bounding info is in the frustum planes
  18537. */
  18538. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18539. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18540. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18541. return false;
  18542. }
  18543. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18544. return true;
  18545. }
  18546. return this.boundingBox.isInFrustum(frustumPlanes);
  18547. };
  18548. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18549. /**
  18550. * Gets the world distance between the min and max points of the bounding box
  18551. */
  18552. get: function () {
  18553. var boundingBox = this.boundingBox;
  18554. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18555. return size.length();
  18556. },
  18557. enumerable: true,
  18558. configurable: true
  18559. });
  18560. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18561. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18562. };
  18563. /** @hidden */
  18564. BoundingInfo.prototype._checkCollision = function (collider) {
  18565. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18566. };
  18567. BoundingInfo.prototype.intersectsPoint = function (point) {
  18568. if (!this.boundingSphere.centerWorld) {
  18569. return false;
  18570. }
  18571. if (!this.boundingSphere.intersectsPoint(point)) {
  18572. return false;
  18573. }
  18574. if (!this.boundingBox.intersectsPoint(point)) {
  18575. return false;
  18576. }
  18577. return true;
  18578. };
  18579. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18580. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18581. return false;
  18582. }
  18583. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18584. return false;
  18585. }
  18586. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18587. return false;
  18588. }
  18589. if (!precise) {
  18590. return true;
  18591. }
  18592. var box0 = this.boundingBox;
  18593. var box1 = boundingInfo.boundingBox;
  18594. if (!axisOverlap(box0.directions[0], box0, box1))
  18595. return false;
  18596. if (!axisOverlap(box0.directions[1], box0, box1))
  18597. return false;
  18598. if (!axisOverlap(box0.directions[2], box0, box1))
  18599. return false;
  18600. if (!axisOverlap(box1.directions[0], box0, box1))
  18601. return false;
  18602. if (!axisOverlap(box1.directions[1], box0, box1))
  18603. return false;
  18604. if (!axisOverlap(box1.directions[2], box0, box1))
  18605. return false;
  18606. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18607. return false;
  18608. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18609. return false;
  18610. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18611. return false;
  18612. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18613. return false;
  18614. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18615. return false;
  18616. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18617. return false;
  18618. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18619. return false;
  18620. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18621. return false;
  18622. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18623. return false;
  18624. return true;
  18625. };
  18626. return BoundingInfo;
  18627. }());
  18628. BABYLON.BoundingInfo = BoundingInfo;
  18629. })(BABYLON || (BABYLON = {}));
  18630. //# sourceMappingURL=babylon.boundingInfo.js.map
  18631. var BABYLON;
  18632. (function (BABYLON) {
  18633. var TransformNode = /** @class */ (function (_super) {
  18634. __extends(TransformNode, _super);
  18635. function TransformNode(name, scene, isPure) {
  18636. if (scene === void 0) { scene = null; }
  18637. if (isPure === void 0) { isPure = true; }
  18638. var _this = _super.call(this, name, scene) || this;
  18639. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18640. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18641. _this._up = new BABYLON.Vector3(0, 1, 0);
  18642. _this._right = new BABYLON.Vector3(1, 0, 0);
  18643. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18644. // Properties
  18645. _this._position = BABYLON.Vector3.Zero();
  18646. _this._rotation = BABYLON.Vector3.Zero();
  18647. _this._scaling = BABYLON.Vector3.One();
  18648. _this._isDirty = false;
  18649. /**
  18650. * Set the billboard mode. Default is 0.
  18651. *
  18652. * | Value | Type | Description |
  18653. * | --- | --- | --- |
  18654. * | 0 | BILLBOARDMODE_NONE | |
  18655. * | 1 | BILLBOARDMODE_X | |
  18656. * | 2 | BILLBOARDMODE_Y | |
  18657. * | 4 | BILLBOARDMODE_Z | |
  18658. * | 7 | BILLBOARDMODE_ALL | |
  18659. *
  18660. */
  18661. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18662. _this.scalingDeterminant = 1;
  18663. _this.infiniteDistance = false;
  18664. /**
  18665. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18666. * By default the system will update normals to compensate
  18667. */
  18668. _this.ignoreNonUniformScaling = false;
  18669. _this._localWorld = BABYLON.Matrix.Zero();
  18670. _this._absolutePosition = BABYLON.Vector3.Zero();
  18671. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18672. _this._postMultiplyPivotMatrix = false;
  18673. _this._isWorldMatrixFrozen = false;
  18674. /**
  18675. * An event triggered after the world matrix is updated
  18676. */
  18677. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18678. _this._nonUniformScaling = false;
  18679. if (isPure) {
  18680. _this.getScene().addTransformNode(_this);
  18681. }
  18682. return _this;
  18683. }
  18684. /**
  18685. * Gets a string identifying the name of the class
  18686. * @returns "TransformNode" string
  18687. */
  18688. TransformNode.prototype.getClassName = function () {
  18689. return "TransformNode";
  18690. };
  18691. Object.defineProperty(TransformNode.prototype, "position", {
  18692. /**
  18693. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  18694. */
  18695. get: function () {
  18696. return this._position;
  18697. },
  18698. set: function (newPosition) {
  18699. this._position = newPosition;
  18700. this._isDirty = true;
  18701. },
  18702. enumerable: true,
  18703. configurable: true
  18704. });
  18705. Object.defineProperty(TransformNode.prototype, "rotation", {
  18706. /**
  18707. * 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)).
  18708. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  18709. */
  18710. get: function () {
  18711. return this._rotation;
  18712. },
  18713. set: function (newRotation) {
  18714. this._rotation = newRotation;
  18715. this._isDirty = true;
  18716. },
  18717. enumerable: true,
  18718. configurable: true
  18719. });
  18720. Object.defineProperty(TransformNode.prototype, "scaling", {
  18721. /**
  18722. * 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)).
  18723. */
  18724. get: function () {
  18725. return this._scaling;
  18726. },
  18727. set: function (newScaling) {
  18728. this._scaling = newScaling;
  18729. this._isDirty = true;
  18730. },
  18731. enumerable: true,
  18732. configurable: true
  18733. });
  18734. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18735. /**
  18736. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  18737. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  18738. */
  18739. get: function () {
  18740. return this._rotationQuaternion;
  18741. },
  18742. set: function (quaternion) {
  18743. this._rotationQuaternion = quaternion;
  18744. //reset the rotation vector.
  18745. if (quaternion && this.rotation.length()) {
  18746. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18747. }
  18748. },
  18749. enumerable: true,
  18750. configurable: true
  18751. });
  18752. Object.defineProperty(TransformNode.prototype, "forward", {
  18753. /**
  18754. * The forward direction of that transform in world space.
  18755. */
  18756. get: function () {
  18757. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18758. },
  18759. enumerable: true,
  18760. configurable: true
  18761. });
  18762. Object.defineProperty(TransformNode.prototype, "up", {
  18763. /**
  18764. * The up direction of that transform in world space.
  18765. */
  18766. get: function () {
  18767. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18768. },
  18769. enumerable: true,
  18770. configurable: true
  18771. });
  18772. Object.defineProperty(TransformNode.prototype, "right", {
  18773. /**
  18774. * The right direction of that transform in world space.
  18775. */
  18776. get: function () {
  18777. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18778. },
  18779. enumerable: true,
  18780. configurable: true
  18781. });
  18782. /**
  18783. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18784. * Returns the TransformNode.
  18785. */
  18786. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18787. this._poseMatrix.copyFrom(matrix);
  18788. return this;
  18789. };
  18790. /**
  18791. * Returns the mesh Pose matrix.
  18792. * Returned object : Matrix
  18793. */
  18794. TransformNode.prototype.getPoseMatrix = function () {
  18795. return this._poseMatrix;
  18796. };
  18797. /** @hidden */
  18798. TransformNode.prototype._isSynchronized = function () {
  18799. if (this._isDirty) {
  18800. return false;
  18801. }
  18802. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18803. return false;
  18804. if (this._cache.pivotMatrixUpdated) {
  18805. return false;
  18806. }
  18807. if (this.infiniteDistance) {
  18808. return false;
  18809. }
  18810. if (!this._cache.position.equals(this._position))
  18811. return false;
  18812. if (this._rotationQuaternion) {
  18813. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  18814. return false;
  18815. }
  18816. else if (!this._cache.rotation.equals(this._rotation))
  18817. return false;
  18818. if (!this._cache.scaling.equals(this._scaling))
  18819. return false;
  18820. return true;
  18821. };
  18822. /** @hidden */
  18823. TransformNode.prototype._initCache = function () {
  18824. _super.prototype._initCache.call(this);
  18825. this._cache.localMatrixUpdated = false;
  18826. this._cache.position = BABYLON.Vector3.Zero();
  18827. this._cache.scaling = BABYLON.Vector3.Zero();
  18828. this._cache.rotation = BABYLON.Vector3.Zero();
  18829. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18830. this._cache.billboardMode = -1;
  18831. };
  18832. TransformNode.prototype.markAsDirty = function (property) {
  18833. if (property === "rotation") {
  18834. this.rotationQuaternion = null;
  18835. }
  18836. this._currentRenderId = Number.MAX_VALUE;
  18837. this._isDirty = true;
  18838. return this;
  18839. };
  18840. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18841. /**
  18842. * Returns the current mesh absolute position.
  18843. * Returns a Vector3.
  18844. */
  18845. get: function () {
  18846. return this._absolutePosition;
  18847. },
  18848. enumerable: true,
  18849. configurable: true
  18850. });
  18851. /**
  18852. * Sets a new matrix to apply before all other transformation
  18853. * @param matrix defines the transform matrix
  18854. * @returns the current TransformNode
  18855. */
  18856. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18857. return this.setPivotMatrix(matrix, false);
  18858. };
  18859. /**
  18860. * Sets a new pivot matrix to the current node
  18861. * @param matrix defines the new pivot matrix to use
  18862. * @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
  18863. * @returns the current TransformNode
  18864. */
  18865. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18866. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18867. this._pivotMatrix = matrix.clone();
  18868. this._cache.pivotMatrixUpdated = true;
  18869. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18870. if (this._postMultiplyPivotMatrix) {
  18871. if (!this._pivotMatrixInverse) {
  18872. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18873. }
  18874. else {
  18875. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18876. }
  18877. }
  18878. return this;
  18879. };
  18880. /**
  18881. * Returns the mesh pivot matrix.
  18882. * Default : Identity.
  18883. * A Matrix is returned.
  18884. */
  18885. TransformNode.prototype.getPivotMatrix = function () {
  18886. return this._pivotMatrix;
  18887. };
  18888. /**
  18889. * Prevents the World matrix to be computed any longer.
  18890. * Returns the TransformNode.
  18891. */
  18892. TransformNode.prototype.freezeWorldMatrix = function () {
  18893. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18894. this.computeWorldMatrix(true);
  18895. this._isWorldMatrixFrozen = true;
  18896. return this;
  18897. };
  18898. /**
  18899. * Allows back the World matrix computation.
  18900. * Returns the TransformNode.
  18901. */
  18902. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18903. this._isWorldMatrixFrozen = false;
  18904. this.computeWorldMatrix(true);
  18905. return this;
  18906. };
  18907. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18908. /**
  18909. * True if the World matrix has been frozen.
  18910. * Returns a boolean.
  18911. */
  18912. get: function () {
  18913. return this._isWorldMatrixFrozen;
  18914. },
  18915. enumerable: true,
  18916. configurable: true
  18917. });
  18918. /**
  18919. * Retuns the mesh absolute position in the World.
  18920. * Returns a Vector3.
  18921. */
  18922. TransformNode.prototype.getAbsolutePosition = function () {
  18923. this.computeWorldMatrix();
  18924. return this._absolutePosition;
  18925. };
  18926. /**
  18927. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18928. * Returns the TransformNode.
  18929. */
  18930. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18931. if (!absolutePosition) {
  18932. return this;
  18933. }
  18934. var absolutePositionX;
  18935. var absolutePositionY;
  18936. var absolutePositionZ;
  18937. if (absolutePosition.x === undefined) {
  18938. if (arguments.length < 3) {
  18939. return this;
  18940. }
  18941. absolutePositionX = arguments[0];
  18942. absolutePositionY = arguments[1];
  18943. absolutePositionZ = arguments[2];
  18944. }
  18945. else {
  18946. absolutePositionX = absolutePosition.x;
  18947. absolutePositionY = absolutePosition.y;
  18948. absolutePositionZ = absolutePosition.z;
  18949. }
  18950. if (this.parent) {
  18951. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18952. invertParentWorldMatrix.invert();
  18953. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18954. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18955. }
  18956. else {
  18957. this.position.x = absolutePositionX;
  18958. this.position.y = absolutePositionY;
  18959. this.position.z = absolutePositionZ;
  18960. }
  18961. return this;
  18962. };
  18963. /**
  18964. * Sets the mesh position in its local space.
  18965. * Returns the TransformNode.
  18966. */
  18967. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18968. this.computeWorldMatrix();
  18969. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18970. return this;
  18971. };
  18972. /**
  18973. * Returns the mesh position in the local space from the current World matrix values.
  18974. * Returns a new Vector3.
  18975. */
  18976. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18977. this.computeWorldMatrix();
  18978. var invLocalWorldMatrix = this._localWorld.clone();
  18979. invLocalWorldMatrix.invert();
  18980. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18981. };
  18982. /**
  18983. * Translates the mesh along the passed Vector3 in its local space.
  18984. * Returns the TransformNode.
  18985. */
  18986. TransformNode.prototype.locallyTranslate = function (vector3) {
  18987. this.computeWorldMatrix(true);
  18988. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18989. return this;
  18990. };
  18991. /**
  18992. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18993. * @param targetPoint the position (must be in same space as current mesh) to look at
  18994. * @param yawCor optional yaw (y-axis) correction in radians
  18995. * @param pitchCor optional pitch (x-axis) correction in radians
  18996. * @param rollCor optional roll (z-axis) correction in radians
  18997. * @param space the choosen space of the target
  18998. * @returns the TransformNode.
  18999. */
  19000. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19001. if (yawCor === void 0) { yawCor = 0; }
  19002. if (pitchCor === void 0) { pitchCor = 0; }
  19003. if (rollCor === void 0) { rollCor = 0; }
  19004. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19005. var dv = TransformNode._lookAtVectorCache;
  19006. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19007. targetPoint.subtractToRef(pos, dv);
  19008. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19009. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19010. var pitch = Math.atan2(dv.y, len);
  19011. if (this.rotationQuaternion) {
  19012. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19013. }
  19014. else {
  19015. this.rotation.x = pitch + pitchCor;
  19016. this.rotation.y = yaw + yawCor;
  19017. this.rotation.z = rollCor;
  19018. }
  19019. return this;
  19020. };
  19021. /**
  19022. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19023. * This Vector3 is expressed in the World space.
  19024. */
  19025. TransformNode.prototype.getDirection = function (localAxis) {
  19026. var result = BABYLON.Vector3.Zero();
  19027. this.getDirectionToRef(localAxis, result);
  19028. return result;
  19029. };
  19030. /**
  19031. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19032. * localAxis is expressed in the mesh local space.
  19033. * result is computed in the Wordl space from the mesh World matrix.
  19034. * Returns the TransformNode.
  19035. */
  19036. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19037. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19038. return this;
  19039. };
  19040. /**
  19041. * Sets a new pivot point to the current node
  19042. * @param point defines the new pivot point to use
  19043. * @param space defines if the point is in world or local space (local by default)
  19044. * @returns the current TransformNode
  19045. */
  19046. TransformNode.prototype.setPivotPoint = function (point, space) {
  19047. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19048. if (this.getScene().getRenderId() == 0) {
  19049. this.computeWorldMatrix(true);
  19050. }
  19051. var wm = this.getWorldMatrix();
  19052. if (space == BABYLON.Space.WORLD) {
  19053. var tmat = BABYLON.Tmp.Matrix[0];
  19054. wm.invertToRef(tmat);
  19055. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19056. }
  19057. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19058. };
  19059. /**
  19060. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19061. */
  19062. TransformNode.prototype.getPivotPoint = function () {
  19063. var point = BABYLON.Vector3.Zero();
  19064. this.getPivotPointToRef(point);
  19065. return point;
  19066. };
  19067. /**
  19068. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19069. * Returns the TransformNode.
  19070. */
  19071. TransformNode.prototype.getPivotPointToRef = function (result) {
  19072. result.x = -this._pivotMatrix.m[12];
  19073. result.y = -this._pivotMatrix.m[13];
  19074. result.z = -this._pivotMatrix.m[14];
  19075. return this;
  19076. };
  19077. /**
  19078. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19079. */
  19080. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19081. var point = BABYLON.Vector3.Zero();
  19082. this.getAbsolutePivotPointToRef(point);
  19083. return point;
  19084. };
  19085. /**
  19086. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19087. * Returns the TransformNode.
  19088. */
  19089. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19090. result.x = this._pivotMatrix.m[12];
  19091. result.y = this._pivotMatrix.m[13];
  19092. result.z = this._pivotMatrix.m[14];
  19093. this.getPivotPointToRef(result);
  19094. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19095. return this;
  19096. };
  19097. /**
  19098. * Defines the passed node as the parent of the current node.
  19099. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19100. * Returns the TransformNode.
  19101. */
  19102. TransformNode.prototype.setParent = function (node) {
  19103. if (!node && !this.parent) {
  19104. return this;
  19105. }
  19106. if (!node) {
  19107. var rotation = BABYLON.Tmp.Quaternion[0];
  19108. var position = BABYLON.Tmp.Vector3[0];
  19109. var scale = BABYLON.Tmp.Vector3[1];
  19110. if (this.parent && this.parent.computeWorldMatrix) {
  19111. this.parent.computeWorldMatrix(true);
  19112. }
  19113. this.computeWorldMatrix(true);
  19114. this.getWorldMatrix().decompose(scale, rotation, position);
  19115. if (this.rotationQuaternion) {
  19116. this.rotationQuaternion.copyFrom(rotation);
  19117. }
  19118. else {
  19119. rotation.toEulerAnglesToRef(this.rotation);
  19120. }
  19121. this.scaling.x = scale.x;
  19122. this.scaling.y = scale.y;
  19123. this.scaling.z = scale.z;
  19124. this.position.x = position.x;
  19125. this.position.y = position.y;
  19126. this.position.z = position.z;
  19127. }
  19128. else {
  19129. var rotation = BABYLON.Tmp.Quaternion[0];
  19130. var position = BABYLON.Tmp.Vector3[0];
  19131. var scale = BABYLON.Tmp.Vector3[1];
  19132. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19133. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19134. this.computeWorldMatrix(true);
  19135. node.computeWorldMatrix(true);
  19136. node.getWorldMatrix().invertToRef(invParentMatrix);
  19137. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19138. diffMatrix.decompose(scale, rotation, position);
  19139. if (this.rotationQuaternion) {
  19140. this.rotationQuaternion.copyFrom(rotation);
  19141. }
  19142. else {
  19143. rotation.toEulerAnglesToRef(this.rotation);
  19144. }
  19145. this.position.x = position.x;
  19146. this.position.y = position.y;
  19147. this.position.z = position.z;
  19148. this.scaling.x = scale.x;
  19149. this.scaling.y = scale.y;
  19150. this.scaling.z = scale.z;
  19151. }
  19152. this.parent = node;
  19153. return this;
  19154. };
  19155. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19156. get: function () {
  19157. return this._nonUniformScaling;
  19158. },
  19159. enumerable: true,
  19160. configurable: true
  19161. });
  19162. /** @hidden */
  19163. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19164. if (this._nonUniformScaling === value) {
  19165. return false;
  19166. }
  19167. this._nonUniformScaling = value;
  19168. return true;
  19169. };
  19170. /**
  19171. * Attach the current TransformNode to another TransformNode associated with a bone
  19172. * @param bone Bone affecting the TransformNode
  19173. * @param affectedTransformNode TransformNode associated with the bone
  19174. */
  19175. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19176. this._transformToBoneReferal = affectedTransformNode;
  19177. this.parent = bone;
  19178. if (bone.getWorldMatrix().determinant() < 0) {
  19179. this.scalingDeterminant *= -1;
  19180. }
  19181. return this;
  19182. };
  19183. TransformNode.prototype.detachFromBone = function () {
  19184. if (!this.parent) {
  19185. return this;
  19186. }
  19187. if (this.parent.getWorldMatrix().determinant() < 0) {
  19188. this.scalingDeterminant *= -1;
  19189. }
  19190. this._transformToBoneReferal = null;
  19191. this.parent = null;
  19192. return this;
  19193. };
  19194. /**
  19195. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19196. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19197. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19198. * The passed axis is also normalized.
  19199. * Returns the TransformNode.
  19200. */
  19201. TransformNode.prototype.rotate = function (axis, amount, space) {
  19202. axis.normalize();
  19203. if (!this.rotationQuaternion) {
  19204. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19205. this.rotation = BABYLON.Vector3.Zero();
  19206. }
  19207. var rotationQuaternion;
  19208. if (!space || space === BABYLON.Space.LOCAL) {
  19209. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19210. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19211. }
  19212. else {
  19213. if (this.parent) {
  19214. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19215. invertParentWorldMatrix.invert();
  19216. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19217. }
  19218. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19219. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19220. }
  19221. return this;
  19222. };
  19223. /**
  19224. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19225. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19226. * The passed axis is also normalized.
  19227. * Returns the TransformNode.
  19228. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19229. */
  19230. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19231. axis.normalize();
  19232. if (!this.rotationQuaternion) {
  19233. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19234. this.rotation.copyFromFloats(0, 0, 0);
  19235. }
  19236. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19237. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19238. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19239. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19240. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19241. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19242. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19243. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19244. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19245. return this;
  19246. };
  19247. /**
  19248. * Translates the mesh along the axis vector for the passed distance in the given space.
  19249. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19250. * Returns the TransformNode.
  19251. */
  19252. TransformNode.prototype.translate = function (axis, distance, space) {
  19253. var displacementVector = axis.scale(distance);
  19254. if (!space || space === BABYLON.Space.LOCAL) {
  19255. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19256. this.setPositionWithLocalVector(tempV3);
  19257. }
  19258. else {
  19259. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19260. }
  19261. return this;
  19262. };
  19263. /**
  19264. * Adds a rotation step to the mesh current rotation.
  19265. * x, y, z are Euler angles expressed in radians.
  19266. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19267. * This means this rotation is made in the mesh local space only.
  19268. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19269. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19270. * ```javascript
  19271. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19272. * ```
  19273. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19274. * 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.
  19275. * Returns the TransformNode.
  19276. */
  19277. TransformNode.prototype.addRotation = function (x, y, z) {
  19278. var rotationQuaternion;
  19279. if (this.rotationQuaternion) {
  19280. rotationQuaternion = this.rotationQuaternion;
  19281. }
  19282. else {
  19283. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19284. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19285. }
  19286. var accumulation = BABYLON.Tmp.Quaternion[0];
  19287. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19288. rotationQuaternion.multiplyInPlace(accumulation);
  19289. if (!this.rotationQuaternion) {
  19290. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19291. }
  19292. return this;
  19293. };
  19294. /**
  19295. * Computes the world matrix of the node
  19296. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19297. * @returns the world matrix
  19298. */
  19299. TransformNode.prototype.computeWorldMatrix = function (force) {
  19300. if (this._isWorldMatrixFrozen) {
  19301. return this._worldMatrix;
  19302. }
  19303. if (!force && this.isSynchronized()) {
  19304. this._currentRenderId = this.getScene().getRenderId();
  19305. return this._worldMatrix;
  19306. }
  19307. this._updateCache();
  19308. this._cache.position.copyFrom(this.position);
  19309. this._cache.scaling.copyFrom(this.scaling);
  19310. this._cache.pivotMatrixUpdated = false;
  19311. this._cache.billboardMode = this.billboardMode;
  19312. this._currentRenderId = this.getScene().getRenderId();
  19313. this._childRenderId = this.getScene().getRenderId();
  19314. this._isDirty = false;
  19315. // Scaling
  19316. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19317. // Rotation
  19318. //rotate, if quaternion is set and rotation was used
  19319. if (this.rotationQuaternion) {
  19320. var len = this.rotation.length();
  19321. if (len) {
  19322. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19323. this.rotation.copyFromFloats(0, 0, 0);
  19324. }
  19325. }
  19326. if (this.rotationQuaternion) {
  19327. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19328. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19329. }
  19330. else {
  19331. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19332. this._cache.rotation.copyFrom(this.rotation);
  19333. }
  19334. // Translation
  19335. var camera = this.getScene().activeCamera;
  19336. if (this.infiniteDistance && !this.parent && camera) {
  19337. var cameraWorldMatrix = camera.getWorldMatrix();
  19338. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19339. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19340. }
  19341. else {
  19342. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19343. }
  19344. // Composing transformations
  19345. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19346. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19347. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19348. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19349. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19350. // Need to decompose each rotation here
  19351. var currentPosition = BABYLON.Tmp.Vector3[3];
  19352. if (this.parent && this.parent.getWorldMatrix) {
  19353. if (this._transformToBoneReferal) {
  19354. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19355. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19356. }
  19357. else {
  19358. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19359. }
  19360. }
  19361. else {
  19362. currentPosition.copyFrom(this.position);
  19363. }
  19364. currentPosition.subtractInPlace(camera.globalPosition);
  19365. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19366. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19367. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19368. }
  19369. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19370. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19371. }
  19372. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19373. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19374. }
  19375. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19376. }
  19377. else {
  19378. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19379. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19380. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19381. }
  19382. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19383. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19384. }
  19385. // Post multiply inverse of pivotMatrix
  19386. if (this._postMultiplyPivotMatrix) {
  19387. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19388. }
  19389. // Local world
  19390. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19391. // Parent
  19392. if (this.parent && this.parent.getWorldMatrix) {
  19393. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19394. if (this._transformToBoneReferal) {
  19395. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19396. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19397. }
  19398. else {
  19399. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19400. }
  19401. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19402. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19403. this._worldMatrix.copyFrom(this._localWorld);
  19404. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19405. }
  19406. else {
  19407. if (this._transformToBoneReferal) {
  19408. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19409. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19410. }
  19411. else {
  19412. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19413. }
  19414. }
  19415. this._markSyncedWithParent();
  19416. }
  19417. else {
  19418. this._worldMatrix.copyFrom(this._localWorld);
  19419. }
  19420. // Normal matrix
  19421. if (!this.ignoreNonUniformScaling) {
  19422. if (this.scaling.isNonUniform) {
  19423. this._updateNonUniformScalingState(true);
  19424. }
  19425. else if (this.parent && this.parent._nonUniformScaling) {
  19426. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19427. }
  19428. else {
  19429. this._updateNonUniformScalingState(false);
  19430. }
  19431. }
  19432. else {
  19433. this._updateNonUniformScalingState(false);
  19434. }
  19435. this._afterComputeWorldMatrix();
  19436. // Absolute position
  19437. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19438. // Callbacks
  19439. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19440. if (!this._poseMatrix) {
  19441. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19442. }
  19443. // Cache the determinant
  19444. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19445. return this._worldMatrix;
  19446. };
  19447. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19448. };
  19449. /**
  19450. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19451. * @param func: callback function to add
  19452. *
  19453. * Returns the TransformNode.
  19454. */
  19455. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19456. this.onAfterWorldMatrixUpdateObservable.add(func);
  19457. return this;
  19458. };
  19459. /**
  19460. * Removes a registered callback function.
  19461. * Returns the TransformNode.
  19462. */
  19463. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19464. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19465. return this;
  19466. };
  19467. /**
  19468. * Clone the current transform node
  19469. * Returns the new transform node
  19470. * @param name Name of the new clone
  19471. * @param newParent New parent for the clone
  19472. * @param doNotCloneChildren Do not clone children hierarchy
  19473. */
  19474. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19475. var _this = this;
  19476. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19477. result.name = name;
  19478. result.id = name;
  19479. if (newParent) {
  19480. result.parent = newParent;
  19481. }
  19482. if (!doNotCloneChildren) {
  19483. // Children
  19484. var directDescendants = this.getDescendants(true);
  19485. for (var index = 0; index < directDescendants.length; index++) {
  19486. var child = directDescendants[index];
  19487. if (child.clone) {
  19488. child.clone(name + "." + child.name, result);
  19489. }
  19490. }
  19491. }
  19492. return result;
  19493. };
  19494. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19495. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19496. serializationObject.type = this.getClassName();
  19497. // Parent
  19498. if (this.parent) {
  19499. serializationObject.parentId = this.parent.id;
  19500. }
  19501. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19502. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19503. }
  19504. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19505. serializationObject.isEnabled = this.isEnabled();
  19506. // Parent
  19507. if (this.parent) {
  19508. serializationObject.parentId = this.parent.id;
  19509. }
  19510. return serializationObject;
  19511. };
  19512. // Statics
  19513. /**
  19514. * Returns a new TransformNode object parsed from the source provided.
  19515. * The parameter `parsedMesh` is the source.
  19516. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19517. */
  19518. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19519. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19520. if (BABYLON.Tags) {
  19521. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19522. }
  19523. if (parsedTransformNode.localMatrix) {
  19524. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19525. }
  19526. else if (parsedTransformNode.pivotMatrix) {
  19527. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19528. }
  19529. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19530. // Parent
  19531. if (parsedTransformNode.parentId) {
  19532. transformNode._waitingParentId = parsedTransformNode.parentId;
  19533. }
  19534. return transformNode;
  19535. };
  19536. /**
  19537. * Releases resources associated with this transform node.
  19538. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19539. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19540. */
  19541. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19542. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19543. // Animations
  19544. this.getScene().stopAnimation(this);
  19545. // Remove from scene
  19546. this.getScene().removeTransformNode(this);
  19547. this.onAfterWorldMatrixUpdateObservable.clear();
  19548. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19549. };
  19550. // Statics
  19551. TransformNode.BILLBOARDMODE_NONE = 0;
  19552. TransformNode.BILLBOARDMODE_X = 1;
  19553. TransformNode.BILLBOARDMODE_Y = 2;
  19554. TransformNode.BILLBOARDMODE_Z = 4;
  19555. TransformNode.BILLBOARDMODE_ALL = 7;
  19556. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19557. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19558. __decorate([
  19559. BABYLON.serializeAsVector3("position")
  19560. ], TransformNode.prototype, "_position", void 0);
  19561. __decorate([
  19562. BABYLON.serializeAsVector3("rotation")
  19563. ], TransformNode.prototype, "_rotation", void 0);
  19564. __decorate([
  19565. BABYLON.serializeAsQuaternion("rotationQuaternion")
  19566. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19567. __decorate([
  19568. BABYLON.serializeAsVector3("scaling")
  19569. ], TransformNode.prototype, "_scaling", void 0);
  19570. __decorate([
  19571. BABYLON.serialize()
  19572. ], TransformNode.prototype, "billboardMode", void 0);
  19573. __decorate([
  19574. BABYLON.serialize()
  19575. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19576. __decorate([
  19577. BABYLON.serialize()
  19578. ], TransformNode.prototype, "infiniteDistance", void 0);
  19579. __decorate([
  19580. BABYLON.serialize()
  19581. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19582. return TransformNode;
  19583. }(BABYLON.Node));
  19584. BABYLON.TransformNode = TransformNode;
  19585. })(BABYLON || (BABYLON = {}));
  19586. //# sourceMappingURL=babylon.transformNode.js.map
  19587. var BABYLON;
  19588. (function (BABYLON) {
  19589. /**
  19590. * Class used to store all common mesh properties
  19591. */
  19592. var AbstractMesh = /** @class */ (function (_super) {
  19593. __extends(AbstractMesh, _super);
  19594. // Constructor
  19595. /**
  19596. * Creates a new AbstractMesh
  19597. * @param name defines the name of the mesh
  19598. * @param scene defines the hosting scene
  19599. */
  19600. function AbstractMesh(name, scene) {
  19601. if (scene === void 0) { scene = null; }
  19602. var _this = _super.call(this, name, scene, false) || this;
  19603. _this._facetNb = 0; // facet number
  19604. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19605. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19606. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19607. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19608. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19609. _this._subDiv = {
  19610. max: 1,
  19611. X: 1,
  19612. Y: 1,
  19613. Z: 1
  19614. };
  19615. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19616. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19617. /** Gets ot sets the culling strategy to use to find visible meshes */
  19618. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19619. // Events
  19620. /**
  19621. * An event triggered when this mesh collides with another one
  19622. */
  19623. _this.onCollideObservable = new BABYLON.Observable();
  19624. /**
  19625. * An event triggered when the collision's position changes
  19626. */
  19627. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19628. /**
  19629. * An event triggered when material is changed
  19630. */
  19631. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19632. // Properties
  19633. /**
  19634. * Gets or sets the orientation for POV movement & rotation
  19635. */
  19636. _this.definedFacingForward = true;
  19637. /**
  19638. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19639. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19640. * * 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.
  19641. * @see http://doc.babylonjs.com/features/occlusionquery
  19642. */
  19643. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19644. /**
  19645. * 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:
  19646. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19647. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19648. * * 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.
  19649. * @see http://doc.babylonjs.com/features/occlusionquery
  19650. */
  19651. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19652. /**
  19653. * 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.
  19654. * The default value is -1 which means don't break the query and wait till the result
  19655. * @see http://doc.babylonjs.com/features/occlusionquery
  19656. */
  19657. _this.occlusionRetryCount = -1;
  19658. /** @hidden */
  19659. _this._occlusionInternalRetryCounter = 0;
  19660. /** @hidden */
  19661. _this._isOccluded = false;
  19662. /** @hidden */
  19663. _this._isOcclusionQueryInProgress = false;
  19664. _this._visibility = 1.0;
  19665. /** Gets or sets the alpha index used to sort transparent meshes
  19666. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19667. */
  19668. _this.alphaIndex = Number.MAX_VALUE;
  19669. /**
  19670. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19671. */
  19672. _this.isVisible = true;
  19673. /**
  19674. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19675. */
  19676. _this.isPickable = true;
  19677. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19678. _this.showSubMeshesBoundingBox = false;
  19679. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19680. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19681. */
  19682. _this.isBlocker = false;
  19683. /**
  19684. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19685. */
  19686. _this.enablePointerMoveEvents = false;
  19687. /**
  19688. * Specifies the rendering group id for this mesh (0 by default)
  19689. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19690. */
  19691. _this.renderingGroupId = 0;
  19692. _this._receiveShadows = false;
  19693. /** Defines color to use when rendering outline */
  19694. _this.outlineColor = BABYLON.Color3.Red();
  19695. /** Define width to use when rendering outline */
  19696. _this.outlineWidth = 0.02;
  19697. /** Defines color to use when rendering overlay */
  19698. _this.overlayColor = BABYLON.Color3.Red();
  19699. /** Defines alpha to use when rendering overlay */
  19700. _this.overlayAlpha = 0.5;
  19701. _this._hasVertexAlpha = false;
  19702. _this._useVertexColors = true;
  19703. _this._computeBonesUsingShaders = true;
  19704. _this._numBoneInfluencers = 4;
  19705. _this._applyFog = true;
  19706. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19707. _this.useOctreeForRenderingSelection = true;
  19708. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19709. _this.useOctreeForPicking = true;
  19710. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19711. _this.useOctreeForCollisions = true;
  19712. _this._layerMask = 0x0FFFFFFF;
  19713. /**
  19714. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19715. */
  19716. _this.alwaysSelectAsActiveMesh = false;
  19717. /**
  19718. * Gets or sets the current action manager
  19719. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19720. */
  19721. _this.actionManager = null;
  19722. // Collisions
  19723. _this._checkCollisions = false;
  19724. _this._collisionMask = -1;
  19725. _this._collisionGroup = -1;
  19726. /**
  19727. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19728. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19729. */
  19730. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19731. /**
  19732. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19733. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19734. */
  19735. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19736. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19737. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19738. // Edges
  19739. /**
  19740. * Defines edge width used when edgesRenderer is enabled
  19741. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19742. */
  19743. _this.edgesWidth = 1;
  19744. /**
  19745. * Defines edge color used when edgesRenderer is enabled
  19746. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19747. */
  19748. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19749. // Cache
  19750. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19751. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19752. /** @hidden */
  19753. _this._renderId = 0;
  19754. /** @hidden */
  19755. _this._intersectionsInProgress = new Array();
  19756. /** @hidden */
  19757. _this._unIndexed = false;
  19758. /** @hidden */
  19759. _this._lightSources = new Array();
  19760. /**
  19761. * An event triggered when the mesh is rebuilt.
  19762. */
  19763. _this.onRebuildObservable = new BABYLON.Observable();
  19764. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19765. if (collidedMesh === void 0) { collidedMesh = null; }
  19766. //TODO move this to the collision coordinator!
  19767. if (_this.getScene().workerCollisions)
  19768. newPosition.multiplyInPlace(_this._collider._radius);
  19769. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19770. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19771. _this.position.addInPlace(_this._diffPositionForCollisions);
  19772. }
  19773. if (collidedMesh) {
  19774. _this.onCollideObservable.notifyObservers(collidedMesh);
  19775. }
  19776. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19777. };
  19778. _this.getScene().addMesh(_this);
  19779. _this._resyncLightSources();
  19780. return _this;
  19781. }
  19782. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19783. /**
  19784. * No billboard
  19785. */
  19786. get: function () {
  19787. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19788. },
  19789. enumerable: true,
  19790. configurable: true
  19791. });
  19792. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19793. /** Billboard on X axis */
  19794. get: function () {
  19795. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19796. },
  19797. enumerable: true,
  19798. configurable: true
  19799. });
  19800. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19801. /** Billboard on Y axis */
  19802. get: function () {
  19803. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19804. },
  19805. enumerable: true,
  19806. configurable: true
  19807. });
  19808. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19809. /** Billboard on Z axis */
  19810. get: function () {
  19811. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19812. },
  19813. enumerable: true,
  19814. configurable: true
  19815. });
  19816. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19817. /** Billboard on all axes */
  19818. get: function () {
  19819. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19820. },
  19821. enumerable: true,
  19822. configurable: true
  19823. });
  19824. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19825. /**
  19826. * Gets the number of facets in the mesh
  19827. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19828. */
  19829. get: function () {
  19830. return this._facetNb;
  19831. },
  19832. enumerable: true,
  19833. configurable: true
  19834. });
  19835. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19836. /**
  19837. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19838. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19839. */
  19840. get: function () {
  19841. return this._partitioningSubdivisions;
  19842. },
  19843. set: function (nb) {
  19844. this._partitioningSubdivisions = nb;
  19845. },
  19846. enumerable: true,
  19847. configurable: true
  19848. });
  19849. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19850. /**
  19851. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19852. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19853. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19854. */
  19855. get: function () {
  19856. return this._partitioningBBoxRatio;
  19857. },
  19858. set: function (ratio) {
  19859. this._partitioningBBoxRatio = ratio;
  19860. },
  19861. enumerable: true,
  19862. configurable: true
  19863. });
  19864. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19865. /**
  19866. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19867. * Works only for updatable meshes.
  19868. * Doesn't work with multi-materials
  19869. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19870. */
  19871. get: function () {
  19872. return this._facetDepthSort;
  19873. },
  19874. set: function (sort) {
  19875. this._facetDepthSort = sort;
  19876. },
  19877. enumerable: true,
  19878. configurable: true
  19879. });
  19880. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19881. /**
  19882. * The location (Vector3) where the facet depth sort must be computed from.
  19883. * By default, the active camera position.
  19884. * Used only when facet depth sort is enabled
  19885. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19886. */
  19887. get: function () {
  19888. return this._facetDepthSortFrom;
  19889. },
  19890. set: function (location) {
  19891. this._facetDepthSortFrom = location;
  19892. },
  19893. enumerable: true,
  19894. configurable: true
  19895. });
  19896. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19897. /**
  19898. * gets a boolean indicating if facetData is enabled
  19899. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19900. */
  19901. get: function () {
  19902. return this._facetDataEnabled;
  19903. },
  19904. enumerable: true,
  19905. configurable: true
  19906. });
  19907. /** @hidden */
  19908. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19909. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19910. return false;
  19911. }
  19912. this._markSubMeshesAsMiscDirty();
  19913. return true;
  19914. };
  19915. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19916. /** Set a function to call when this mesh collides with another one */
  19917. set: function (callback) {
  19918. if (this._onCollideObserver) {
  19919. this.onCollideObservable.remove(this._onCollideObserver);
  19920. }
  19921. this._onCollideObserver = this.onCollideObservable.add(callback);
  19922. },
  19923. enumerable: true,
  19924. configurable: true
  19925. });
  19926. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19927. /** Set a function to call when the collision's position changes */
  19928. set: function (callback) {
  19929. if (this._onCollisionPositionChangeObserver) {
  19930. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19931. }
  19932. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19933. },
  19934. enumerable: true,
  19935. configurable: true
  19936. });
  19937. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19938. /**
  19939. * 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
  19940. * @see http://doc.babylonjs.com/features/occlusionquery
  19941. */
  19942. get: function () {
  19943. return this._isOccluded;
  19944. },
  19945. set: function (value) {
  19946. this._isOccluded = value;
  19947. },
  19948. enumerable: true,
  19949. configurable: true
  19950. });
  19951. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19952. /**
  19953. * Flag to check the progress status of the query
  19954. * @see http://doc.babylonjs.com/features/occlusionquery
  19955. */
  19956. get: function () {
  19957. return this._isOcclusionQueryInProgress;
  19958. },
  19959. enumerable: true,
  19960. configurable: true
  19961. });
  19962. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19963. /**
  19964. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19965. */
  19966. get: function () {
  19967. return this._visibility;
  19968. },
  19969. /**
  19970. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19971. */
  19972. set: function (value) {
  19973. if (this._visibility === value) {
  19974. return;
  19975. }
  19976. this._visibility = value;
  19977. this._markSubMeshesAsMiscDirty();
  19978. },
  19979. enumerable: true,
  19980. configurable: true
  19981. });
  19982. Object.defineProperty(AbstractMesh.prototype, "material", {
  19983. /** Gets or sets current material */
  19984. get: function () {
  19985. return this._material;
  19986. },
  19987. set: function (value) {
  19988. if (this._material === value) {
  19989. return;
  19990. }
  19991. this._material = value;
  19992. if (this.onMaterialChangedObservable.hasObservers) {
  19993. this.onMaterialChangedObservable.notifyObservers(this);
  19994. }
  19995. if (!this.subMeshes) {
  19996. return;
  19997. }
  19998. this._unBindEffect();
  19999. },
  20000. enumerable: true,
  20001. configurable: true
  20002. });
  20003. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20004. /**
  20005. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20006. * @see http://doc.babylonjs.com/babylon101/shadows
  20007. */
  20008. get: function () {
  20009. return this._receiveShadows;
  20010. },
  20011. set: function (value) {
  20012. if (this._receiveShadows === value) {
  20013. return;
  20014. }
  20015. this._receiveShadows = value;
  20016. this._markSubMeshesAsLightDirty();
  20017. },
  20018. enumerable: true,
  20019. configurable: true
  20020. });
  20021. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20022. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20023. get: function () {
  20024. return this._hasVertexAlpha;
  20025. },
  20026. set: function (value) {
  20027. if (this._hasVertexAlpha === value) {
  20028. return;
  20029. }
  20030. this._hasVertexAlpha = value;
  20031. this._markSubMeshesAsAttributesDirty();
  20032. this._markSubMeshesAsMiscDirty();
  20033. },
  20034. enumerable: true,
  20035. configurable: true
  20036. });
  20037. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20038. /** 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) */
  20039. get: function () {
  20040. return this._useVertexColors;
  20041. },
  20042. set: function (value) {
  20043. if (this._useVertexColors === value) {
  20044. return;
  20045. }
  20046. this._useVertexColors = value;
  20047. this._markSubMeshesAsAttributesDirty();
  20048. },
  20049. enumerable: true,
  20050. configurable: true
  20051. });
  20052. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20053. /**
  20054. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20055. */
  20056. get: function () {
  20057. return this._computeBonesUsingShaders;
  20058. },
  20059. set: function (value) {
  20060. if (this._computeBonesUsingShaders === value) {
  20061. return;
  20062. }
  20063. this._computeBonesUsingShaders = value;
  20064. this._markSubMeshesAsAttributesDirty();
  20065. },
  20066. enumerable: true,
  20067. configurable: true
  20068. });
  20069. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20070. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20071. get: function () {
  20072. return this._numBoneInfluencers;
  20073. },
  20074. set: function (value) {
  20075. if (this._numBoneInfluencers === value) {
  20076. return;
  20077. }
  20078. this._numBoneInfluencers = value;
  20079. this._markSubMeshesAsAttributesDirty();
  20080. },
  20081. enumerable: true,
  20082. configurable: true
  20083. });
  20084. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20085. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20086. get: function () {
  20087. return this._applyFog;
  20088. },
  20089. set: function (value) {
  20090. if (this._applyFog === value) {
  20091. return;
  20092. }
  20093. this._applyFog = value;
  20094. this._markSubMeshesAsMiscDirty();
  20095. },
  20096. enumerable: true,
  20097. configurable: true
  20098. });
  20099. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20100. /**
  20101. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20102. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20103. */
  20104. get: function () {
  20105. return this._layerMask;
  20106. },
  20107. set: function (value) {
  20108. if (value === this._layerMask) {
  20109. return;
  20110. }
  20111. this._layerMask = value;
  20112. this._resyncLightSources();
  20113. },
  20114. enumerable: true,
  20115. configurable: true
  20116. });
  20117. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20118. /**
  20119. * Gets or sets a collision mask used to mask collisions (default is -1).
  20120. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20121. */
  20122. get: function () {
  20123. return this._collisionMask;
  20124. },
  20125. set: function (mask) {
  20126. this._collisionMask = !isNaN(mask) ? mask : -1;
  20127. },
  20128. enumerable: true,
  20129. configurable: true
  20130. });
  20131. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20132. /**
  20133. * Gets or sets the current collision group mask (-1 by default).
  20134. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20135. */
  20136. get: function () {
  20137. return this._collisionGroup;
  20138. },
  20139. set: function (mask) {
  20140. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20141. },
  20142. enumerable: true,
  20143. configurable: true
  20144. });
  20145. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20146. /** @hidden */
  20147. get: function () {
  20148. return null;
  20149. },
  20150. enumerable: true,
  20151. configurable: true
  20152. });
  20153. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20154. get: function () {
  20155. return this._skeleton;
  20156. },
  20157. /**
  20158. * Gets or sets a skeleton to apply skining transformations
  20159. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20160. */
  20161. set: function (value) {
  20162. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20163. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20164. }
  20165. if (value && value.needInitialSkinMatrix) {
  20166. value._registerMeshWithPoseMatrix(this);
  20167. }
  20168. this._skeleton = value;
  20169. if (!this._skeleton) {
  20170. this._bonesTransformMatrices = null;
  20171. }
  20172. this._markSubMeshesAsAttributesDirty();
  20173. },
  20174. enumerable: true,
  20175. configurable: true
  20176. });
  20177. /**
  20178. * Returns the string "AbstractMesh"
  20179. * @returns "AbstractMesh"
  20180. */
  20181. AbstractMesh.prototype.getClassName = function () {
  20182. return "AbstractMesh";
  20183. };
  20184. /**
  20185. * Gets a string representation of the current mesh
  20186. * @param fullDetails defines a boolean indicating if full details must be included
  20187. * @returns a string representation of the current mesh
  20188. */
  20189. AbstractMesh.prototype.toString = function (fullDetails) {
  20190. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20191. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20192. if (this._skeleton) {
  20193. ret += ", skeleton: " + this._skeleton.name;
  20194. }
  20195. if (fullDetails) {
  20196. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20197. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20198. }
  20199. return ret;
  20200. };
  20201. /** @hidden */
  20202. AbstractMesh.prototype._rebuild = function () {
  20203. this.onRebuildObservable.notifyObservers(this);
  20204. if (this._occlusionQuery) {
  20205. this._occlusionQuery = null;
  20206. }
  20207. if (!this.subMeshes) {
  20208. return;
  20209. }
  20210. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20211. var subMesh = _a[_i];
  20212. subMesh._rebuild();
  20213. }
  20214. };
  20215. /** @hidden */
  20216. AbstractMesh.prototype._resyncLightSources = function () {
  20217. this._lightSources.length = 0;
  20218. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20219. var light = _a[_i];
  20220. if (!light.isEnabled()) {
  20221. continue;
  20222. }
  20223. if (light.canAffectMesh(this)) {
  20224. this._lightSources.push(light);
  20225. }
  20226. }
  20227. this._markSubMeshesAsLightDirty();
  20228. };
  20229. /** @hidden */
  20230. AbstractMesh.prototype._resyncLighSource = function (light) {
  20231. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20232. var index = this._lightSources.indexOf(light);
  20233. if (index === -1) {
  20234. if (!isIn) {
  20235. return;
  20236. }
  20237. this._lightSources.push(light);
  20238. }
  20239. else {
  20240. if (isIn) {
  20241. return;
  20242. }
  20243. this._lightSources.splice(index, 1);
  20244. }
  20245. this._markSubMeshesAsLightDirty();
  20246. };
  20247. /** @hidden */
  20248. AbstractMesh.prototype._unBindEffect = function () {
  20249. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20250. var subMesh = _a[_i];
  20251. subMesh.setEffect(null);
  20252. }
  20253. };
  20254. /** @hidden */
  20255. AbstractMesh.prototype._removeLightSource = function (light) {
  20256. var index = this._lightSources.indexOf(light);
  20257. if (index === -1) {
  20258. return;
  20259. }
  20260. this._lightSources.splice(index, 1);
  20261. this._markSubMeshesAsLightDirty();
  20262. };
  20263. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20264. if (!this.subMeshes) {
  20265. return;
  20266. }
  20267. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20268. var subMesh = _a[_i];
  20269. if (subMesh._materialDefines) {
  20270. func(subMesh._materialDefines);
  20271. }
  20272. }
  20273. };
  20274. /** @hidden */
  20275. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20276. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20277. };
  20278. /** @hidden */
  20279. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20280. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20281. };
  20282. /** @hidden */
  20283. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20284. if (!this.subMeshes) {
  20285. return;
  20286. }
  20287. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20288. var subMesh = _a[_i];
  20289. var material = subMesh.getMaterial();
  20290. if (material) {
  20291. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20292. }
  20293. }
  20294. };
  20295. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20296. /**
  20297. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20298. */
  20299. get: function () {
  20300. return this._scaling;
  20301. },
  20302. set: function (newScaling) {
  20303. this._scaling = newScaling;
  20304. if (this.physicsImpostor) {
  20305. this.physicsImpostor.forceUpdate();
  20306. }
  20307. },
  20308. enumerable: true,
  20309. configurable: true
  20310. });
  20311. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20312. // Methods
  20313. /**
  20314. * Returns true if the mesh is blocked. Implemented by child classes
  20315. */
  20316. get: function () {
  20317. return false;
  20318. },
  20319. enumerable: true,
  20320. configurable: true
  20321. });
  20322. /**
  20323. * Returns the mesh itself by default. Implemented by child classes
  20324. * @param camera defines the camera to use to pick the right LOD level
  20325. * @returns the currentAbstractMesh
  20326. */
  20327. AbstractMesh.prototype.getLOD = function (camera) {
  20328. return this;
  20329. };
  20330. /**
  20331. * Returns 0 by default. Implemented by child classes
  20332. * @returns an integer
  20333. */
  20334. AbstractMesh.prototype.getTotalVertices = function () {
  20335. return 0;
  20336. };
  20337. /**
  20338. * Returns null by default. Implemented by child classes
  20339. * @returns null
  20340. */
  20341. AbstractMesh.prototype.getIndices = function () {
  20342. return null;
  20343. };
  20344. /**
  20345. * Returns the array of the requested vertex data kind. Implemented by child classes
  20346. * @param kind defines the vertex data kind to use
  20347. * @returns null
  20348. */
  20349. AbstractMesh.prototype.getVerticesData = function (kind) {
  20350. return null;
  20351. };
  20352. /**
  20353. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20354. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20355. * Note that a new underlying VertexBuffer object is created each call.
  20356. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20357. * @param kind defines vertex data kind:
  20358. * * BABYLON.VertexBuffer.PositionKind
  20359. * * BABYLON.VertexBuffer.UVKind
  20360. * * BABYLON.VertexBuffer.UV2Kind
  20361. * * BABYLON.VertexBuffer.UV3Kind
  20362. * * BABYLON.VertexBuffer.UV4Kind
  20363. * * BABYLON.VertexBuffer.UV5Kind
  20364. * * BABYLON.VertexBuffer.UV6Kind
  20365. * * BABYLON.VertexBuffer.ColorKind
  20366. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20367. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20368. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20369. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20370. * @param data defines the data source
  20371. * @param updatable defines if the data must be flagged as updatable (or static)
  20372. * @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
  20373. * @returns the current mesh
  20374. */
  20375. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20376. return this;
  20377. };
  20378. /**
  20379. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20380. * If the mesh has no geometry, it is simply returned as it is.
  20381. * @param kind defines vertex data kind:
  20382. * * BABYLON.VertexBuffer.PositionKind
  20383. * * BABYLON.VertexBuffer.UVKind
  20384. * * BABYLON.VertexBuffer.UV2Kind
  20385. * * BABYLON.VertexBuffer.UV3Kind
  20386. * * BABYLON.VertexBuffer.UV4Kind
  20387. * * BABYLON.VertexBuffer.UV5Kind
  20388. * * BABYLON.VertexBuffer.UV6Kind
  20389. * * BABYLON.VertexBuffer.ColorKind
  20390. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20391. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20392. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20393. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20394. * @param data defines the data source
  20395. * @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
  20396. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20397. * @returns the current mesh
  20398. */
  20399. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20400. return this;
  20401. };
  20402. /**
  20403. * Sets the mesh indices,
  20404. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20405. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20406. * @param totalVertices Defines the total number of vertices
  20407. * @returns the current mesh
  20408. */
  20409. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20410. return this;
  20411. };
  20412. /**
  20413. * Gets a boolean indicating if specific vertex data is present
  20414. * @param kind defines the vertex data kind to use
  20415. * @returns true is data kind is present
  20416. */
  20417. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20418. return false;
  20419. };
  20420. /**
  20421. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20422. * @returns a BoundingInfo
  20423. */
  20424. AbstractMesh.prototype.getBoundingInfo = function () {
  20425. if (this._masterMesh) {
  20426. return this._masterMesh.getBoundingInfo();
  20427. }
  20428. if (!this._boundingInfo) {
  20429. // this._boundingInfo is being created here
  20430. this._updateBoundingInfo();
  20431. }
  20432. // cannot be null.
  20433. return this._boundingInfo;
  20434. };
  20435. /**
  20436. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20437. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20438. * @returns the current mesh
  20439. */
  20440. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20441. if (includeDescendants === void 0) { includeDescendants = true; }
  20442. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20443. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20444. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20445. if (maxDimension === 0) {
  20446. return this;
  20447. }
  20448. var scale = 1 / maxDimension;
  20449. this.scaling.scaleInPlace(scale);
  20450. return this;
  20451. };
  20452. /**
  20453. * Overwrite the current bounding info
  20454. * @param boundingInfo defines the new bounding info
  20455. * @returns the current mesh
  20456. */
  20457. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20458. this._boundingInfo = boundingInfo;
  20459. return this;
  20460. };
  20461. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20462. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20463. get: function () {
  20464. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20465. },
  20466. enumerable: true,
  20467. configurable: true
  20468. });
  20469. /** @hidden */
  20470. AbstractMesh.prototype._preActivate = function () {
  20471. };
  20472. /** @hidden */
  20473. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20474. };
  20475. /** @hidden */
  20476. AbstractMesh.prototype._activate = function (renderId) {
  20477. this._renderId = renderId;
  20478. };
  20479. /**
  20480. * Gets the current world matrix
  20481. * @returns a Matrix
  20482. */
  20483. AbstractMesh.prototype.getWorldMatrix = function () {
  20484. if (this._masterMesh) {
  20485. return this._masterMesh.getWorldMatrix();
  20486. }
  20487. return _super.prototype.getWorldMatrix.call(this);
  20488. };
  20489. /** @hidden */
  20490. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20491. if (this._masterMesh) {
  20492. return this._masterMesh._getWorldMatrixDeterminant();
  20493. }
  20494. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20495. };
  20496. // ================================== Point of View Movement =================================
  20497. /**
  20498. * Perform relative position change from the point of view of behind the front of the mesh.
  20499. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20500. * Supports definition of mesh facing forward or backward
  20501. * @param amountRight defines the distance on the right axis
  20502. * @param amountUp defines the distance on the up axis
  20503. * @param amountForward defines the distance on the forward axis
  20504. * @returns the current mesh
  20505. */
  20506. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20507. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20508. return this;
  20509. };
  20510. /**
  20511. * Calculate relative position change from the point of view of behind the front of the mesh.
  20512. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20513. * Supports definition of mesh facing forward or backward
  20514. * @param amountRight defines the distance on the right axis
  20515. * @param amountUp defines the distance on the up axis
  20516. * @param amountForward defines the distance on the forward axis
  20517. * @returns the new displacement vector
  20518. */
  20519. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20520. var rotMatrix = new BABYLON.Matrix();
  20521. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20522. rotQuaternion.toRotationMatrix(rotMatrix);
  20523. var translationDelta = BABYLON.Vector3.Zero();
  20524. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20525. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20526. return translationDelta;
  20527. };
  20528. // ================================== Point of View Rotation =================================
  20529. /**
  20530. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20531. * Supports definition of mesh facing forward or backward
  20532. * @param flipBack defines the flip
  20533. * @param twirlClockwise defines the twirl
  20534. * @param tiltRight defines the tilt
  20535. * @returns the current mesh
  20536. */
  20537. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20538. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20539. return this;
  20540. };
  20541. /**
  20542. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20543. * Supports definition of mesh facing forward or backward.
  20544. * @param flipBack defines the flip
  20545. * @param twirlClockwise defines the twirl
  20546. * @param tiltRight defines the tilt
  20547. * @returns the new rotation vector
  20548. */
  20549. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20550. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20551. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20552. };
  20553. /**
  20554. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20555. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20556. * @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
  20557. * @returns the new bounding vectors
  20558. */
  20559. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20560. if (includeDescendants === void 0) { includeDescendants = true; }
  20561. if (predicate === void 0) { predicate = null; }
  20562. // Ensures that all world matrix will be recomputed.
  20563. this.getScene().incrementRenderId();
  20564. this.computeWorldMatrix(true);
  20565. var min;
  20566. var max;
  20567. var boundingInfo = this.getBoundingInfo();
  20568. if (!this.subMeshes) {
  20569. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20570. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20571. }
  20572. else {
  20573. min = boundingInfo.boundingBox.minimumWorld;
  20574. max = boundingInfo.boundingBox.maximumWorld;
  20575. }
  20576. if (includeDescendants) {
  20577. var descendants = this.getDescendants(false);
  20578. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20579. var descendant = descendants_1[_i];
  20580. var childMesh = descendant;
  20581. childMesh.computeWorldMatrix(true);
  20582. // Filters meshes based on custom predicate function.
  20583. if (predicate && !predicate(childMesh)) {
  20584. continue;
  20585. }
  20586. //make sure we have the needed params to get mix and max
  20587. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20588. continue;
  20589. }
  20590. var childBoundingInfo = childMesh.getBoundingInfo();
  20591. var boundingBox = childBoundingInfo.boundingBox;
  20592. var minBox = boundingBox.minimumWorld;
  20593. var maxBox = boundingBox.maximumWorld;
  20594. BABYLON.Tools.CheckExtends(minBox, min, max);
  20595. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20596. }
  20597. }
  20598. return {
  20599. min: min,
  20600. max: max
  20601. };
  20602. };
  20603. /** @hidden */
  20604. AbstractMesh.prototype._updateBoundingInfo = function () {
  20605. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20606. this._boundingInfo.update(this.worldMatrixFromCache);
  20607. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20608. return this;
  20609. };
  20610. /** @hidden */
  20611. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20612. if (!this.subMeshes) {
  20613. return this;
  20614. }
  20615. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20616. var subMesh = this.subMeshes[subIndex];
  20617. if (!subMesh.IsGlobal) {
  20618. subMesh.updateBoundingInfo(matrix);
  20619. }
  20620. }
  20621. return this;
  20622. };
  20623. /** @hidden */
  20624. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20625. // Bounding info
  20626. this._updateBoundingInfo();
  20627. };
  20628. /**
  20629. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20630. * A mesh is in the frustum if its bounding box intersects the frustum
  20631. * @param frustumPlanes defines the frustum to test
  20632. * @returns true if the mesh is in the frustum planes
  20633. */
  20634. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20635. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20636. };
  20637. /**
  20638. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20639. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20640. * @param frustumPlanes defines the frustum to test
  20641. * @returns true if the mesh is completely in the frustum planes
  20642. */
  20643. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20644. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20645. };
  20646. /**
  20647. * True if the mesh intersects another mesh or a SolidParticle object
  20648. * @param mesh defines a target mesh or SolidParticle to test
  20649. * @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)
  20650. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20651. * @returns true if there is an intersection
  20652. */
  20653. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20654. if (precise === void 0) { precise = false; }
  20655. if (!this._boundingInfo || !mesh._boundingInfo) {
  20656. return false;
  20657. }
  20658. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20659. return true;
  20660. }
  20661. if (includeDescendants) {
  20662. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20663. var child = _a[_i];
  20664. if (child.intersectsMesh(mesh, precise, true)) {
  20665. return true;
  20666. }
  20667. }
  20668. }
  20669. return false;
  20670. };
  20671. /**
  20672. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20673. * @param point defines the point to test
  20674. * @returns true if there is an intersection
  20675. */
  20676. AbstractMesh.prototype.intersectsPoint = function (point) {
  20677. if (!this._boundingInfo) {
  20678. return false;
  20679. }
  20680. return this._boundingInfo.intersectsPoint(point);
  20681. };
  20682. /**
  20683. * Gets the position of the current mesh in camera space
  20684. * @param camera defines the camera to use
  20685. * @returns a position
  20686. */
  20687. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20688. if (camera === void 0) { camera = null; }
  20689. if (!camera) {
  20690. camera = this.getScene().activeCamera;
  20691. }
  20692. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20693. };
  20694. /**
  20695. * Returns the distance from the mesh to the active camera
  20696. * @param camera defines the camera to use
  20697. * @returns the distance
  20698. */
  20699. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20700. if (camera === void 0) { camera = null; }
  20701. if (!camera) {
  20702. camera = this.getScene().activeCamera;
  20703. }
  20704. return this.absolutePosition.subtract(camera.position).length();
  20705. };
  20706. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20707. // Collisions
  20708. /**
  20709. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20710. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20711. */
  20712. get: function () {
  20713. return this._checkCollisions;
  20714. },
  20715. set: function (collisionEnabled) {
  20716. this._checkCollisions = collisionEnabled;
  20717. if (this.getScene().workerCollisions) {
  20718. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20719. }
  20720. },
  20721. enumerable: true,
  20722. configurable: true
  20723. });
  20724. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20725. /**
  20726. * Gets Collider object used to compute collisions (not physics)
  20727. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20728. */
  20729. get: function () {
  20730. return this._collider;
  20731. },
  20732. enumerable: true,
  20733. configurable: true
  20734. });
  20735. /**
  20736. * Move the mesh using collision engine
  20737. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20738. * @param displacement defines the requested displacement vector
  20739. * @returns the current mesh
  20740. */
  20741. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20742. var globalPosition = this.getAbsolutePosition();
  20743. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20744. if (!this._collider) {
  20745. this._collider = new BABYLON.Collider();
  20746. }
  20747. this._collider._radius = this.ellipsoid;
  20748. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20749. return this;
  20750. };
  20751. // Collisions
  20752. /** @hidden */
  20753. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20754. this._generatePointsArray();
  20755. if (!this._positions) {
  20756. return this;
  20757. }
  20758. // Transformation
  20759. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20760. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20761. subMesh._lastColliderWorldVertices = [];
  20762. subMesh._trianglePlanes = [];
  20763. var start = subMesh.verticesStart;
  20764. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20765. for (var i = start; i < end; i++) {
  20766. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20767. }
  20768. }
  20769. // Collide
  20770. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20771. if (collider.collisionFound) {
  20772. collider.collidedMesh = this;
  20773. }
  20774. return this;
  20775. };
  20776. /** @hidden */
  20777. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20778. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  20779. var len = subMeshes.length;
  20780. for (var index = 0; index < len; index++) {
  20781. var subMesh = subMeshes.data[index];
  20782. // Bounding test
  20783. if (len > 1 && !subMesh._checkCollision(collider))
  20784. continue;
  20785. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20786. }
  20787. return this;
  20788. };
  20789. /** @hidden */
  20790. AbstractMesh.prototype._checkCollision = function (collider) {
  20791. // Bounding box test
  20792. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20793. return this;
  20794. // Transformation matrix
  20795. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20796. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20797. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20798. return this;
  20799. };
  20800. // Picking
  20801. /** @hidden */
  20802. AbstractMesh.prototype._generatePointsArray = function () {
  20803. return false;
  20804. };
  20805. /**
  20806. * Checks if the passed Ray intersects with the mesh
  20807. * @param ray defines the ray to use
  20808. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20809. * @returns the picking info
  20810. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20811. */
  20812. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20813. var pickingInfo = new BABYLON.PickingInfo();
  20814. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20815. return pickingInfo;
  20816. }
  20817. if (!this._generatePointsArray()) {
  20818. return pickingInfo;
  20819. }
  20820. var intersectInfo = null;
  20821. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  20822. var len = subMeshes.length;
  20823. for (var index = 0; index < len; index++) {
  20824. var subMesh = subMeshes.data[index];
  20825. // Bounding test
  20826. if (len > 1 && !subMesh.canIntersects(ray))
  20827. continue;
  20828. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20829. if (currentIntersectInfo) {
  20830. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20831. intersectInfo = currentIntersectInfo;
  20832. intersectInfo.subMeshId = index;
  20833. if (fastCheck) {
  20834. break;
  20835. }
  20836. }
  20837. }
  20838. }
  20839. if (intersectInfo) {
  20840. // Get picked point
  20841. var world = this.getWorldMatrix();
  20842. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20843. var direction = ray.direction.clone();
  20844. direction = direction.scale(intersectInfo.distance);
  20845. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20846. var pickedPoint = worldOrigin.add(worldDirection);
  20847. // Return result
  20848. pickingInfo.hit = true;
  20849. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20850. pickingInfo.pickedPoint = pickedPoint;
  20851. pickingInfo.pickedMesh = this;
  20852. pickingInfo.bu = intersectInfo.bu || 0;
  20853. pickingInfo.bv = intersectInfo.bv || 0;
  20854. pickingInfo.faceId = intersectInfo.faceId;
  20855. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20856. return pickingInfo;
  20857. }
  20858. return pickingInfo;
  20859. };
  20860. /**
  20861. * Clones the current mesh
  20862. * @param name defines the mesh name
  20863. * @param newParent defines the new mesh parent
  20864. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20865. * @returns the new mesh
  20866. */
  20867. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20868. return null;
  20869. };
  20870. /**
  20871. * Disposes all the submeshes of the current meshnp
  20872. * @returns the current mesh
  20873. */
  20874. AbstractMesh.prototype.releaseSubMeshes = function () {
  20875. if (this.subMeshes) {
  20876. while (this.subMeshes.length) {
  20877. this.subMeshes[0].dispose();
  20878. }
  20879. }
  20880. else {
  20881. this.subMeshes = new Array();
  20882. }
  20883. return this;
  20884. };
  20885. /**
  20886. * Releases resources associated with this abstract mesh.
  20887. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20888. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20889. */
  20890. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20891. var _this = this;
  20892. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20893. var index;
  20894. // Smart Array Retainers.
  20895. this.getScene().freeActiveMeshes();
  20896. this.getScene().freeRenderingGroups();
  20897. // Action manager
  20898. if (this.actionManager !== undefined && this.actionManager !== null) {
  20899. this.actionManager.dispose();
  20900. this.actionManager = null;
  20901. }
  20902. // Skeleton
  20903. this._skeleton = null;
  20904. // Intersections in progress
  20905. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20906. var other = this._intersectionsInProgress[index];
  20907. var pos = other._intersectionsInProgress.indexOf(this);
  20908. other._intersectionsInProgress.splice(pos, 1);
  20909. }
  20910. this._intersectionsInProgress = [];
  20911. // Lights
  20912. var lights = this.getScene().lights;
  20913. lights.forEach(function (light) {
  20914. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20915. if (meshIndex !== -1) {
  20916. light.includedOnlyMeshes.splice(meshIndex, 1);
  20917. }
  20918. meshIndex = light.excludedMeshes.indexOf(_this);
  20919. if (meshIndex !== -1) {
  20920. light.excludedMeshes.splice(meshIndex, 1);
  20921. }
  20922. // Shadow generators
  20923. var generator = light.getShadowGenerator();
  20924. if (generator) {
  20925. var shadowMap = generator.getShadowMap();
  20926. if (shadowMap && shadowMap.renderList) {
  20927. meshIndex = shadowMap.renderList.indexOf(_this);
  20928. if (meshIndex !== -1) {
  20929. shadowMap.renderList.splice(meshIndex, 1);
  20930. }
  20931. }
  20932. }
  20933. });
  20934. // SubMeshes
  20935. if (this.getClassName() !== "InstancedMesh") {
  20936. this.releaseSubMeshes();
  20937. }
  20938. // Query
  20939. var engine = this.getScene().getEngine();
  20940. if (this._occlusionQuery) {
  20941. this._isOcclusionQueryInProgress = false;
  20942. engine.deleteQuery(this._occlusionQuery);
  20943. this._occlusionQuery = null;
  20944. }
  20945. // Engine
  20946. engine.wipeCaches();
  20947. // Remove from scene
  20948. this.getScene().removeMesh(this);
  20949. if (disposeMaterialAndTextures) {
  20950. if (this.material) {
  20951. this.material.dispose(false, true);
  20952. }
  20953. }
  20954. if (!doNotRecurse) {
  20955. // Particles
  20956. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20957. if (this.getScene().particleSystems[index].emitter === this) {
  20958. this.getScene().particleSystems[index].dispose();
  20959. index--;
  20960. }
  20961. }
  20962. }
  20963. // facet data
  20964. if (this._facetDataEnabled) {
  20965. this.disableFacetData();
  20966. }
  20967. this.onAfterWorldMatrixUpdateObservable.clear();
  20968. this.onCollideObservable.clear();
  20969. this.onCollisionPositionChangeObservable.clear();
  20970. this.onRebuildObservable.clear();
  20971. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20972. };
  20973. /**
  20974. * Adds the passed mesh as a child to the current mesh
  20975. * @param mesh defines the child mesh
  20976. * @returns the current mesh
  20977. */
  20978. AbstractMesh.prototype.addChild = function (mesh) {
  20979. mesh.setParent(this);
  20980. return this;
  20981. };
  20982. /**
  20983. * Removes the passed mesh from the current mesh children list
  20984. * @param mesh defines the child mesh
  20985. * @returns the current mesh
  20986. */
  20987. AbstractMesh.prototype.removeChild = function (mesh) {
  20988. mesh.setParent(null);
  20989. return this;
  20990. };
  20991. // Facet data
  20992. /** @hidden */
  20993. AbstractMesh.prototype._initFacetData = function () {
  20994. if (!this._facetNormals) {
  20995. this._facetNormals = new Array();
  20996. }
  20997. if (!this._facetPositions) {
  20998. this._facetPositions = new Array();
  20999. }
  21000. if (!this._facetPartitioning) {
  21001. this._facetPartitioning = new Array();
  21002. }
  21003. this._facetNb = (this.getIndices().length / 3) | 0;
  21004. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21005. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21006. for (var f = 0; f < this._facetNb; f++) {
  21007. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21008. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21009. }
  21010. this._facetDataEnabled = true;
  21011. return this;
  21012. };
  21013. /**
  21014. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21015. * This method can be called within the render loop.
  21016. * 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
  21017. * @returns the current mesh
  21018. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21019. */
  21020. AbstractMesh.prototype.updateFacetData = function () {
  21021. if (!this._facetDataEnabled) {
  21022. this._initFacetData();
  21023. }
  21024. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21025. var indices = this.getIndices();
  21026. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21027. var bInfo = this.getBoundingInfo();
  21028. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21029. // init arrays, matrix and sort function on first call
  21030. this._facetDepthSortEnabled = true;
  21031. if (indices instanceof Uint16Array) {
  21032. this._depthSortedIndices = new Uint16Array(indices);
  21033. }
  21034. else if (indices instanceof Uint32Array) {
  21035. this._depthSortedIndices = new Uint32Array(indices);
  21036. }
  21037. else {
  21038. var needs32bits = false;
  21039. for (var i = 0; i < indices.length; i++) {
  21040. if (indices[i] > 65535) {
  21041. needs32bits = true;
  21042. break;
  21043. }
  21044. }
  21045. if (needs32bits) {
  21046. this._depthSortedIndices = new Uint32Array(indices);
  21047. }
  21048. else {
  21049. this._depthSortedIndices = new Uint16Array(indices);
  21050. }
  21051. }
  21052. this._facetDepthSortFunction = function (f1, f2) {
  21053. return (f2.sqDistance - f1.sqDistance);
  21054. };
  21055. if (!this._facetDepthSortFrom) {
  21056. var camera = this.getScene().activeCamera;
  21057. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21058. }
  21059. this._depthSortedFacets = [];
  21060. for (var f = 0; f < this._facetNb; f++) {
  21061. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21062. this._depthSortedFacets.push(depthSortedFacet);
  21063. }
  21064. this._invertedMatrix = BABYLON.Matrix.Identity();
  21065. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21066. }
  21067. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21068. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21069. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21070. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21071. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21072. this._subDiv.max = this._partitioningSubdivisions;
  21073. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21074. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21075. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21076. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21077. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21078. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21079. // set the parameters for ComputeNormals()
  21080. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21081. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21082. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21083. this._facetParameters.bInfo = bInfo;
  21084. this._facetParameters.bbSize = this._bbSize;
  21085. this._facetParameters.subDiv = this._subDiv;
  21086. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21087. this._facetParameters.depthSort = this._facetDepthSort;
  21088. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21089. this.computeWorldMatrix(true);
  21090. this._worldMatrix.invertToRef(this._invertedMatrix);
  21091. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21092. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21093. }
  21094. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21095. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21096. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21097. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21098. var l = (this._depthSortedIndices.length / 3) | 0;
  21099. for (var f = 0; f < l; f++) {
  21100. var sind = this._depthSortedFacets[f].ind;
  21101. this._depthSortedIndices[f * 3] = indices[sind];
  21102. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21103. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21104. }
  21105. this.updateIndices(this._depthSortedIndices);
  21106. }
  21107. return this;
  21108. };
  21109. /**
  21110. * Returns the facetLocalNormals array.
  21111. * The normals are expressed in the mesh local spac
  21112. * @returns an array of Vector3
  21113. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21114. */
  21115. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21116. if (!this._facetNormals) {
  21117. this.updateFacetData();
  21118. }
  21119. return this._facetNormals;
  21120. };
  21121. /**
  21122. * Returns the facetLocalPositions array.
  21123. * The facet positions are expressed in the mesh local space
  21124. * @returns an array of Vector3
  21125. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21126. */
  21127. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21128. if (!this._facetPositions) {
  21129. this.updateFacetData();
  21130. }
  21131. return this._facetPositions;
  21132. };
  21133. /**
  21134. * Returns the facetLocalPartioning array
  21135. * @returns an array of array of numbers
  21136. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21137. */
  21138. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21139. if (!this._facetPartitioning) {
  21140. this.updateFacetData();
  21141. }
  21142. return this._facetPartitioning;
  21143. };
  21144. /**
  21145. * Returns the i-th facet position in the world system.
  21146. * This method allocates a new Vector3 per call
  21147. * @param i defines the facet index
  21148. * @returns a new Vector3
  21149. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21150. */
  21151. AbstractMesh.prototype.getFacetPosition = function (i) {
  21152. var pos = BABYLON.Vector3.Zero();
  21153. this.getFacetPositionToRef(i, pos);
  21154. return pos;
  21155. };
  21156. /**
  21157. * Sets the reference Vector3 with the i-th facet position in the world system
  21158. * @param i defines the facet index
  21159. * @param ref defines the target vector
  21160. * @returns the current mesh
  21161. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21162. */
  21163. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21164. var localPos = (this.getFacetLocalPositions())[i];
  21165. var world = this.getWorldMatrix();
  21166. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21167. return this;
  21168. };
  21169. /**
  21170. * Returns the i-th facet normal in the world system.
  21171. * This method allocates a new Vector3 per call
  21172. * @param i defines the facet index
  21173. * @returns a new Vector3
  21174. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21175. */
  21176. AbstractMesh.prototype.getFacetNormal = function (i) {
  21177. var norm = BABYLON.Vector3.Zero();
  21178. this.getFacetNormalToRef(i, norm);
  21179. return norm;
  21180. };
  21181. /**
  21182. * Sets the reference Vector3 with the i-th facet normal in the world system
  21183. * @param i defines the facet index
  21184. * @param ref defines the target vector
  21185. * @returns the current mesh
  21186. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21187. */
  21188. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21189. var localNorm = (this.getFacetLocalNormals())[i];
  21190. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21191. return this;
  21192. };
  21193. /**
  21194. * 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)
  21195. * @param x defines x coordinate
  21196. * @param y defines y coordinate
  21197. * @param z defines z coordinate
  21198. * @returns the array of facet indexes
  21199. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21200. */
  21201. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21202. var bInfo = this.getBoundingInfo();
  21203. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21204. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21205. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21206. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21207. return null;
  21208. }
  21209. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21210. };
  21211. /**
  21212. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21213. * @param projected sets as the (x,y,z) world projection on the facet
  21214. * @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
  21215. * @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
  21216. * @param x defines x coordinate
  21217. * @param y defines y coordinate
  21218. * @param z defines z coordinate
  21219. * @returns the face index if found (or null instead)
  21220. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21221. */
  21222. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21223. if (checkFace === void 0) { checkFace = false; }
  21224. if (facing === void 0) { facing = true; }
  21225. var world = this.getWorldMatrix();
  21226. var invMat = BABYLON.Tmp.Matrix[5];
  21227. world.invertToRef(invMat);
  21228. var invVect = BABYLON.Tmp.Vector3[8];
  21229. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21230. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21231. if (projected) {
  21232. // tranform the local computed projected vector to world coordinates
  21233. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21234. }
  21235. return closest;
  21236. };
  21237. /**
  21238. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21239. * @param projected sets as the (x,y,z) local projection on the facet
  21240. * @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
  21241. * @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
  21242. * @param x defines x coordinate
  21243. * @param y defines y coordinate
  21244. * @param z defines z coordinate
  21245. * @returns the face index if found (or null instead)
  21246. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21247. */
  21248. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21249. if (checkFace === void 0) { checkFace = false; }
  21250. if (facing === void 0) { facing = true; }
  21251. var closest = null;
  21252. var tmpx = 0.0;
  21253. var tmpy = 0.0;
  21254. var tmpz = 0.0;
  21255. var d = 0.0; // tmp dot facet normal * facet position
  21256. var t0 = 0.0;
  21257. var projx = 0.0;
  21258. var projy = 0.0;
  21259. var projz = 0.0;
  21260. // Get all the facets in the same partitioning block than (x, y, z)
  21261. var facetPositions = this.getFacetLocalPositions();
  21262. var facetNormals = this.getFacetLocalNormals();
  21263. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21264. if (!facetsInBlock) {
  21265. return null;
  21266. }
  21267. // Get the closest facet to (x, y, z)
  21268. var shortest = Number.MAX_VALUE; // init distance vars
  21269. var tmpDistance = shortest;
  21270. var fib; // current facet in the block
  21271. var norm; // current facet normal
  21272. var p0; // current facet barycenter position
  21273. // loop on all the facets in the current partitioning block
  21274. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21275. fib = facetsInBlock[idx];
  21276. norm = facetNormals[fib];
  21277. p0 = facetPositions[fib];
  21278. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21279. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21280. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21281. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21282. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21283. projx = x + norm.x * t0;
  21284. projy = y + norm.y * t0;
  21285. projz = z + norm.z * t0;
  21286. tmpx = projx - x;
  21287. tmpy = projy - y;
  21288. tmpz = projz - z;
  21289. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21290. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21291. shortest = tmpDistance;
  21292. closest = fib;
  21293. if (projected) {
  21294. projected.x = projx;
  21295. projected.y = projy;
  21296. projected.z = projz;
  21297. }
  21298. }
  21299. }
  21300. }
  21301. return closest;
  21302. };
  21303. /**
  21304. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21305. * @returns the parameters
  21306. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21307. */
  21308. AbstractMesh.prototype.getFacetDataParameters = function () {
  21309. return this._facetParameters;
  21310. };
  21311. /**
  21312. * Disables the feature FacetData and frees the related memory
  21313. * @returns the current mesh
  21314. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21315. */
  21316. AbstractMesh.prototype.disableFacetData = function () {
  21317. if (this._facetDataEnabled) {
  21318. this._facetDataEnabled = false;
  21319. this._facetPositions = new Array();
  21320. this._facetNormals = new Array();
  21321. this._facetPartitioning = new Array();
  21322. this._facetParameters = null;
  21323. this._depthSortedIndices = new Uint32Array(0);
  21324. }
  21325. return this;
  21326. };
  21327. /**
  21328. * Updates the AbstractMesh indices array
  21329. * @param indices defines the data source
  21330. * @returns the current mesh
  21331. */
  21332. AbstractMesh.prototype.updateIndices = function (indices) {
  21333. return this;
  21334. };
  21335. /**
  21336. * Creates new normals data for the mesh
  21337. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21338. * @returns the current mesh
  21339. */
  21340. AbstractMesh.prototype.createNormals = function (updatable) {
  21341. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21342. var indices = this.getIndices();
  21343. var normals;
  21344. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21345. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21346. }
  21347. else {
  21348. normals = [];
  21349. }
  21350. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21351. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21352. return this;
  21353. };
  21354. /**
  21355. * Align the mesh with a normal
  21356. * @param normal defines the normal to use
  21357. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21358. * @returns the current mesh
  21359. */
  21360. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21361. if (!upDirection) {
  21362. upDirection = BABYLON.Axis.Y;
  21363. }
  21364. var axisX = BABYLON.Tmp.Vector3[0];
  21365. var axisZ = BABYLON.Tmp.Vector3[1];
  21366. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21367. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21368. if (this.rotationQuaternion) {
  21369. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21370. }
  21371. else {
  21372. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21373. }
  21374. return this;
  21375. };
  21376. /** @hidden */
  21377. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21378. this._isOccluded = false;
  21379. };
  21380. /** No occlusion */
  21381. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21382. /** Occlusion set to optimisitic */
  21383. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21384. /** Occlusion set to strict */
  21385. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21386. /** Use an accurante occlusion algorithm */
  21387. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21388. /** Use a conservative occlusion algorithm */
  21389. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21390. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21391. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21392. /** Culling strategy with bounding sphere only and then frustum culling */
  21393. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21394. return AbstractMesh;
  21395. }(BABYLON.TransformNode));
  21396. BABYLON.AbstractMesh = AbstractMesh;
  21397. })(BABYLON || (BABYLON = {}));
  21398. //# sourceMappingURL=babylon.abstractMesh.js.map
  21399. var BABYLON;
  21400. (function (BABYLON) {
  21401. /**
  21402. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21403. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21404. * 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.
  21405. */
  21406. var Light = /** @class */ (function (_super) {
  21407. __extends(Light, _super);
  21408. /**
  21409. * Creates a Light object in the scene.
  21410. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21411. * @param name The firendly name of the light
  21412. * @param scene The scene the light belongs too
  21413. */
  21414. function Light(name, scene) {
  21415. var _this = _super.call(this, name, scene) || this;
  21416. /**
  21417. * Diffuse gives the basic color to an object.
  21418. */
  21419. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21420. /**
  21421. * Specular produces a highlight color on an object.
  21422. * Note: This is note affecting PBR materials.
  21423. */
  21424. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21425. /**
  21426. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21427. * falling off base on range or angle.
  21428. * This can be set to any values in Light.FALLOFF_x.
  21429. *
  21430. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21431. * other types of materials.
  21432. */
  21433. _this.falloffType = Light.FALLOFF_DEFAULT;
  21434. /**
  21435. * Strength of the light.
  21436. * Note: By default it is define in the framework own unit.
  21437. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21438. */
  21439. _this.intensity = 1.0;
  21440. _this._range = Number.MAX_VALUE;
  21441. _this._inverseSquaredRange = 0;
  21442. /**
  21443. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21444. * of light.
  21445. */
  21446. _this._photometricScale = 1.0;
  21447. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21448. _this._radius = 0.00001;
  21449. /**
  21450. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21451. * exceeding the number allowed of the materials.
  21452. */
  21453. _this.renderPriority = 0;
  21454. _this._shadowEnabled = true;
  21455. _this._excludeWithLayerMask = 0;
  21456. _this._includeOnlyWithLayerMask = 0;
  21457. _this._lightmapMode = 0;
  21458. /**
  21459. * @hidden Internal use only.
  21460. */
  21461. _this._excludedMeshesIds = new Array();
  21462. /**
  21463. * @hidden Internal use only.
  21464. */
  21465. _this._includedOnlyMeshesIds = new Array();
  21466. _this.getScene().addLight(_this);
  21467. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21468. _this._buildUniformLayout();
  21469. _this.includedOnlyMeshes = new Array();
  21470. _this.excludedMeshes = new Array();
  21471. _this._resyncMeshes();
  21472. return _this;
  21473. }
  21474. Object.defineProperty(Light.prototype, "range", {
  21475. /**
  21476. * Defines how far from the source the light is impacting in scene units.
  21477. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21478. */
  21479. get: function () {
  21480. return this._range;
  21481. },
  21482. /**
  21483. * Defines how far from the source the light is impacting in scene units.
  21484. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21485. */
  21486. set: function (value) {
  21487. this._range = value;
  21488. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21489. },
  21490. enumerable: true,
  21491. configurable: true
  21492. });
  21493. Object.defineProperty(Light.prototype, "intensityMode", {
  21494. /**
  21495. * Gets the photometric scale used to interpret the intensity.
  21496. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21497. */
  21498. get: function () {
  21499. return this._intensityMode;
  21500. },
  21501. /**
  21502. * Sets the photometric scale used to interpret the intensity.
  21503. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21504. */
  21505. set: function (value) {
  21506. this._intensityMode = value;
  21507. this._computePhotometricScale();
  21508. },
  21509. enumerable: true,
  21510. configurable: true
  21511. });
  21512. ;
  21513. ;
  21514. Object.defineProperty(Light.prototype, "radius", {
  21515. /**
  21516. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21517. */
  21518. get: function () {
  21519. return this._radius;
  21520. },
  21521. /**
  21522. * sets the light radius used by PBR Materials to simulate soft area lights.
  21523. */
  21524. set: function (value) {
  21525. this._radius = value;
  21526. this._computePhotometricScale();
  21527. },
  21528. enumerable: true,
  21529. configurable: true
  21530. });
  21531. ;
  21532. ;
  21533. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21534. /**
  21535. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21536. * the current shadow generator.
  21537. */
  21538. get: function () {
  21539. return this._shadowEnabled;
  21540. },
  21541. /**
  21542. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21543. * the current shadow generator.
  21544. */
  21545. set: function (value) {
  21546. if (this._shadowEnabled === value) {
  21547. return;
  21548. }
  21549. this._shadowEnabled = value;
  21550. this._markMeshesAsLightDirty();
  21551. },
  21552. enumerable: true,
  21553. configurable: true
  21554. });
  21555. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21556. /**
  21557. * Gets the only meshes impacted by this light.
  21558. */
  21559. get: function () {
  21560. return this._includedOnlyMeshes;
  21561. },
  21562. /**
  21563. * Sets the only meshes impacted by this light.
  21564. */
  21565. set: function (value) {
  21566. this._includedOnlyMeshes = value;
  21567. this._hookArrayForIncludedOnly(value);
  21568. },
  21569. enumerable: true,
  21570. configurable: true
  21571. });
  21572. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21573. /**
  21574. * Gets the meshes not impacted by this light.
  21575. */
  21576. get: function () {
  21577. return this._excludedMeshes;
  21578. },
  21579. /**
  21580. * Sets the meshes not impacted by this light.
  21581. */
  21582. set: function (value) {
  21583. this._excludedMeshes = value;
  21584. this._hookArrayForExcluded(value);
  21585. },
  21586. enumerable: true,
  21587. configurable: true
  21588. });
  21589. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21590. /**
  21591. * Gets the layer id use to find what meshes are not impacted by the light.
  21592. * Inactive if 0
  21593. */
  21594. get: function () {
  21595. return this._excludeWithLayerMask;
  21596. },
  21597. /**
  21598. * Sets the layer id use to find what meshes are not impacted by the light.
  21599. * Inactive if 0
  21600. */
  21601. set: function (value) {
  21602. this._excludeWithLayerMask = value;
  21603. this._resyncMeshes();
  21604. },
  21605. enumerable: true,
  21606. configurable: true
  21607. });
  21608. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21609. /**
  21610. * Gets the layer id use to find what meshes are impacted by the light.
  21611. * Inactive if 0
  21612. */
  21613. get: function () {
  21614. return this._includeOnlyWithLayerMask;
  21615. },
  21616. /**
  21617. * Sets the layer id use to find what meshes are impacted by the light.
  21618. * Inactive if 0
  21619. */
  21620. set: function (value) {
  21621. this._includeOnlyWithLayerMask = value;
  21622. this._resyncMeshes();
  21623. },
  21624. enumerable: true,
  21625. configurable: true
  21626. });
  21627. Object.defineProperty(Light.prototype, "lightmapMode", {
  21628. /**
  21629. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21630. */
  21631. get: function () {
  21632. return this._lightmapMode;
  21633. },
  21634. /**
  21635. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21636. */
  21637. set: function (value) {
  21638. if (this._lightmapMode === value) {
  21639. return;
  21640. }
  21641. this._lightmapMode = value;
  21642. this._markMeshesAsLightDirty();
  21643. },
  21644. enumerable: true,
  21645. configurable: true
  21646. });
  21647. /**
  21648. * Returns the string "Light".
  21649. * @returns the class name
  21650. */
  21651. Light.prototype.getClassName = function () {
  21652. return "Light";
  21653. };
  21654. /**
  21655. * Converts the light information to a readable string for debug purpose.
  21656. * @param fullDetails Supports for multiple levels of logging within scene loading
  21657. * @returns the human readable light info
  21658. */
  21659. Light.prototype.toString = function (fullDetails) {
  21660. var ret = "Name: " + this.name;
  21661. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21662. if (this.animations) {
  21663. for (var i = 0; i < this.animations.length; i++) {
  21664. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21665. }
  21666. }
  21667. if (fullDetails) {
  21668. }
  21669. return ret;
  21670. };
  21671. /** @hidden */
  21672. Light.prototype._syncParentEnabledState = function () {
  21673. _super.prototype._syncParentEnabledState.call(this);
  21674. this._resyncMeshes();
  21675. };
  21676. /**
  21677. * Set the enabled state of this node.
  21678. * @param value - the new enabled state
  21679. */
  21680. Light.prototype.setEnabled = function (value) {
  21681. _super.prototype.setEnabled.call(this, value);
  21682. this._resyncMeshes();
  21683. };
  21684. /**
  21685. * Returns the Light associated shadow generator if any.
  21686. * @return the associated shadow generator.
  21687. */
  21688. Light.prototype.getShadowGenerator = function () {
  21689. return this._shadowGenerator;
  21690. };
  21691. /**
  21692. * Returns a Vector3, the absolute light position in the World.
  21693. * @returns the world space position of the light
  21694. */
  21695. Light.prototype.getAbsolutePosition = function () {
  21696. return BABYLON.Vector3.Zero();
  21697. };
  21698. /**
  21699. * Specifies if the light will affect the passed mesh.
  21700. * @param mesh The mesh to test against the light
  21701. * @return true the mesh is affected otherwise, false.
  21702. */
  21703. Light.prototype.canAffectMesh = function (mesh) {
  21704. if (!mesh) {
  21705. return true;
  21706. }
  21707. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21708. return false;
  21709. }
  21710. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21711. return false;
  21712. }
  21713. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21714. return false;
  21715. }
  21716. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21717. return false;
  21718. }
  21719. return true;
  21720. };
  21721. /**
  21722. * Sort function to order lights for rendering.
  21723. * @param a First Light object to compare to second.
  21724. * @param b Second Light object to compare first.
  21725. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21726. */
  21727. Light.CompareLightsPriority = function (a, b) {
  21728. //shadow-casting lights have priority over non-shadow-casting lights
  21729. //the renderPrioirty is a secondary sort criterion
  21730. if (a.shadowEnabled !== b.shadowEnabled) {
  21731. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21732. }
  21733. return b.renderPriority - a.renderPriority;
  21734. };
  21735. /**
  21736. * Releases resources associated with this node.
  21737. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21738. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21739. */
  21740. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21741. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21742. if (this._shadowGenerator) {
  21743. this._shadowGenerator.dispose();
  21744. this._shadowGenerator = null;
  21745. }
  21746. // Animations
  21747. this.getScene().stopAnimation(this);
  21748. // Remove from meshes
  21749. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21750. var mesh = _a[_i];
  21751. mesh._removeLightSource(this);
  21752. }
  21753. this._uniformBuffer.dispose();
  21754. // Remove from scene
  21755. this.getScene().removeLight(this);
  21756. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21757. };
  21758. /**
  21759. * Returns the light type ID (integer).
  21760. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21761. */
  21762. Light.prototype.getTypeID = function () {
  21763. return 0;
  21764. };
  21765. /**
  21766. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21767. * @returns the scaled intensity in intensity mode unit
  21768. */
  21769. Light.prototype.getScaledIntensity = function () {
  21770. return this._photometricScale * this.intensity;
  21771. };
  21772. /**
  21773. * Returns a new Light object, named "name", from the current one.
  21774. * @param name The name of the cloned light
  21775. * @returns the new created light
  21776. */
  21777. Light.prototype.clone = function (name) {
  21778. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21779. if (!constructor) {
  21780. return null;
  21781. }
  21782. return BABYLON.SerializationHelper.Clone(constructor, this);
  21783. };
  21784. /**
  21785. * Serializes the current light into a Serialization object.
  21786. * @returns the serialized object.
  21787. */
  21788. Light.prototype.serialize = function () {
  21789. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21790. // Type
  21791. serializationObject.type = this.getTypeID();
  21792. // Parent
  21793. if (this.parent) {
  21794. serializationObject.parentId = this.parent.id;
  21795. }
  21796. // Inclusion / exclusions
  21797. if (this.excludedMeshes.length > 0) {
  21798. serializationObject.excludedMeshesIds = [];
  21799. this.excludedMeshes.forEach(function (mesh) {
  21800. serializationObject.excludedMeshesIds.push(mesh.id);
  21801. });
  21802. }
  21803. if (this.includedOnlyMeshes.length > 0) {
  21804. serializationObject.includedOnlyMeshesIds = [];
  21805. this.includedOnlyMeshes.forEach(function (mesh) {
  21806. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21807. });
  21808. }
  21809. // Animations
  21810. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21811. serializationObject.ranges = this.serializeAnimationRanges();
  21812. return serializationObject;
  21813. };
  21814. /**
  21815. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21816. * This new light is named "name" and added to the passed scene.
  21817. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21818. * @param name The friendly name of the light
  21819. * @param scene The scene the new light will belong to
  21820. * @returns the constructor function
  21821. */
  21822. Light.GetConstructorFromName = function (type, name, scene) {
  21823. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21824. if (constructorFunc) {
  21825. return constructorFunc;
  21826. }
  21827. // Default to no light for none present once.
  21828. return null;
  21829. };
  21830. /**
  21831. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21832. * @param parsedLight The JSON representation of the light
  21833. * @param scene The scene to create the parsed light in
  21834. * @returns the created light after parsing
  21835. */
  21836. Light.Parse = function (parsedLight, scene) {
  21837. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21838. if (!constructor) {
  21839. return null;
  21840. }
  21841. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21842. // Inclusion / exclusions
  21843. if (parsedLight.excludedMeshesIds) {
  21844. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21845. }
  21846. if (parsedLight.includedOnlyMeshesIds) {
  21847. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21848. }
  21849. // Parent
  21850. if (parsedLight.parentId) {
  21851. light._waitingParentId = parsedLight.parentId;
  21852. }
  21853. // Animations
  21854. if (parsedLight.animations) {
  21855. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21856. var parsedAnimation = parsedLight.animations[animationIndex];
  21857. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21858. }
  21859. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21860. }
  21861. if (parsedLight.autoAnimate) {
  21862. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21863. }
  21864. return light;
  21865. };
  21866. Light.prototype._hookArrayForExcluded = function (array) {
  21867. var _this = this;
  21868. var oldPush = array.push;
  21869. array.push = function () {
  21870. var items = [];
  21871. for (var _i = 0; _i < arguments.length; _i++) {
  21872. items[_i] = arguments[_i];
  21873. }
  21874. var result = oldPush.apply(array, items);
  21875. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21876. var item = items_1[_a];
  21877. item._resyncLighSource(_this);
  21878. }
  21879. return result;
  21880. };
  21881. var oldSplice = array.splice;
  21882. array.splice = function (index, deleteCount) {
  21883. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21884. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21885. var item = deleted_1[_i];
  21886. item._resyncLighSource(_this);
  21887. }
  21888. return deleted;
  21889. };
  21890. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21891. var item = array_1[_i];
  21892. item._resyncLighSource(this);
  21893. }
  21894. };
  21895. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21896. var _this = this;
  21897. var oldPush = array.push;
  21898. array.push = function () {
  21899. var items = [];
  21900. for (var _i = 0; _i < arguments.length; _i++) {
  21901. items[_i] = arguments[_i];
  21902. }
  21903. var result = oldPush.apply(array, items);
  21904. _this._resyncMeshes();
  21905. return result;
  21906. };
  21907. var oldSplice = array.splice;
  21908. array.splice = function (index, deleteCount) {
  21909. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21910. _this._resyncMeshes();
  21911. return deleted;
  21912. };
  21913. this._resyncMeshes();
  21914. };
  21915. Light.prototype._resyncMeshes = function () {
  21916. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21917. var mesh = _a[_i];
  21918. mesh._resyncLighSource(this);
  21919. }
  21920. };
  21921. /**
  21922. * Forces the meshes to update their light related information in their rendering used effects
  21923. * @hidden Internal Use Only
  21924. */
  21925. Light.prototype._markMeshesAsLightDirty = function () {
  21926. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21927. var mesh = _a[_i];
  21928. if (mesh._lightSources.indexOf(this) !== -1) {
  21929. mesh._markSubMeshesAsLightDirty();
  21930. }
  21931. }
  21932. };
  21933. /**
  21934. * Recomputes the cached photometric scale if needed.
  21935. */
  21936. Light.prototype._computePhotometricScale = function () {
  21937. this._photometricScale = this._getPhotometricScale();
  21938. this.getScene().resetCachedMaterial();
  21939. };
  21940. /**
  21941. * Returns the Photometric Scale according to the light type and intensity mode.
  21942. */
  21943. Light.prototype._getPhotometricScale = function () {
  21944. var photometricScale = 0.0;
  21945. var lightTypeID = this.getTypeID();
  21946. //get photometric mode
  21947. var photometricMode = this.intensityMode;
  21948. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21949. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21950. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21951. }
  21952. else {
  21953. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21954. }
  21955. }
  21956. //compute photometric scale
  21957. switch (lightTypeID) {
  21958. case Light.LIGHTTYPEID_POINTLIGHT:
  21959. case Light.LIGHTTYPEID_SPOTLIGHT:
  21960. switch (photometricMode) {
  21961. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21962. photometricScale = 1.0 / (4.0 * Math.PI);
  21963. break;
  21964. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21965. photometricScale = 1.0;
  21966. break;
  21967. case Light.INTENSITYMODE_LUMINANCE:
  21968. photometricScale = this.radius * this.radius;
  21969. break;
  21970. }
  21971. break;
  21972. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21973. switch (photometricMode) {
  21974. case Light.INTENSITYMODE_ILLUMINANCE:
  21975. photometricScale = 1.0;
  21976. break;
  21977. case Light.INTENSITYMODE_LUMINANCE:
  21978. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21979. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21980. var apexAngleRadians = this.radius;
  21981. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21982. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21983. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21984. photometricScale = solidAngle;
  21985. break;
  21986. }
  21987. break;
  21988. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21989. // No fall off in hemisperic light.
  21990. photometricScale = 1.0;
  21991. break;
  21992. }
  21993. return photometricScale;
  21994. };
  21995. /**
  21996. * Reorder the light in the scene according to their defined priority.
  21997. * @hidden Internal Use Only
  21998. */
  21999. Light.prototype._reorderLightsInScene = function () {
  22000. var scene = this.getScene();
  22001. if (this._renderPriority != 0) {
  22002. scene.requireLightSorting = true;
  22003. }
  22004. this.getScene().sortLightsByPriority();
  22005. };
  22006. /**
  22007. * Falloff Default: light is falling off following the material specification:
  22008. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22009. */
  22010. Light.FALLOFF_DEFAULT = 0;
  22011. /**
  22012. * Falloff Physical: light is falling off following the inverse squared distance law.
  22013. */
  22014. Light.FALLOFF_PHYSICAL = 1;
  22015. /**
  22016. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22017. * to enhance interoperability with other engines.
  22018. */
  22019. Light.FALLOFF_GLTF = 2;
  22020. /**
  22021. * Falloff Standard: light is falling off like in the standard material
  22022. * to enhance interoperability with other materials.
  22023. */
  22024. Light.FALLOFF_STANDARD = 3;
  22025. //lightmapMode Consts
  22026. /**
  22027. * If every light affecting the material is in this lightmapMode,
  22028. * material.lightmapTexture adds or multiplies
  22029. * (depends on material.useLightmapAsShadowmap)
  22030. * after every other light calculations.
  22031. */
  22032. Light.LIGHTMAP_DEFAULT = 0;
  22033. /**
  22034. * material.lightmapTexture as only diffuse lighting from this light
  22035. * adds only specular lighting from this light
  22036. * adds dynamic shadows
  22037. */
  22038. Light.LIGHTMAP_SPECULAR = 1;
  22039. /**
  22040. * material.lightmapTexture as only lighting
  22041. * no light calculation from this light
  22042. * only adds dynamic shadows from this light
  22043. */
  22044. Light.LIGHTMAP_SHADOWSONLY = 2;
  22045. // Intensity Mode Consts
  22046. /**
  22047. * Each light type uses the default quantity according to its type:
  22048. * point/spot lights use luminous intensity
  22049. * directional lights use illuminance
  22050. */
  22051. Light.INTENSITYMODE_AUTOMATIC = 0;
  22052. /**
  22053. * lumen (lm)
  22054. */
  22055. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22056. /**
  22057. * candela (lm/sr)
  22058. */
  22059. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22060. /**
  22061. * lux (lm/m^2)
  22062. */
  22063. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22064. /**
  22065. * nit (cd/m^2)
  22066. */
  22067. Light.INTENSITYMODE_LUMINANCE = 4;
  22068. // Light types ids const.
  22069. /**
  22070. * Light type const id of the point light.
  22071. */
  22072. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22073. /**
  22074. * Light type const id of the directional light.
  22075. */
  22076. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22077. /**
  22078. * Light type const id of the spot light.
  22079. */
  22080. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22081. /**
  22082. * Light type const id of the hemispheric light.
  22083. */
  22084. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22085. __decorate([
  22086. BABYLON.serializeAsColor3()
  22087. ], Light.prototype, "diffuse", void 0);
  22088. __decorate([
  22089. BABYLON.serializeAsColor3()
  22090. ], Light.prototype, "specular", void 0);
  22091. __decorate([
  22092. BABYLON.serialize()
  22093. ], Light.prototype, "falloffType", void 0);
  22094. __decorate([
  22095. BABYLON.serialize()
  22096. ], Light.prototype, "intensity", void 0);
  22097. __decorate([
  22098. BABYLON.serialize()
  22099. ], Light.prototype, "range", null);
  22100. __decorate([
  22101. BABYLON.serialize()
  22102. ], Light.prototype, "intensityMode", null);
  22103. __decorate([
  22104. BABYLON.serialize()
  22105. ], Light.prototype, "radius", null);
  22106. __decorate([
  22107. BABYLON.serialize()
  22108. ], Light.prototype, "_renderPriority", void 0);
  22109. __decorate([
  22110. BABYLON.expandToProperty("_reorderLightsInScene")
  22111. ], Light.prototype, "renderPriority", void 0);
  22112. __decorate([
  22113. BABYLON.serialize("shadowEnabled")
  22114. ], Light.prototype, "_shadowEnabled", void 0);
  22115. __decorate([
  22116. BABYLON.serialize("excludeWithLayerMask")
  22117. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22118. __decorate([
  22119. BABYLON.serialize("includeOnlyWithLayerMask")
  22120. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22121. __decorate([
  22122. BABYLON.serialize("lightmapMode")
  22123. ], Light.prototype, "_lightmapMode", void 0);
  22124. return Light;
  22125. }(BABYLON.Node));
  22126. BABYLON.Light = Light;
  22127. })(BABYLON || (BABYLON = {}));
  22128. //# sourceMappingURL=babylon.light.js.map
  22129. var BABYLON;
  22130. (function (BABYLON) {
  22131. var Camera = /** @class */ (function (_super) {
  22132. __extends(Camera, _super);
  22133. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22134. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22135. var _this = _super.call(this, name, scene) || this;
  22136. /**
  22137. * The vector the camera should consider as up.
  22138. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22139. */
  22140. _this.upVector = BABYLON.Vector3.Up();
  22141. _this.orthoLeft = null;
  22142. _this.orthoRight = null;
  22143. _this.orthoBottom = null;
  22144. _this.orthoTop = null;
  22145. /**
  22146. * FOV is set in Radians. (default is 0.8)
  22147. */
  22148. _this.fov = 0.8;
  22149. _this.minZ = 1;
  22150. _this.maxZ = 10000.0;
  22151. _this.inertia = 0.9;
  22152. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22153. _this.isIntermediate = false;
  22154. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22155. /**
  22156. * Restricts the camera to viewing objects with the same layerMask.
  22157. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22158. */
  22159. _this.layerMask = 0x0FFFFFFF;
  22160. /**
  22161. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22162. */
  22163. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22164. // Camera rig members
  22165. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22166. /** @hidden */
  22167. _this._rigCameras = new Array();
  22168. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22169. /** @hidden */
  22170. _this._skipRendering = false;
  22171. _this.customRenderTargets = new Array();
  22172. // Observables
  22173. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22174. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22175. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22176. _this.onRestoreStateObservable = new BABYLON.Observable();
  22177. // Cache
  22178. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22179. _this._projectionMatrix = new BABYLON.Matrix();
  22180. _this._doNotComputeProjectionMatrix = false;
  22181. _this._postProcesses = new Array();
  22182. _this._transformMatrix = BABYLON.Matrix.Zero();
  22183. _this._activeMeshes = new BABYLON.SmartArray(256);
  22184. _this._globalPosition = BABYLON.Vector3.Zero();
  22185. _this._refreshFrustumPlanes = true;
  22186. _this.getScene().addCamera(_this);
  22187. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22188. _this.getScene().activeCamera = _this;
  22189. }
  22190. _this.position = position;
  22191. return _this;
  22192. }
  22193. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22194. get: function () {
  22195. return Camera._PERSPECTIVE_CAMERA;
  22196. },
  22197. enumerable: true,
  22198. configurable: true
  22199. });
  22200. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22201. get: function () {
  22202. return Camera._ORTHOGRAPHIC_CAMERA;
  22203. },
  22204. enumerable: true,
  22205. configurable: true
  22206. });
  22207. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22208. /**
  22209. * This is the default FOV mode for perspective cameras.
  22210. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22211. *
  22212. */
  22213. get: function () {
  22214. return Camera._FOVMODE_VERTICAL_FIXED;
  22215. },
  22216. enumerable: true,
  22217. configurable: true
  22218. });
  22219. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22220. /**
  22221. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22222. *
  22223. */
  22224. get: function () {
  22225. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22226. },
  22227. enumerable: true,
  22228. configurable: true
  22229. });
  22230. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22231. get: function () {
  22232. return Camera._RIG_MODE_NONE;
  22233. },
  22234. enumerable: true,
  22235. configurable: true
  22236. });
  22237. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22238. get: function () {
  22239. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22240. },
  22241. enumerable: true,
  22242. configurable: true
  22243. });
  22244. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22245. get: function () {
  22246. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22247. },
  22248. enumerable: true,
  22249. configurable: true
  22250. });
  22251. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22252. get: function () {
  22253. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22254. },
  22255. enumerable: true,
  22256. configurable: true
  22257. });
  22258. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22259. get: function () {
  22260. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22261. },
  22262. enumerable: true,
  22263. configurable: true
  22264. });
  22265. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22266. get: function () {
  22267. return Camera._RIG_MODE_VR;
  22268. },
  22269. enumerable: true,
  22270. configurable: true
  22271. });
  22272. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22273. get: function () {
  22274. return Camera._RIG_MODE_WEBVR;
  22275. },
  22276. enumerable: true,
  22277. configurable: true
  22278. });
  22279. /**
  22280. * Store current camera state (fov, position, etc..)
  22281. */
  22282. Camera.prototype.storeState = function () {
  22283. this._stateStored = true;
  22284. this._storedFov = this.fov;
  22285. return this;
  22286. };
  22287. /**
  22288. * Restores the camera state values if it has been stored. You must call storeState() first
  22289. */
  22290. Camera.prototype._restoreStateValues = function () {
  22291. if (!this._stateStored) {
  22292. return false;
  22293. }
  22294. this.fov = this._storedFov;
  22295. return true;
  22296. };
  22297. /**
  22298. * Restored camera state. You must call storeState() first
  22299. */
  22300. Camera.prototype.restoreState = function () {
  22301. if (this._restoreStateValues()) {
  22302. this.onRestoreStateObservable.notifyObservers(this);
  22303. return true;
  22304. }
  22305. return false;
  22306. };
  22307. Camera.prototype.getClassName = function () {
  22308. return "Camera";
  22309. };
  22310. /**
  22311. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22312. */
  22313. Camera.prototype.toString = function (fullDetails) {
  22314. var ret = "Name: " + this.name;
  22315. ret += ", type: " + this.getClassName();
  22316. if (this.animations) {
  22317. for (var i = 0; i < this.animations.length; i++) {
  22318. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22319. }
  22320. }
  22321. if (fullDetails) {
  22322. }
  22323. return ret;
  22324. };
  22325. Object.defineProperty(Camera.prototype, "globalPosition", {
  22326. get: function () {
  22327. return this._globalPosition;
  22328. },
  22329. enumerable: true,
  22330. configurable: true
  22331. });
  22332. Camera.prototype.getActiveMeshes = function () {
  22333. return this._activeMeshes;
  22334. };
  22335. Camera.prototype.isActiveMesh = function (mesh) {
  22336. return (this._activeMeshes.indexOf(mesh) !== -1);
  22337. };
  22338. /**
  22339. * Is this camera ready to be used/rendered
  22340. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22341. * @return true if the camera is ready
  22342. */
  22343. Camera.prototype.isReady = function (completeCheck) {
  22344. if (completeCheck === void 0) { completeCheck = false; }
  22345. if (completeCheck) {
  22346. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22347. var pp = _a[_i];
  22348. if (pp && !pp.isReady()) {
  22349. return false;
  22350. }
  22351. }
  22352. }
  22353. return _super.prototype.isReady.call(this, completeCheck);
  22354. };
  22355. //Cache
  22356. /** @hidden */
  22357. Camera.prototype._initCache = function () {
  22358. _super.prototype._initCache.call(this);
  22359. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22360. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22361. this._cache.mode = undefined;
  22362. this._cache.minZ = undefined;
  22363. this._cache.maxZ = undefined;
  22364. this._cache.fov = undefined;
  22365. this._cache.fovMode = undefined;
  22366. this._cache.aspectRatio = undefined;
  22367. this._cache.orthoLeft = undefined;
  22368. this._cache.orthoRight = undefined;
  22369. this._cache.orthoBottom = undefined;
  22370. this._cache.orthoTop = undefined;
  22371. this._cache.renderWidth = undefined;
  22372. this._cache.renderHeight = undefined;
  22373. };
  22374. /** @hidden */
  22375. Camera.prototype._updateCache = function (ignoreParentClass) {
  22376. if (!ignoreParentClass) {
  22377. _super.prototype._updateCache.call(this);
  22378. }
  22379. this._cache.position.copyFrom(this.position);
  22380. this._cache.upVector.copyFrom(this.upVector);
  22381. };
  22382. // Synchronized
  22383. /** @hidden */
  22384. Camera.prototype._isSynchronized = function () {
  22385. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22386. };
  22387. /** @hidden */
  22388. Camera.prototype._isSynchronizedViewMatrix = function () {
  22389. if (!_super.prototype._isSynchronized.call(this))
  22390. return false;
  22391. return this._cache.position.equals(this.position)
  22392. && this._cache.upVector.equals(this.upVector)
  22393. && this.isSynchronizedWithParent();
  22394. };
  22395. /** @hidden */
  22396. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22397. var check = this._cache.mode === this.mode
  22398. && this._cache.minZ === this.minZ
  22399. && this._cache.maxZ === this.maxZ;
  22400. if (!check) {
  22401. return false;
  22402. }
  22403. var engine = this.getEngine();
  22404. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22405. check = this._cache.fov === this.fov
  22406. && this._cache.fovMode === this.fovMode
  22407. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22408. }
  22409. else {
  22410. check = this._cache.orthoLeft === this.orthoLeft
  22411. && this._cache.orthoRight === this.orthoRight
  22412. && this._cache.orthoBottom === this.orthoBottom
  22413. && this._cache.orthoTop === this.orthoTop
  22414. && this._cache.renderWidth === engine.getRenderWidth()
  22415. && this._cache.renderHeight === engine.getRenderHeight();
  22416. }
  22417. return check;
  22418. };
  22419. // Controls
  22420. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22421. };
  22422. Camera.prototype.detachControl = function (element) {
  22423. };
  22424. Camera.prototype.update = function () {
  22425. this._checkInputs();
  22426. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22427. this._updateRigCameras();
  22428. }
  22429. };
  22430. /** @hidden */
  22431. Camera.prototype._checkInputs = function () {
  22432. this.onAfterCheckInputsObservable.notifyObservers(this);
  22433. };
  22434. Object.defineProperty(Camera.prototype, "rigCameras", {
  22435. get: function () {
  22436. return this._rigCameras;
  22437. },
  22438. enumerable: true,
  22439. configurable: true
  22440. });
  22441. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22442. get: function () {
  22443. return this._rigPostProcess;
  22444. },
  22445. enumerable: true,
  22446. configurable: true
  22447. });
  22448. /**
  22449. * Internal, gets the first post proces.
  22450. * @returns the first post process to be run on this camera.
  22451. */
  22452. Camera.prototype._getFirstPostProcess = function () {
  22453. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22454. if (this._postProcesses[ppIndex] !== null) {
  22455. return this._postProcesses[ppIndex];
  22456. }
  22457. }
  22458. return null;
  22459. };
  22460. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22461. // invalidate framebuffer
  22462. var firstPostProcess = this._getFirstPostProcess();
  22463. if (firstPostProcess) {
  22464. firstPostProcess.markTextureDirty();
  22465. }
  22466. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22467. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22468. var cam = this._rigCameras[i];
  22469. var rigPostProcess = cam._rigPostProcess;
  22470. // for VR rig, there does not have to be a post process
  22471. if (rigPostProcess) {
  22472. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22473. if (isPass) {
  22474. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22475. cam.isIntermediate = this._postProcesses.length === 0;
  22476. }
  22477. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22478. rigPostProcess.markTextureDirty();
  22479. }
  22480. else {
  22481. cam._postProcesses = this._postProcesses.slice(0);
  22482. }
  22483. }
  22484. };
  22485. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22486. if (insertAt === void 0) { insertAt = null; }
  22487. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22488. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22489. return 0;
  22490. }
  22491. if (insertAt == null || insertAt < 0) {
  22492. this._postProcesses.push(postProcess);
  22493. }
  22494. else if (this._postProcesses[insertAt] === null) {
  22495. this._postProcesses[insertAt] = postProcess;
  22496. }
  22497. else {
  22498. this._postProcesses.splice(insertAt, 0, postProcess);
  22499. }
  22500. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22501. return this._postProcesses.indexOf(postProcess);
  22502. };
  22503. Camera.prototype.detachPostProcess = function (postProcess) {
  22504. var idx = this._postProcesses.indexOf(postProcess);
  22505. if (idx !== -1) {
  22506. this._postProcesses[idx] = null;
  22507. }
  22508. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22509. };
  22510. Camera.prototype.getWorldMatrix = function () {
  22511. if (this._isSynchronizedViewMatrix()) {
  22512. return this._worldMatrix;
  22513. }
  22514. // Getting the the view matrix will also compute the world matrix.
  22515. this.getViewMatrix();
  22516. return this._worldMatrix;
  22517. };
  22518. /** @hidden */
  22519. Camera.prototype._getViewMatrix = function () {
  22520. return BABYLON.Matrix.Identity();
  22521. };
  22522. Camera.prototype.getViewMatrix = function (force) {
  22523. if (!force && this._isSynchronizedViewMatrix()) {
  22524. return this._computedViewMatrix;
  22525. }
  22526. this.updateCache();
  22527. this._computedViewMatrix = this._getViewMatrix();
  22528. this._currentRenderId = this.getScene().getRenderId();
  22529. this._childRenderId = this._currentRenderId;
  22530. this._refreshFrustumPlanes = true;
  22531. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22532. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22533. }
  22534. this.onViewMatrixChangedObservable.notifyObservers(this);
  22535. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22536. return this._computedViewMatrix;
  22537. };
  22538. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22539. this._doNotComputeProjectionMatrix = true;
  22540. if (projection !== undefined) {
  22541. this._projectionMatrix = projection;
  22542. }
  22543. };
  22544. ;
  22545. Camera.prototype.unfreezeProjectionMatrix = function () {
  22546. this._doNotComputeProjectionMatrix = false;
  22547. };
  22548. ;
  22549. Camera.prototype.getProjectionMatrix = function (force) {
  22550. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22551. return this._projectionMatrix;
  22552. }
  22553. // Cache
  22554. this._cache.mode = this.mode;
  22555. this._cache.minZ = this.minZ;
  22556. this._cache.maxZ = this.maxZ;
  22557. // Matrix
  22558. this._refreshFrustumPlanes = true;
  22559. var engine = this.getEngine();
  22560. var scene = this.getScene();
  22561. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22562. this._cache.fov = this.fov;
  22563. this._cache.fovMode = this.fovMode;
  22564. this._cache.aspectRatio = engine.getAspectRatio(this);
  22565. if (this.minZ <= 0) {
  22566. this.minZ = 0.1;
  22567. }
  22568. if (scene.useRightHandedSystem) {
  22569. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22570. }
  22571. else {
  22572. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22573. }
  22574. }
  22575. else {
  22576. var halfWidth = engine.getRenderWidth() / 2.0;
  22577. var halfHeight = engine.getRenderHeight() / 2.0;
  22578. if (scene.useRightHandedSystem) {
  22579. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22580. }
  22581. else {
  22582. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22583. }
  22584. this._cache.orthoLeft = this.orthoLeft;
  22585. this._cache.orthoRight = this.orthoRight;
  22586. this._cache.orthoBottom = this.orthoBottom;
  22587. this._cache.orthoTop = this.orthoTop;
  22588. this._cache.renderWidth = engine.getRenderWidth();
  22589. this._cache.renderHeight = engine.getRenderHeight();
  22590. }
  22591. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22592. return this._projectionMatrix;
  22593. };
  22594. /**
  22595. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22596. * @returns a Matrix
  22597. */
  22598. Camera.prototype.getTransformationMatrix = function () {
  22599. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22600. return this._transformMatrix;
  22601. };
  22602. Camera.prototype.updateFrustumPlanes = function () {
  22603. if (!this._refreshFrustumPlanes) {
  22604. return;
  22605. }
  22606. this.getTransformationMatrix();
  22607. if (!this._frustumPlanes) {
  22608. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22609. }
  22610. else {
  22611. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22612. }
  22613. this._refreshFrustumPlanes = false;
  22614. };
  22615. Camera.prototype.isInFrustum = function (target) {
  22616. this.updateFrustumPlanes();
  22617. return target.isInFrustum(this._frustumPlanes);
  22618. };
  22619. Camera.prototype.isCompletelyInFrustum = function (target) {
  22620. this.updateFrustumPlanes();
  22621. return target.isCompletelyInFrustum(this._frustumPlanes);
  22622. };
  22623. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22624. if (length === void 0) { length = 100; }
  22625. if (!transform) {
  22626. transform = this.getWorldMatrix();
  22627. }
  22628. if (!origin) {
  22629. origin = this.position;
  22630. }
  22631. var forward = new BABYLON.Vector3(0, 0, 1);
  22632. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22633. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22634. return new BABYLON.Ray(origin, direction, length);
  22635. };
  22636. /**
  22637. * Releases resources associated with this node.
  22638. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22639. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22640. */
  22641. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22642. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22643. // Observables
  22644. this.onViewMatrixChangedObservable.clear();
  22645. this.onProjectionMatrixChangedObservable.clear();
  22646. this.onAfterCheckInputsObservable.clear();
  22647. this.onRestoreStateObservable.clear();
  22648. // Inputs
  22649. if (this.inputs) {
  22650. this.inputs.clear();
  22651. }
  22652. // Animations
  22653. this.getScene().stopAnimation(this);
  22654. // Remove from scene
  22655. this.getScene().removeCamera(this);
  22656. while (this._rigCameras.length > 0) {
  22657. var camera = this._rigCameras.pop();
  22658. if (camera) {
  22659. camera.dispose();
  22660. }
  22661. }
  22662. // Postprocesses
  22663. if (this._rigPostProcess) {
  22664. this._rigPostProcess.dispose(this);
  22665. this._rigPostProcess = null;
  22666. this._postProcesses = [];
  22667. }
  22668. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22669. this._rigPostProcess = null;
  22670. this._postProcesses = [];
  22671. }
  22672. else {
  22673. var i = this._postProcesses.length;
  22674. while (--i >= 0) {
  22675. var postProcess = this._postProcesses[i];
  22676. if (postProcess) {
  22677. postProcess.dispose(this);
  22678. }
  22679. }
  22680. }
  22681. // Render targets
  22682. var i = this.customRenderTargets.length;
  22683. while (--i >= 0) {
  22684. this.customRenderTargets[i].dispose();
  22685. }
  22686. this.customRenderTargets = [];
  22687. // Active Meshes
  22688. this._activeMeshes.dispose();
  22689. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22690. };
  22691. Object.defineProperty(Camera.prototype, "leftCamera", {
  22692. // ---- Camera rigs section ----
  22693. get: function () {
  22694. if (this._rigCameras.length < 1) {
  22695. return null;
  22696. }
  22697. return this._rigCameras[0];
  22698. },
  22699. enumerable: true,
  22700. configurable: true
  22701. });
  22702. Object.defineProperty(Camera.prototype, "rightCamera", {
  22703. get: function () {
  22704. if (this._rigCameras.length < 2) {
  22705. return null;
  22706. }
  22707. return this._rigCameras[1];
  22708. },
  22709. enumerable: true,
  22710. configurable: true
  22711. });
  22712. Camera.prototype.getLeftTarget = function () {
  22713. if (this._rigCameras.length < 1) {
  22714. return null;
  22715. }
  22716. return this._rigCameras[0].getTarget();
  22717. };
  22718. Camera.prototype.getRightTarget = function () {
  22719. if (this._rigCameras.length < 2) {
  22720. return null;
  22721. }
  22722. return this._rigCameras[1].getTarget();
  22723. };
  22724. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22725. if (this.cameraRigMode === mode) {
  22726. return;
  22727. }
  22728. while (this._rigCameras.length > 0) {
  22729. var camera = this._rigCameras.pop();
  22730. if (camera) {
  22731. camera.dispose();
  22732. }
  22733. }
  22734. this.cameraRigMode = mode;
  22735. this._cameraRigParams = {};
  22736. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22737. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22738. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22739. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22740. // create the rig cameras, unless none
  22741. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22742. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22743. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22744. if (leftCamera && rightCamera) {
  22745. this._rigCameras.push(leftCamera);
  22746. this._rigCameras.push(rightCamera);
  22747. }
  22748. }
  22749. switch (this.cameraRigMode) {
  22750. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22751. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22752. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22753. break;
  22754. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22755. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22756. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22757. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22758. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22759. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22760. break;
  22761. case Camera.RIG_MODE_VR:
  22762. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22763. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22764. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22765. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22766. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22767. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22768. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22769. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22770. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22771. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22772. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22773. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22774. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22775. if (metrics.compensateDistortion) {
  22776. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22777. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22778. }
  22779. break;
  22780. case Camera.RIG_MODE_WEBVR:
  22781. if (rigParams.vrDisplay) {
  22782. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22783. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22784. //Left eye
  22785. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22786. this._rigCameras[0].setCameraRigParameter("left", true);
  22787. //leaving this for future reference
  22788. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22789. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22790. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22791. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22792. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22793. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22794. this._rigCameras[0].parent = this;
  22795. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22796. //Right eye
  22797. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22798. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22799. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22800. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22801. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22802. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22803. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22804. this._rigCameras[1].parent = this;
  22805. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22806. if (Camera.UseAlternateWebVRRendering) {
  22807. this._rigCameras[1]._skipRendering = true;
  22808. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22809. }
  22810. }
  22811. break;
  22812. }
  22813. this._cascadePostProcessesToRigCams();
  22814. this.update();
  22815. };
  22816. Camera.prototype._getVRProjectionMatrix = function () {
  22817. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22818. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22819. return this._projectionMatrix;
  22820. };
  22821. Camera.prototype._updateCameraRotationMatrix = function () {
  22822. //Here for WebVR
  22823. };
  22824. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22825. //Here for WebVR
  22826. };
  22827. /**
  22828. * This function MUST be overwritten by the different WebVR cameras available.
  22829. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22830. */
  22831. Camera.prototype._getWebVRProjectionMatrix = function () {
  22832. return BABYLON.Matrix.Identity();
  22833. };
  22834. /**
  22835. * This function MUST be overwritten by the different WebVR cameras available.
  22836. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22837. */
  22838. Camera.prototype._getWebVRViewMatrix = function () {
  22839. return BABYLON.Matrix.Identity();
  22840. };
  22841. Camera.prototype.setCameraRigParameter = function (name, value) {
  22842. if (!this._cameraRigParams) {
  22843. this._cameraRigParams = {};
  22844. }
  22845. this._cameraRigParams[name] = value;
  22846. //provisionnally:
  22847. if (name === "interaxialDistance") {
  22848. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22849. }
  22850. };
  22851. /**
  22852. * needs to be overridden by children so sub has required properties to be copied
  22853. */
  22854. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22855. return null;
  22856. };
  22857. /**
  22858. * May need to be overridden by children
  22859. * @hidden
  22860. */
  22861. Camera.prototype._updateRigCameras = function () {
  22862. for (var i = 0; i < this._rigCameras.length; i++) {
  22863. this._rigCameras[i].minZ = this.minZ;
  22864. this._rigCameras[i].maxZ = this.maxZ;
  22865. this._rigCameras[i].fov = this.fov;
  22866. }
  22867. // only update viewport when ANAGLYPH
  22868. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22869. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22870. }
  22871. };
  22872. /** @hidden */
  22873. Camera.prototype._setupInputs = function () {
  22874. };
  22875. Camera.prototype.serialize = function () {
  22876. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22877. // Type
  22878. serializationObject.type = this.getClassName();
  22879. // Parent
  22880. if (this.parent) {
  22881. serializationObject.parentId = this.parent.id;
  22882. }
  22883. if (this.inputs) {
  22884. this.inputs.serialize(serializationObject);
  22885. }
  22886. // Animations
  22887. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22888. serializationObject.ranges = this.serializeAnimationRanges();
  22889. return serializationObject;
  22890. };
  22891. Camera.prototype.clone = function (name) {
  22892. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22893. };
  22894. Camera.prototype.getDirection = function (localAxis) {
  22895. var result = BABYLON.Vector3.Zero();
  22896. this.getDirectionToRef(localAxis, result);
  22897. return result;
  22898. };
  22899. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22900. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22901. };
  22902. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22903. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22904. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22905. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22906. interaxial_distance: interaxial_distance,
  22907. isStereoscopicSideBySide: isStereoscopicSideBySide
  22908. });
  22909. if (constructorFunc) {
  22910. return constructorFunc;
  22911. }
  22912. // Default to universal camera
  22913. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22914. };
  22915. Camera.prototype.computeWorldMatrix = function () {
  22916. return this.getWorldMatrix();
  22917. };
  22918. Camera.Parse = function (parsedCamera, scene) {
  22919. var type = parsedCamera.type;
  22920. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22921. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22922. // Parent
  22923. if (parsedCamera.parentId) {
  22924. camera._waitingParentId = parsedCamera.parentId;
  22925. }
  22926. //If camera has an input manager, let it parse inputs settings
  22927. if (camera.inputs) {
  22928. camera.inputs.parse(parsedCamera);
  22929. camera._setupInputs();
  22930. }
  22931. if (camera.setPosition) { // need to force position
  22932. camera.position.copyFromFloats(0, 0, 0);
  22933. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22934. }
  22935. // Target
  22936. if (parsedCamera.target) {
  22937. if (camera.setTarget) {
  22938. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22939. }
  22940. }
  22941. // Apply 3d rig, when found
  22942. if (parsedCamera.cameraRigMode) {
  22943. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22944. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22945. }
  22946. // Animations
  22947. if (parsedCamera.animations) {
  22948. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22949. var parsedAnimation = parsedCamera.animations[animationIndex];
  22950. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22951. }
  22952. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22953. }
  22954. if (parsedCamera.autoAnimate) {
  22955. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22956. }
  22957. return camera;
  22958. };
  22959. // Statics
  22960. Camera._PERSPECTIVE_CAMERA = 0;
  22961. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22962. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22963. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22964. Camera._RIG_MODE_NONE = 0;
  22965. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22966. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22967. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22968. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22969. Camera._RIG_MODE_VR = 20;
  22970. Camera._RIG_MODE_WEBVR = 21;
  22971. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22972. Camera.UseAlternateWebVRRendering = false;
  22973. __decorate([
  22974. BABYLON.serializeAsVector3()
  22975. ], Camera.prototype, "position", void 0);
  22976. __decorate([
  22977. BABYLON.serializeAsVector3()
  22978. ], Camera.prototype, "upVector", void 0);
  22979. __decorate([
  22980. BABYLON.serialize()
  22981. ], Camera.prototype, "orthoLeft", void 0);
  22982. __decorate([
  22983. BABYLON.serialize()
  22984. ], Camera.prototype, "orthoRight", void 0);
  22985. __decorate([
  22986. BABYLON.serialize()
  22987. ], Camera.prototype, "orthoBottom", void 0);
  22988. __decorate([
  22989. BABYLON.serialize()
  22990. ], Camera.prototype, "orthoTop", void 0);
  22991. __decorate([
  22992. BABYLON.serialize()
  22993. ], Camera.prototype, "fov", void 0);
  22994. __decorate([
  22995. BABYLON.serialize()
  22996. ], Camera.prototype, "minZ", void 0);
  22997. __decorate([
  22998. BABYLON.serialize()
  22999. ], Camera.prototype, "maxZ", void 0);
  23000. __decorate([
  23001. BABYLON.serialize()
  23002. ], Camera.prototype, "inertia", void 0);
  23003. __decorate([
  23004. BABYLON.serialize()
  23005. ], Camera.prototype, "mode", void 0);
  23006. __decorate([
  23007. BABYLON.serialize()
  23008. ], Camera.prototype, "layerMask", void 0);
  23009. __decorate([
  23010. BABYLON.serialize()
  23011. ], Camera.prototype, "fovMode", void 0);
  23012. __decorate([
  23013. BABYLON.serialize()
  23014. ], Camera.prototype, "cameraRigMode", void 0);
  23015. __decorate([
  23016. BABYLON.serialize()
  23017. ], Camera.prototype, "interaxialDistance", void 0);
  23018. __decorate([
  23019. BABYLON.serialize()
  23020. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23021. return Camera;
  23022. }(BABYLON.Node));
  23023. BABYLON.Camera = Camera;
  23024. })(BABYLON || (BABYLON = {}));
  23025. //# sourceMappingURL=babylon.camera.js.map
  23026. var BABYLON;
  23027. (function (BABYLON) {
  23028. var RenderingManager = /** @class */ (function () {
  23029. function RenderingManager(scene) {
  23030. /**
  23031. * @hidden
  23032. */
  23033. this._useSceneAutoClearSetup = false;
  23034. this._renderingGroups = new Array();
  23035. this._autoClearDepthStencil = {};
  23036. this._customOpaqueSortCompareFn = {};
  23037. this._customAlphaTestSortCompareFn = {};
  23038. this._customTransparentSortCompareFn = {};
  23039. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23040. this._scene = scene;
  23041. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23042. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23043. }
  23044. }
  23045. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23046. if (depth === void 0) { depth = true; }
  23047. if (stencil === void 0) { stencil = true; }
  23048. if (this._depthStencilBufferAlreadyCleaned) {
  23049. return;
  23050. }
  23051. this._scene.getEngine().clear(null, false, depth, stencil);
  23052. this._depthStencilBufferAlreadyCleaned = true;
  23053. };
  23054. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23055. // Update the observable context (not null as it only goes away on dispose)
  23056. var info = this._renderingGroupInfo;
  23057. info.scene = this._scene;
  23058. info.camera = this._scene.activeCamera;
  23059. // Dispatch sprites
  23060. if (this._scene.spriteManagers && renderSprites) {
  23061. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23062. var manager = this._scene.spriteManagers[index];
  23063. this.dispatchSprites(manager);
  23064. }
  23065. }
  23066. // Render
  23067. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23068. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23069. var renderingGroup = this._renderingGroups[index];
  23070. if (!renderingGroup)
  23071. continue;
  23072. var renderingGroupMask = Math.pow(2, index);
  23073. info.renderingGroupId = index;
  23074. // Before Observable
  23075. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23076. // Clear depth/stencil if needed
  23077. if (RenderingManager.AUTOCLEAR) {
  23078. var autoClear = this._useSceneAutoClearSetup ?
  23079. this._scene.getAutoClearDepthStencilSetup(index) :
  23080. this._autoClearDepthStencil[index];
  23081. if (autoClear && autoClear.autoClear) {
  23082. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23083. }
  23084. }
  23085. // Render
  23086. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23087. var step = _a[_i];
  23088. step.action(index);
  23089. }
  23090. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23091. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23092. var step = _c[_b];
  23093. step.action(index);
  23094. }
  23095. // After Observable
  23096. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23097. }
  23098. };
  23099. RenderingManager.prototype.reset = function () {
  23100. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23101. var renderingGroup = this._renderingGroups[index];
  23102. if (renderingGroup) {
  23103. renderingGroup.prepare();
  23104. }
  23105. }
  23106. };
  23107. RenderingManager.prototype.dispose = function () {
  23108. this.freeRenderingGroups();
  23109. this._renderingGroups.length = 0;
  23110. this._renderingGroupInfo = null;
  23111. };
  23112. /**
  23113. * Clear the info related to rendering groups preventing retention points during dispose.
  23114. */
  23115. RenderingManager.prototype.freeRenderingGroups = function () {
  23116. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23117. var renderingGroup = this._renderingGroups[index];
  23118. if (renderingGroup) {
  23119. renderingGroup.dispose();
  23120. }
  23121. }
  23122. };
  23123. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23124. if (this._renderingGroups[renderingGroupId] === undefined) {
  23125. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23126. }
  23127. };
  23128. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23129. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23130. this._prepareRenderingGroup(renderingGroupId);
  23131. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23132. };
  23133. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23134. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23135. this._prepareRenderingGroup(renderingGroupId);
  23136. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23137. };
  23138. /**
  23139. * @param subMesh The submesh to dispatch
  23140. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23141. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23142. */
  23143. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23144. if (mesh === undefined) {
  23145. mesh = subMesh.getMesh();
  23146. }
  23147. var renderingGroupId = mesh.renderingGroupId || 0;
  23148. this._prepareRenderingGroup(renderingGroupId);
  23149. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23150. };
  23151. /**
  23152. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23153. * This allowed control for front to back rendering or reversly depending of the special needs.
  23154. *
  23155. * @param renderingGroupId The rendering group id corresponding to its index
  23156. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23157. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23158. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23159. */
  23160. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23161. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23162. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23163. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23164. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23165. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23166. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23167. if (this._renderingGroups[renderingGroupId]) {
  23168. var group = this._renderingGroups[renderingGroupId];
  23169. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23170. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23171. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23172. }
  23173. };
  23174. /**
  23175. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23176. *
  23177. * @param renderingGroupId The rendering group id corresponding to its index
  23178. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23179. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23180. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23181. */
  23182. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23183. if (depth === void 0) { depth = true; }
  23184. if (stencil === void 0) { stencil = true; }
  23185. this._autoClearDepthStencil[renderingGroupId] = {
  23186. autoClear: autoClearDepthStencil,
  23187. depth: depth,
  23188. stencil: stencil
  23189. };
  23190. };
  23191. /**
  23192. * Gets the current auto clear configuration for one rendering group of the rendering
  23193. * manager.
  23194. * @param index the rendering group index to get the information for
  23195. * @returns The auto clear setup for the requested rendering group
  23196. */
  23197. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23198. return this._autoClearDepthStencil[index];
  23199. };
  23200. /**
  23201. * The max id used for rendering groups (not included)
  23202. */
  23203. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23204. /**
  23205. * The min id used for rendering groups (included)
  23206. */
  23207. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23208. /**
  23209. * Used to globally prevent autoclearing scenes.
  23210. */
  23211. RenderingManager.AUTOCLEAR = true;
  23212. return RenderingManager;
  23213. }());
  23214. BABYLON.RenderingManager = RenderingManager;
  23215. })(BABYLON || (BABYLON = {}));
  23216. //# sourceMappingURL=babylon.renderingManager.js.map
  23217. var BABYLON;
  23218. (function (BABYLON) {
  23219. var RenderingGroup = /** @class */ (function () {
  23220. /**
  23221. * Creates a new rendering group.
  23222. * @param index The rendering group index
  23223. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23224. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23225. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23226. */
  23227. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23228. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23229. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23230. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23231. this.index = index;
  23232. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23233. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23234. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23235. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23236. this._particleSystems = new BABYLON.SmartArray(256);
  23237. this._spriteManagers = new BABYLON.SmartArray(256);
  23238. this._edgesRenderers = new BABYLON.SmartArray(16);
  23239. this._scene = scene;
  23240. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23241. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23242. this.transparentSortCompareFn = transparentSortCompareFn;
  23243. }
  23244. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23245. /**
  23246. * Set the opaque sort comparison function.
  23247. * If null the sub meshes will be render in the order they were created
  23248. */
  23249. set: function (value) {
  23250. this._opaqueSortCompareFn = value;
  23251. if (value) {
  23252. this._renderOpaque = this.renderOpaqueSorted;
  23253. }
  23254. else {
  23255. this._renderOpaque = RenderingGroup.renderUnsorted;
  23256. }
  23257. },
  23258. enumerable: true,
  23259. configurable: true
  23260. });
  23261. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23262. /**
  23263. * Set the alpha test sort comparison function.
  23264. * If null the sub meshes will be render in the order they were created
  23265. */
  23266. set: function (value) {
  23267. this._alphaTestSortCompareFn = value;
  23268. if (value) {
  23269. this._renderAlphaTest = this.renderAlphaTestSorted;
  23270. }
  23271. else {
  23272. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23273. }
  23274. },
  23275. enumerable: true,
  23276. configurable: true
  23277. });
  23278. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23279. /**
  23280. * Set the transparent sort comparison function.
  23281. * If null the sub meshes will be render in the order they were created
  23282. */
  23283. set: function (value) {
  23284. if (value) {
  23285. this._transparentSortCompareFn = value;
  23286. }
  23287. else {
  23288. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23289. }
  23290. this._renderTransparent = this.renderTransparentSorted;
  23291. },
  23292. enumerable: true,
  23293. configurable: true
  23294. });
  23295. /**
  23296. * Render all the sub meshes contained in the group.
  23297. * @param customRenderFunction Used to override the default render behaviour of the group.
  23298. * @returns true if rendered some submeshes.
  23299. */
  23300. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23301. if (customRenderFunction) {
  23302. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23303. return;
  23304. }
  23305. var engine = this._scene.getEngine();
  23306. // Depth only
  23307. if (this._depthOnlySubMeshes.length !== 0) {
  23308. engine.setColorWrite(false);
  23309. this._renderAlphaTest(this._depthOnlySubMeshes);
  23310. engine.setColorWrite(true);
  23311. }
  23312. // Opaque
  23313. if (this._opaqueSubMeshes.length !== 0) {
  23314. this._renderOpaque(this._opaqueSubMeshes);
  23315. }
  23316. // Alpha test
  23317. if (this._alphaTestSubMeshes.length !== 0) {
  23318. this._renderAlphaTest(this._alphaTestSubMeshes);
  23319. }
  23320. var stencilState = engine.getStencilBuffer();
  23321. engine.setStencilBuffer(false);
  23322. // Sprites
  23323. if (renderSprites) {
  23324. this._renderSprites();
  23325. }
  23326. // Particles
  23327. if (renderParticles) {
  23328. this._renderParticles(activeMeshes);
  23329. }
  23330. if (this.onBeforeTransparentRendering) {
  23331. this.onBeforeTransparentRendering();
  23332. }
  23333. // Transparent
  23334. if (this._transparentSubMeshes.length !== 0) {
  23335. this._renderTransparent(this._transparentSubMeshes);
  23336. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23337. }
  23338. // Set back stencil to false in case it changes before the edge renderer.
  23339. engine.setStencilBuffer(false);
  23340. // Edges
  23341. if (this._edgesRenderers.length) {
  23342. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23343. this._edgesRenderers.data[edgesRendererIndex].render();
  23344. }
  23345. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23346. }
  23347. // Restore Stencil state.
  23348. engine.setStencilBuffer(stencilState);
  23349. };
  23350. /**
  23351. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23352. * @param subMeshes The submeshes to render
  23353. */
  23354. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23355. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23356. };
  23357. /**
  23358. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23359. * @param subMeshes The submeshes to render
  23360. */
  23361. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23362. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23363. };
  23364. /**
  23365. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23366. * @param subMeshes The submeshes to render
  23367. */
  23368. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23369. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23370. };
  23371. /**
  23372. * Renders the submeshes in a specified order.
  23373. * @param subMeshes The submeshes to sort before render
  23374. * @param sortCompareFn The comparison function use to sort
  23375. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23376. * @param transparent Specifies to activate blending if true
  23377. */
  23378. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23379. var subIndex = 0;
  23380. var subMesh;
  23381. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23382. for (; subIndex < subMeshes.length; subIndex++) {
  23383. subMesh = subMeshes.data[subIndex];
  23384. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23385. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23386. }
  23387. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23388. if (sortCompareFn) {
  23389. sortedArray.sort(sortCompareFn);
  23390. }
  23391. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23392. subMesh = sortedArray[subIndex];
  23393. if (transparent) {
  23394. var material = subMesh.getMaterial();
  23395. if (material && material.needDepthPrePass) {
  23396. var engine = material.getScene().getEngine();
  23397. engine.setColorWrite(false);
  23398. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23399. subMesh.render(false);
  23400. engine.setColorWrite(true);
  23401. }
  23402. }
  23403. subMesh.render(transparent);
  23404. }
  23405. };
  23406. /**
  23407. * Renders the submeshes in the order they were dispatched (no sort applied).
  23408. * @param subMeshes The submeshes to render
  23409. */
  23410. RenderingGroup.renderUnsorted = function (subMeshes) {
  23411. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23412. var submesh = subMeshes.data[subIndex];
  23413. submesh.render(false);
  23414. }
  23415. };
  23416. /**
  23417. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23418. * are rendered back to front if in the same alpha index.
  23419. *
  23420. * @param a The first submesh
  23421. * @param b The second submesh
  23422. * @returns The result of the comparison
  23423. */
  23424. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23425. // Alpha index first
  23426. if (a._alphaIndex > b._alphaIndex) {
  23427. return 1;
  23428. }
  23429. if (a._alphaIndex < b._alphaIndex) {
  23430. return -1;
  23431. }
  23432. // Then distance to camera
  23433. return RenderingGroup.backToFrontSortCompare(a, b);
  23434. };
  23435. /**
  23436. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23437. * are rendered back to front.
  23438. *
  23439. * @param a The first submesh
  23440. * @param b The second submesh
  23441. * @returns The result of the comparison
  23442. */
  23443. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23444. // Then distance to camera
  23445. if (a._distanceToCamera < b._distanceToCamera) {
  23446. return 1;
  23447. }
  23448. if (a._distanceToCamera > b._distanceToCamera) {
  23449. return -1;
  23450. }
  23451. return 0;
  23452. };
  23453. /**
  23454. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23455. * are rendered front to back (prevent overdraw).
  23456. *
  23457. * @param a The first submesh
  23458. * @param b The second submesh
  23459. * @returns The result of the comparison
  23460. */
  23461. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23462. // Then distance to camera
  23463. if (a._distanceToCamera < b._distanceToCamera) {
  23464. return -1;
  23465. }
  23466. if (a._distanceToCamera > b._distanceToCamera) {
  23467. return 1;
  23468. }
  23469. return 0;
  23470. };
  23471. /**
  23472. * Resets the different lists of submeshes to prepare a new frame.
  23473. */
  23474. RenderingGroup.prototype.prepare = function () {
  23475. this._opaqueSubMeshes.reset();
  23476. this._transparentSubMeshes.reset();
  23477. this._alphaTestSubMeshes.reset();
  23478. this._depthOnlySubMeshes.reset();
  23479. this._particleSystems.reset();
  23480. this._spriteManagers.reset();
  23481. this._edgesRenderers.reset();
  23482. };
  23483. RenderingGroup.prototype.dispose = function () {
  23484. this._opaqueSubMeshes.dispose();
  23485. this._transparentSubMeshes.dispose();
  23486. this._alphaTestSubMeshes.dispose();
  23487. this._depthOnlySubMeshes.dispose();
  23488. this._particleSystems.dispose();
  23489. this._spriteManagers.dispose();
  23490. this._edgesRenderers.dispose();
  23491. };
  23492. /**
  23493. * Inserts the submesh in its correct queue depending on its material.
  23494. * @param subMesh The submesh to dispatch
  23495. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23496. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23497. */
  23498. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23499. // Get mesh and materials if not provided
  23500. if (mesh === undefined) {
  23501. mesh = subMesh.getMesh();
  23502. }
  23503. if (material === undefined) {
  23504. material = subMesh.getMaterial();
  23505. }
  23506. if (material === null || material === undefined) {
  23507. return;
  23508. }
  23509. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23510. this._transparentSubMeshes.push(subMesh);
  23511. }
  23512. else if (material.needAlphaTesting()) { // Alpha test
  23513. if (material.needDepthPrePass) {
  23514. this._depthOnlySubMeshes.push(subMesh);
  23515. }
  23516. this._alphaTestSubMeshes.push(subMesh);
  23517. }
  23518. else {
  23519. if (material.needDepthPrePass) {
  23520. this._depthOnlySubMeshes.push(subMesh);
  23521. }
  23522. this._opaqueSubMeshes.push(subMesh); // Opaque
  23523. }
  23524. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  23525. this._edgesRenderers.push(mesh._edgesRenderer);
  23526. }
  23527. };
  23528. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23529. this._spriteManagers.push(spriteManager);
  23530. };
  23531. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23532. this._particleSystems.push(particleSystem);
  23533. };
  23534. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23535. if (this._particleSystems.length === 0) {
  23536. return;
  23537. }
  23538. // Particles
  23539. var activeCamera = this._scene.activeCamera;
  23540. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23541. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23542. var particleSystem = this._particleSystems.data[particleIndex];
  23543. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23544. continue;
  23545. }
  23546. var emitter = particleSystem.emitter;
  23547. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23548. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23549. }
  23550. }
  23551. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23552. };
  23553. RenderingGroup.prototype._renderSprites = function () {
  23554. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23555. return;
  23556. }
  23557. // Sprites
  23558. var activeCamera = this._scene.activeCamera;
  23559. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23560. for (var id = 0; id < this._spriteManagers.length; id++) {
  23561. var spriteManager = this._spriteManagers.data[id];
  23562. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23563. spriteManager.render();
  23564. }
  23565. }
  23566. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23567. };
  23568. return RenderingGroup;
  23569. }());
  23570. BABYLON.RenderingGroup = RenderingGroup;
  23571. })(BABYLON || (BABYLON = {}));
  23572. //# sourceMappingURL=babylon.renderingGroup.js.map
  23573. var BABYLON;
  23574. (function (BABYLON) {
  23575. /**
  23576. * Groups all the scene component constants in one place to ease maintenance.
  23577. * @hidden
  23578. */
  23579. var SceneComponentConstants = /** @class */ (function () {
  23580. function SceneComponentConstants() {
  23581. }
  23582. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23583. SceneComponentConstants.NAME_LAYER = "Layer";
  23584. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23585. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23586. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23587. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23588. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23589. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23590. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23591. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  23592. SceneComponentConstants.NAME_SPRITE = "Sprite";
  23593. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  23594. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  23595. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  23596. SceneComponentConstants.NAME_OCTREE = "Octree";
  23597. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  23598. SceneComponentConstants.NAME_AUDIO = "Audio";
  23599. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23600. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23601. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23602. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23603. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23604. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23605. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23606. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  23607. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  23608. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23609. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  23610. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23611. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23612. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  23613. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23614. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23615. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  23616. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  23617. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  23618. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  23619. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  23620. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  23621. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  23622. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  23623. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  23624. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  23625. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  23626. return SceneComponentConstants;
  23627. }());
  23628. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23629. /**
  23630. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23631. * @hidden
  23632. */
  23633. var Stage = /** @class */ (function (_super) {
  23634. __extends(Stage, _super);
  23635. /**
  23636. * Hide ctor from the rest of the world.
  23637. * @param items The items to add.
  23638. */
  23639. function Stage(items) {
  23640. return _super.apply(this, items) || this;
  23641. }
  23642. /**
  23643. * Creates a new Stage.
  23644. * @returns A new instance of a Stage
  23645. */
  23646. Stage.Create = function () {
  23647. return Object.create(Stage.prototype);
  23648. };
  23649. /**
  23650. * Registers a step in an ordered way in the targeted stage.
  23651. * @param index Defines the position to register the step in
  23652. * @param component Defines the component attached to the step
  23653. * @param action Defines the action to launch during the step
  23654. */
  23655. Stage.prototype.registerStep = function (index, component, action) {
  23656. var i = 0;
  23657. var maxIndex = Number.MAX_VALUE;
  23658. for (; i < this.length && i < maxIndex; i++) {
  23659. var step = this[i];
  23660. maxIndex = step.index;
  23661. }
  23662. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23663. };
  23664. /**
  23665. * Clears all the steps from the stage.
  23666. */
  23667. Stage.prototype.clear = function () {
  23668. this.length = 0;
  23669. };
  23670. return Stage;
  23671. }(Array));
  23672. BABYLON.Stage = Stage;
  23673. })(BABYLON || (BABYLON = {}));
  23674. //# sourceMappingURL=babylon.sceneComponent.js.map
  23675. var BABYLON;
  23676. (function (BABYLON) {
  23677. /**
  23678. * Base class of the scene acting as a container for the different elements composing a scene.
  23679. * This class is dynamically extended by the different components of the scene increasing
  23680. * flexibility and reducing coupling
  23681. */
  23682. var AbstractScene = /** @class */ (function () {
  23683. function AbstractScene() {
  23684. /**
  23685. * Gets the list of root nodes (ie. nodes with no parent)
  23686. */
  23687. this.rootNodes = new Array();
  23688. /** All of the cameras added to this scene
  23689. * @see http://doc.babylonjs.com/babylon101/cameras
  23690. */
  23691. this.cameras = new Array();
  23692. /**
  23693. * All of the lights added to this scene
  23694. * @see http://doc.babylonjs.com/babylon101/lights
  23695. */
  23696. this.lights = new Array();
  23697. /**
  23698. * All of the (abstract) meshes added to this scene
  23699. */
  23700. this.meshes = new Array();
  23701. /**
  23702. * The list of skeletons added to the scene
  23703. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23704. */
  23705. this.skeletons = new Array();
  23706. /**
  23707. * All of the particle systems added to this scene
  23708. * @see http://doc.babylonjs.com/babylon101/particles
  23709. */
  23710. this.particleSystems = new Array();
  23711. /**
  23712. * Gets a list of Animations associated with the scene
  23713. */
  23714. this.animations = [];
  23715. /**
  23716. * All of the animation groups added to this scene
  23717. * @see http://doc.babylonjs.com/how_to/group
  23718. */
  23719. this.animationGroups = new Array();
  23720. /**
  23721. * All of the multi-materials added to this scene
  23722. * @see http://doc.babylonjs.com/how_to/multi_materials
  23723. */
  23724. this.multiMaterials = new Array();
  23725. /**
  23726. * All of the materials added to this scene
  23727. * @see http://doc.babylonjs.com/babylon101/materials
  23728. */
  23729. this.materials = new Array();
  23730. /**
  23731. * The list of morph target managers added to the scene
  23732. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23733. */
  23734. this.morphTargetManagers = new Array();
  23735. /**
  23736. * The list of geometries used in the scene.
  23737. */
  23738. this.geometries = new Array();
  23739. /**
  23740. * All of the tranform nodes added to this scene
  23741. * @see http://doc.babylonjs.com/how_to/transformnode
  23742. */
  23743. this.transformNodes = new Array();
  23744. /**
  23745. * ActionManagers available on the scene.
  23746. */
  23747. this.actionManagers = new Array();
  23748. /**
  23749. * Textures to keep.
  23750. */
  23751. this.textures = new Array();
  23752. }
  23753. /**
  23754. * Adds a parser in the list of available ones
  23755. * @param name Defines the name of the parser
  23756. * @param parser Defines the parser to add
  23757. */
  23758. AbstractScene.AddParser = function (name, parser) {
  23759. this._BabylonFileParsers[name] = parser;
  23760. };
  23761. /**
  23762. * Gets a general parser from the list of avaialble ones
  23763. * @param name Defines the name of the parser
  23764. * @returns the requested parser or null
  23765. */
  23766. AbstractScene.GetParser = function (name) {
  23767. if (this._BabylonFileParsers[name]) {
  23768. return this._BabylonFileParsers[name];
  23769. }
  23770. return null;
  23771. };
  23772. /**
  23773. * Adds n individual parser in the list of available ones
  23774. * @param name Defines the name of the parser
  23775. * @param parser Defines the parser to add
  23776. */
  23777. AbstractScene.AddIndividualParser = function (name, parser) {
  23778. this._IndividualBabylonFileParsers[name] = parser;
  23779. };
  23780. /**
  23781. * Gets an individual parser from the list of avaialble ones
  23782. * @param name Defines the name of the parser
  23783. * @returns the requested parser or null
  23784. */
  23785. AbstractScene.GetIndividualParser = function (name) {
  23786. if (this._IndividualBabylonFileParsers[name]) {
  23787. return this._IndividualBabylonFileParsers[name];
  23788. }
  23789. return null;
  23790. };
  23791. /**
  23792. * Parser json data and populate both a scene and its associated container object
  23793. * @param jsonData Defines the data to parse
  23794. * @param scene Defines the scene to parse the data for
  23795. * @param container Defines the container attached to the parsing sequence
  23796. * @param rootUrl Defines the root url of the data
  23797. */
  23798. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23799. for (var parserName in this._BabylonFileParsers) {
  23800. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23801. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23802. }
  23803. }
  23804. };
  23805. /**
  23806. * Stores the list of available parsers in the application.
  23807. */
  23808. AbstractScene._BabylonFileParsers = {};
  23809. /**
  23810. * Stores the list of available individual parsers in the application.
  23811. */
  23812. AbstractScene._IndividualBabylonFileParsers = {};
  23813. return AbstractScene;
  23814. }());
  23815. BABYLON.AbstractScene = AbstractScene;
  23816. })(BABYLON || (BABYLON = {}));
  23817. //# sourceMappingURL=babylon.abstractScene.js.map
  23818. var BABYLON;
  23819. (function (BABYLON) {
  23820. /** @hidden */
  23821. var ClickInfo = /** @class */ (function () {
  23822. function ClickInfo() {
  23823. this._singleClick = false;
  23824. this._doubleClick = false;
  23825. this._hasSwiped = false;
  23826. this._ignore = false;
  23827. }
  23828. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23829. get: function () {
  23830. return this._singleClick;
  23831. },
  23832. set: function (b) {
  23833. this._singleClick = b;
  23834. },
  23835. enumerable: true,
  23836. configurable: true
  23837. });
  23838. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23839. get: function () {
  23840. return this._doubleClick;
  23841. },
  23842. set: function (b) {
  23843. this._doubleClick = b;
  23844. },
  23845. enumerable: true,
  23846. configurable: true
  23847. });
  23848. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23849. get: function () {
  23850. return this._hasSwiped;
  23851. },
  23852. set: function (b) {
  23853. this._hasSwiped = b;
  23854. },
  23855. enumerable: true,
  23856. configurable: true
  23857. });
  23858. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23859. get: function () {
  23860. return this._ignore;
  23861. },
  23862. set: function (b) {
  23863. this._ignore = b;
  23864. },
  23865. enumerable: true,
  23866. configurable: true
  23867. });
  23868. return ClickInfo;
  23869. }());
  23870. /**
  23871. * This class is used by the onRenderingGroupObservable
  23872. */
  23873. var RenderingGroupInfo = /** @class */ (function () {
  23874. function RenderingGroupInfo() {
  23875. }
  23876. return RenderingGroupInfo;
  23877. }());
  23878. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23879. /**
  23880. * Represents a scene to be rendered by the engine.
  23881. * @see http://doc.babylonjs.com/features/scene
  23882. */
  23883. var Scene = /** @class */ (function (_super) {
  23884. __extends(Scene, _super);
  23885. /**
  23886. * Creates a new Scene
  23887. * @param engine defines the engine to use to render this scene
  23888. */
  23889. function Scene(engine) {
  23890. var _this = _super.call(this) || this;
  23891. // Members
  23892. /**
  23893. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23894. */
  23895. _this.autoClear = true;
  23896. /**
  23897. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23898. */
  23899. _this.autoClearDepthAndStencil = true;
  23900. /**
  23901. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23902. */
  23903. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23904. /**
  23905. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23906. */
  23907. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23908. _this._forceWireframe = false;
  23909. _this._forcePointsCloud = false;
  23910. /**
  23911. * Gets or sets a boolean indicating if animations are enabled
  23912. */
  23913. _this.animationsEnabled = true;
  23914. _this._animationPropertiesOverride = null;
  23915. /**
  23916. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23917. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23918. */
  23919. _this.useConstantAnimationDeltaTime = false;
  23920. /**
  23921. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23922. * Please note that it requires to run a ray cast through the scene on every frame
  23923. */
  23924. _this.constantlyUpdateMeshUnderPointer = false;
  23925. /**
  23926. * Defines the HTML cursor to use when hovering over interactive elements
  23927. */
  23928. _this.hoverCursor = "pointer";
  23929. /**
  23930. * Defines the HTML default cursor to use (empty by default)
  23931. */
  23932. _this.defaultCursor = "";
  23933. /**
  23934. * This is used to call preventDefault() on pointer down
  23935. * in order to block unwanted artifacts like system double clicks
  23936. */
  23937. _this.preventDefaultOnPointerDown = true;
  23938. // Metadata
  23939. /**
  23940. * Gets or sets user defined metadata
  23941. */
  23942. _this.metadata = null;
  23943. /**
  23944. * Use this array to add regular expressions used to disable offline support for specific urls
  23945. */
  23946. _this.disableOfflineSupportExceptionRules = new Array();
  23947. /**
  23948. * An event triggered when the scene is disposed.
  23949. */
  23950. _this.onDisposeObservable = new BABYLON.Observable();
  23951. _this._onDisposeObserver = null;
  23952. /**
  23953. * An event triggered before rendering the scene (right after animations and physics)
  23954. */
  23955. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23956. _this._onBeforeRenderObserver = null;
  23957. /**
  23958. * An event triggered after rendering the scene
  23959. */
  23960. _this.onAfterRenderObservable = new BABYLON.Observable();
  23961. _this._onAfterRenderObserver = null;
  23962. /**
  23963. * An event triggered before animating the scene
  23964. */
  23965. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23966. /**
  23967. * An event triggered after animations processing
  23968. */
  23969. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23970. /**
  23971. * An event triggered before draw calls are ready to be sent
  23972. */
  23973. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23974. /**
  23975. * An event triggered after draw calls have been sent
  23976. */
  23977. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23978. /**
  23979. * An event triggered when the scene is ready
  23980. */
  23981. _this.onReadyObservable = new BABYLON.Observable();
  23982. /**
  23983. * An event triggered before rendering a camera
  23984. */
  23985. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23986. _this._onBeforeCameraRenderObserver = null;
  23987. /**
  23988. * An event triggered after rendering a camera
  23989. */
  23990. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23991. _this._onAfterCameraRenderObserver = null;
  23992. /**
  23993. * An event triggered when active meshes evaluation is about to start
  23994. */
  23995. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23996. /**
  23997. * An event triggered when active meshes evaluation is done
  23998. */
  23999. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24000. /**
  24001. * An event triggered when particles rendering is about to start
  24002. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24003. */
  24004. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24005. /**
  24006. * An event triggered when particles rendering is done
  24007. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24008. */
  24009. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24010. /**
  24011. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24012. */
  24013. _this.onDataLoadedObservable = new BABYLON.Observable();
  24014. /**
  24015. * An event triggered when a camera is created
  24016. */
  24017. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24018. /**
  24019. * An event triggered when a camera is removed
  24020. */
  24021. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24022. /**
  24023. * An event triggered when a light is created
  24024. */
  24025. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24026. /**
  24027. * An event triggered when a light is removed
  24028. */
  24029. _this.onLightRemovedObservable = new BABYLON.Observable();
  24030. /**
  24031. * An event triggered when a geometry is created
  24032. */
  24033. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24034. /**
  24035. * An event triggered when a geometry is removed
  24036. */
  24037. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24038. /**
  24039. * An event triggered when a transform node is created
  24040. */
  24041. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24042. /**
  24043. * An event triggered when a transform node is removed
  24044. */
  24045. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24046. /**
  24047. * An event triggered when a mesh is created
  24048. */
  24049. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24050. /**
  24051. * An event triggered when a mesh is removed
  24052. */
  24053. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24054. /**
  24055. * An event triggered when render targets are about to be rendered
  24056. * Can happen multiple times per frame.
  24057. */
  24058. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24059. /**
  24060. * An event triggered when render targets were rendered.
  24061. * Can happen multiple times per frame.
  24062. */
  24063. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24064. /**
  24065. * An event triggered before calculating deterministic simulation step
  24066. */
  24067. _this.onBeforeStepObservable = new BABYLON.Observable();
  24068. /**
  24069. * An event triggered after calculating deterministic simulation step
  24070. */
  24071. _this.onAfterStepObservable = new BABYLON.Observable();
  24072. /**
  24073. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24074. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24075. * 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)
  24076. */
  24077. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24078. /**
  24079. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24080. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24081. * 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)
  24082. */
  24083. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24084. /**
  24085. * This Observable will when a mesh has been imported into the scene.
  24086. */
  24087. _this.onMeshImportedObservable = new BABYLON.Observable();
  24088. // Animations
  24089. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24090. /**
  24091. * 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).
  24092. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24093. */
  24094. _this.onPrePointerObservable = new BABYLON.Observable();
  24095. /**
  24096. * Observable event triggered each time an input event is received from the rendering canvas
  24097. */
  24098. _this.onPointerObservable = new BABYLON.Observable();
  24099. _this._meshPickProceed = false;
  24100. _this._currentPickResult = null;
  24101. _this._previousPickResult = null;
  24102. _this._totalPointersPressed = 0;
  24103. _this._doubleClickOccured = false;
  24104. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24105. _this.cameraToUseForPointers = null;
  24106. _this._pointerX = 0;
  24107. _this._pointerY = 0;
  24108. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24109. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24110. _this._startingPointerTime = 0;
  24111. _this._previousStartingPointerTime = 0;
  24112. _this._pointerCaptures = {};
  24113. // Deterministic lockstep
  24114. _this._timeAccumulator = 0;
  24115. _this._currentStepId = 0;
  24116. _this._currentInternalStep = 0;
  24117. // Keyboard
  24118. /**
  24119. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24120. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24121. */
  24122. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24123. /**
  24124. * Observable event triggered each time an keyboard event is received from the hosting window
  24125. */
  24126. _this.onKeyboardObservable = new BABYLON.Observable();
  24127. // Coordinates system
  24128. _this._useRightHandedSystem = false;
  24129. // Fog
  24130. _this._fogEnabled = true;
  24131. _this._fogMode = Scene.FOGMODE_NONE;
  24132. /**
  24133. * Gets or sets the fog color to use
  24134. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24135. */
  24136. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24137. /**
  24138. * Gets or sets the fog density to use
  24139. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24140. */
  24141. _this.fogDensity = 0.1;
  24142. /**
  24143. * Gets or sets the fog start distance to use
  24144. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24145. */
  24146. _this.fogStart = 0;
  24147. /**
  24148. * Gets or sets the fog end distance to use
  24149. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24150. */
  24151. _this.fogEnd = 1000.0;
  24152. // Lights
  24153. _this._shadowsEnabled = true;
  24154. _this._lightsEnabled = true;
  24155. /** All of the active cameras added to this scene. */
  24156. _this.activeCameras = new Array();
  24157. // Textures
  24158. _this._texturesEnabled = true;
  24159. // Particles
  24160. /**
  24161. * Gets or sets a boolean indicating if particles are enabled on this scene
  24162. */
  24163. _this.particlesEnabled = true;
  24164. // Sprites
  24165. /**
  24166. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24167. */
  24168. _this.spritesEnabled = true;
  24169. // Skeletons
  24170. _this._skeletonsEnabled = true;
  24171. // Lens flares
  24172. /**
  24173. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24174. */
  24175. _this.lensFlaresEnabled = true;
  24176. // Collisions
  24177. /**
  24178. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24179. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24180. */
  24181. _this.collisionsEnabled = true;
  24182. /**
  24183. * Defines the gravity applied to this scene (used only for collisions)
  24184. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24185. */
  24186. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24187. // Postprocesses
  24188. /**
  24189. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24190. */
  24191. _this.postProcessesEnabled = true;
  24192. /**
  24193. * The list of postprocesses added to the scene
  24194. */
  24195. _this.postProcesses = new Array();
  24196. // Customs render targets
  24197. /**
  24198. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24199. */
  24200. _this.renderTargetsEnabled = true;
  24201. /**
  24202. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24203. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24204. */
  24205. _this.dumpNextRenderTargets = false;
  24206. /**
  24207. * The list of user defined render targets added to the scene
  24208. */
  24209. _this.customRenderTargets = new Array();
  24210. /**
  24211. * Gets the list of meshes imported to the scene through SceneLoader
  24212. */
  24213. _this.importedMeshesFiles = new Array();
  24214. // Probes
  24215. /**
  24216. * Gets or sets a boolean indicating if probes are enabled on this scene
  24217. */
  24218. _this.probesEnabled = true;
  24219. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24220. // Procedural textures
  24221. /**
  24222. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24223. */
  24224. _this.proceduralTexturesEnabled = true;
  24225. // Performance counters
  24226. _this._totalVertices = new BABYLON.PerfCounter();
  24227. /** @hidden */
  24228. _this._activeIndices = new BABYLON.PerfCounter();
  24229. /** @hidden */
  24230. _this._activeParticles = new BABYLON.PerfCounter();
  24231. /** @hidden */
  24232. _this._activeBones = new BABYLON.PerfCounter();
  24233. _this._animationTime = 0;
  24234. /**
  24235. * Gets or sets a general scale for animation speed
  24236. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24237. */
  24238. _this.animationTimeScale = 1;
  24239. _this._renderId = 0;
  24240. _this._frameId = 0;
  24241. _this._executeWhenReadyTimeoutId = -1;
  24242. _this._intermediateRendering = false;
  24243. _this._viewUpdateFlag = -1;
  24244. _this._projectionUpdateFlag = -1;
  24245. _this._alternateViewUpdateFlag = -1;
  24246. _this._alternateProjectionUpdateFlag = -1;
  24247. /** @hidden */
  24248. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24249. _this._activeRequests = new Array();
  24250. _this._pendingData = new Array();
  24251. _this._isDisposed = false;
  24252. /**
  24253. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24254. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24255. */
  24256. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24257. _this._activeMeshes = new BABYLON.SmartArray(256);
  24258. _this._processedMaterials = new BABYLON.SmartArray(256);
  24259. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24260. /** @hidden */
  24261. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24262. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24263. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24264. /** @hidden */
  24265. _this._activeAnimatables = new Array();
  24266. _this._transformMatrix = BABYLON.Matrix.Zero();
  24267. _this._useAlternateCameraConfiguration = false;
  24268. _this._alternateRendering = false;
  24269. /**
  24270. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24271. * This is useful if there are more lights that the maximum simulteanous authorized
  24272. */
  24273. _this.requireLightSorting = false;
  24274. /**
  24275. * @hidden
  24276. * Backing store of defined scene components.
  24277. */
  24278. _this._components = [];
  24279. /**
  24280. * @hidden
  24281. * Backing store of defined scene components.
  24282. */
  24283. _this._serializableComponents = [];
  24284. /**
  24285. * List of components to register on the next registration step.
  24286. */
  24287. _this._transientComponents = [];
  24288. /**
  24289. * @hidden
  24290. * Defines the actions happening before camera updates.
  24291. */
  24292. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24293. /**
  24294. * @hidden
  24295. * Defines the actions happening before clear the canvas.
  24296. */
  24297. _this._beforeClearStage = BABYLON.Stage.Create();
  24298. /**
  24299. * @hidden
  24300. * Defines the actions when collecting render targets for the frame.
  24301. */
  24302. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24303. /**
  24304. * @hidden
  24305. * Defines the actions happening for one camera in the frame.
  24306. */
  24307. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  24308. /**
  24309. * @hidden
  24310. * Defines the actions happening during the per mesh ready checks.
  24311. */
  24312. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24313. /**
  24314. * @hidden
  24315. * Defines the actions happening before evaluate active mesh checks.
  24316. */
  24317. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24318. /**
  24319. * @hidden
  24320. * Defines the actions happening during the evaluate sub mesh checks.
  24321. */
  24322. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24323. /**
  24324. * @hidden
  24325. * Defines the actions happening during the active mesh stage.
  24326. */
  24327. _this._activeMeshStage = BABYLON.Stage.Create();
  24328. /**
  24329. * @hidden
  24330. * Defines the actions happening during the per camera render target step.
  24331. */
  24332. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24333. /**
  24334. * @hidden
  24335. * Defines the actions happening just before the active camera is drawing.
  24336. */
  24337. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24338. /**
  24339. * @hidden
  24340. * Defines the actions happening just before a rendering group is drawing.
  24341. */
  24342. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24343. /**
  24344. * @hidden
  24345. * Defines the actions happening just before a mesh is drawing.
  24346. */
  24347. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  24348. /**
  24349. * @hidden
  24350. * Defines the actions happening just after a mesh has been drawn.
  24351. */
  24352. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  24353. /**
  24354. * @hidden
  24355. * Defines the actions happening just after a rendering group has been drawn.
  24356. */
  24357. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24358. /**
  24359. * @hidden
  24360. * Defines the actions happening just after the active camera has been drawn.
  24361. */
  24362. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24363. /**
  24364. * @hidden
  24365. * Defines the actions happening just after rendering all cameras and computing intersections.
  24366. */
  24367. _this._afterRenderStage = BABYLON.Stage.Create();
  24368. /**
  24369. * @hidden
  24370. * Defines the actions happening when a pointer move event happens.
  24371. */
  24372. _this._pointerMoveStage = BABYLON.Stage.Create();
  24373. /**
  24374. * @hidden
  24375. * Defines the actions happening when a pointer down event happens.
  24376. */
  24377. _this._pointerDownStage = BABYLON.Stage.Create();
  24378. /**
  24379. * @hidden
  24380. * Defines the actions happening when a pointer up event happens.
  24381. */
  24382. _this._pointerUpStage = BABYLON.Stage.Create();
  24383. _this._defaultMeshCandidates = {
  24384. data: [],
  24385. length: 0
  24386. };
  24387. _this._defaultSubMeshCandidates = {
  24388. data: [],
  24389. length: 0
  24390. };
  24391. _this._activeMeshesFrozen = false;
  24392. /** @hidden */
  24393. _this._allowPostProcessClearColor = true;
  24394. /**
  24395. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  24396. */
  24397. _this.getDeterministicFrameTime = function () {
  24398. return 1000.0 / 60.0; // frame time in ms
  24399. };
  24400. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24401. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  24402. _this.blockMaterialDirtyMechanism = false;
  24403. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24404. _this._engine.scenes.push(_this);
  24405. _this._uid = null;
  24406. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24407. if (BABYLON.PostProcessManager) {
  24408. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24409. }
  24410. if (BABYLON.Tools.IsWindowObjectExist()) {
  24411. _this.attachControl();
  24412. }
  24413. //collision coordinator initialization. For now legacy per default.
  24414. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24415. // Uniform Buffer
  24416. _this._createUbo();
  24417. // Default Image processing definition
  24418. if (BABYLON.ImageProcessingConfiguration) {
  24419. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24420. }
  24421. _this.setDefaultCandidateProviders();
  24422. return _this;
  24423. }
  24424. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24425. /**
  24426. * Texture used in all pbr material as the reflection texture.
  24427. * As in the majority of the scene they are the same (exception for multi room and so on),
  24428. * this is easier to reference from here than from all the materials.
  24429. */
  24430. get: function () {
  24431. return this._environmentTexture;
  24432. },
  24433. /**
  24434. * Texture used in all pbr material as the reflection texture.
  24435. * As in the majority of the scene they are the same (exception for multi room and so on),
  24436. * this is easier to set here than in all the materials.
  24437. */
  24438. set: function (value) {
  24439. if (this._environmentTexture === value) {
  24440. return;
  24441. }
  24442. this._environmentTexture = value;
  24443. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24444. },
  24445. enumerable: true,
  24446. configurable: true
  24447. });
  24448. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24449. /**
  24450. * Default image processing configuration used either in the rendering
  24451. * Forward main pass or through the imageProcessingPostProcess if present.
  24452. * As in the majority of the scene they are the same (exception for multi camera),
  24453. * this is easier to reference from here than from all the materials and post process.
  24454. *
  24455. * No setter as we it is a shared configuration, you can set the values instead.
  24456. */
  24457. get: function () {
  24458. return this._imageProcessingConfiguration;
  24459. },
  24460. enumerable: true,
  24461. configurable: true
  24462. });
  24463. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24464. get: function () {
  24465. return this._forceWireframe;
  24466. },
  24467. /**
  24468. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24469. */
  24470. set: function (value) {
  24471. if (this._forceWireframe === value) {
  24472. return;
  24473. }
  24474. this._forceWireframe = value;
  24475. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24476. },
  24477. enumerable: true,
  24478. configurable: true
  24479. });
  24480. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24481. get: function () {
  24482. return this._forcePointsCloud;
  24483. },
  24484. /**
  24485. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24486. */
  24487. set: function (value) {
  24488. if (this._forcePointsCloud === value) {
  24489. return;
  24490. }
  24491. this._forcePointsCloud = value;
  24492. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24493. },
  24494. enumerable: true,
  24495. configurable: true
  24496. });
  24497. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24498. /**
  24499. * Gets or sets the animation properties override
  24500. */
  24501. get: function () {
  24502. return this._animationPropertiesOverride;
  24503. },
  24504. set: function (value) {
  24505. this._animationPropertiesOverride = value;
  24506. },
  24507. enumerable: true,
  24508. configurable: true
  24509. });
  24510. Object.defineProperty(Scene.prototype, "onDispose", {
  24511. /** Sets a function to be executed when this scene is disposed. */
  24512. set: function (callback) {
  24513. if (this._onDisposeObserver) {
  24514. this.onDisposeObservable.remove(this._onDisposeObserver);
  24515. }
  24516. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24517. },
  24518. enumerable: true,
  24519. configurable: true
  24520. });
  24521. Object.defineProperty(Scene.prototype, "beforeRender", {
  24522. /** Sets a function to be executed before rendering this scene */
  24523. set: function (callback) {
  24524. if (this._onBeforeRenderObserver) {
  24525. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24526. }
  24527. if (callback) {
  24528. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24529. }
  24530. },
  24531. enumerable: true,
  24532. configurable: true
  24533. });
  24534. Object.defineProperty(Scene.prototype, "afterRender", {
  24535. /** Sets a function to be executed after rendering this scene */
  24536. set: function (callback) {
  24537. if (this._onAfterRenderObserver) {
  24538. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24539. }
  24540. if (callback) {
  24541. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24542. }
  24543. },
  24544. enumerable: true,
  24545. configurable: true
  24546. });
  24547. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24548. /** Sets a function to be executed before rendering a camera*/
  24549. set: function (callback) {
  24550. if (this._onBeforeCameraRenderObserver) {
  24551. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24552. }
  24553. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24554. },
  24555. enumerable: true,
  24556. configurable: true
  24557. });
  24558. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24559. /** Sets a function to be executed after rendering a camera*/
  24560. set: function (callback) {
  24561. if (this._onAfterCameraRenderObserver) {
  24562. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24563. }
  24564. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24565. },
  24566. enumerable: true,
  24567. configurable: true
  24568. });
  24569. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24570. /**
  24571. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24572. */
  24573. get: function () {
  24574. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24575. },
  24576. enumerable: true,
  24577. configurable: true
  24578. });
  24579. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24580. get: function () {
  24581. return this._useRightHandedSystem;
  24582. },
  24583. /**
  24584. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24585. */
  24586. set: function (value) {
  24587. if (this._useRightHandedSystem === value) {
  24588. return;
  24589. }
  24590. this._useRightHandedSystem = value;
  24591. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24592. },
  24593. enumerable: true,
  24594. configurable: true
  24595. });
  24596. /**
  24597. * Sets the step Id used by deterministic lock step
  24598. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24599. * @param newStepId defines the step Id
  24600. */
  24601. Scene.prototype.setStepId = function (newStepId) {
  24602. this._currentStepId = newStepId;
  24603. };
  24604. ;
  24605. /**
  24606. * Gets the step Id used by deterministic lock step
  24607. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24608. * @returns the step Id
  24609. */
  24610. Scene.prototype.getStepId = function () {
  24611. return this._currentStepId;
  24612. };
  24613. ;
  24614. /**
  24615. * Gets the internal step used by deterministic lock step
  24616. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24617. * @returns the internal step
  24618. */
  24619. Scene.prototype.getInternalStep = function () {
  24620. return this._currentInternalStep;
  24621. };
  24622. ;
  24623. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24624. get: function () {
  24625. return this._fogEnabled;
  24626. },
  24627. /**
  24628. * Gets or sets a boolean indicating if fog is enabled on this scene
  24629. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24630. */
  24631. set: function (value) {
  24632. if (this._fogEnabled === value) {
  24633. return;
  24634. }
  24635. this._fogEnabled = value;
  24636. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24637. },
  24638. enumerable: true,
  24639. configurable: true
  24640. });
  24641. Object.defineProperty(Scene.prototype, "fogMode", {
  24642. get: function () {
  24643. return this._fogMode;
  24644. },
  24645. /**
  24646. * Gets or sets the fog mode to use
  24647. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24648. */
  24649. set: function (value) {
  24650. if (this._fogMode === value) {
  24651. return;
  24652. }
  24653. this._fogMode = value;
  24654. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24655. },
  24656. enumerable: true,
  24657. configurable: true
  24658. });
  24659. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24660. get: function () {
  24661. return this._shadowsEnabled;
  24662. },
  24663. /**
  24664. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24665. */
  24666. set: function (value) {
  24667. if (this._shadowsEnabled === value) {
  24668. return;
  24669. }
  24670. this._shadowsEnabled = value;
  24671. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24672. },
  24673. enumerable: true,
  24674. configurable: true
  24675. });
  24676. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24677. get: function () {
  24678. return this._lightsEnabled;
  24679. },
  24680. /**
  24681. * Gets or sets a boolean indicating if lights are enabled on this scene
  24682. */
  24683. set: function (value) {
  24684. if (this._lightsEnabled === value) {
  24685. return;
  24686. }
  24687. this._lightsEnabled = value;
  24688. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24689. },
  24690. enumerable: true,
  24691. configurable: true
  24692. });
  24693. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24694. /** The default material used on meshes when no material is affected */
  24695. get: function () {
  24696. if (!this._defaultMaterial) {
  24697. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24698. }
  24699. return this._defaultMaterial;
  24700. },
  24701. /** The default material used on meshes when no material is affected */
  24702. set: function (value) {
  24703. this._defaultMaterial = value;
  24704. },
  24705. enumerable: true,
  24706. configurable: true
  24707. });
  24708. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24709. get: function () {
  24710. return this._texturesEnabled;
  24711. },
  24712. /**
  24713. * Gets or sets a boolean indicating if textures are enabled on this scene
  24714. */
  24715. set: function (value) {
  24716. if (this._texturesEnabled === value) {
  24717. return;
  24718. }
  24719. this._texturesEnabled = value;
  24720. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24721. },
  24722. enumerable: true,
  24723. configurable: true
  24724. });
  24725. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24726. get: function () {
  24727. return this._skeletonsEnabled;
  24728. },
  24729. /**
  24730. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24731. */
  24732. set: function (value) {
  24733. if (this._skeletonsEnabled === value) {
  24734. return;
  24735. }
  24736. this._skeletonsEnabled = value;
  24737. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24738. },
  24739. enumerable: true,
  24740. configurable: true
  24741. });
  24742. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24743. /** @hidden */
  24744. get: function () {
  24745. return this._alternateRendering;
  24746. },
  24747. enumerable: true,
  24748. configurable: true
  24749. });
  24750. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24751. /**
  24752. * Gets the list of frustum planes (built from the active camera)
  24753. */
  24754. get: function () {
  24755. return this._frustumPlanes;
  24756. },
  24757. enumerable: true,
  24758. configurable: true
  24759. });
  24760. /**
  24761. * Registers the transient components if needed.
  24762. */
  24763. Scene.prototype._registerTransientComponents = function () {
  24764. // Register components that have been associated lately to the scene.
  24765. if (this._transientComponents.length > 0) {
  24766. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24767. var component = _a[_i];
  24768. component.register();
  24769. }
  24770. this._transientComponents = [];
  24771. }
  24772. };
  24773. /**
  24774. * @hidden
  24775. * Add a component to the scene.
  24776. * Note that the ccomponent could be registered on th next frame if this is called after
  24777. * the register component stage.
  24778. * @param component Defines the component to add to the scene
  24779. */
  24780. Scene.prototype._addComponent = function (component) {
  24781. this._components.push(component);
  24782. this._transientComponents.push(component);
  24783. var serializableComponent = component;
  24784. if (serializableComponent.addFromContainer) {
  24785. this._serializableComponents.push(serializableComponent);
  24786. }
  24787. };
  24788. /**
  24789. * @hidden
  24790. * Gets a component from the scene.
  24791. * @param name defines the name of the component to retrieve
  24792. * @returns the component or null if not present
  24793. */
  24794. Scene.prototype._getComponent = function (name) {
  24795. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24796. var component = _a[_i];
  24797. if (component.name === name) {
  24798. return component;
  24799. }
  24800. }
  24801. return null;
  24802. };
  24803. /**
  24804. * @hidden
  24805. */
  24806. Scene.prototype._getDefaultMeshCandidates = function () {
  24807. this._defaultMeshCandidates.data = this.meshes;
  24808. this._defaultMeshCandidates.length = this.meshes.length;
  24809. return this._defaultMeshCandidates;
  24810. };
  24811. /**
  24812. * @hidden
  24813. */
  24814. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  24815. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  24816. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  24817. return this._defaultSubMeshCandidates;
  24818. };
  24819. /**
  24820. * Sets the default candidate providers for the scene.
  24821. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  24822. * and getCollidingSubMeshCandidates to their default function
  24823. */
  24824. Scene.prototype.setDefaultCandidateProviders = function () {
  24825. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  24826. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24827. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24828. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24829. };
  24830. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24831. /**
  24832. * Gets a boolean indicating if collisions are processed on a web worker
  24833. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24834. */
  24835. get: function () {
  24836. return this._workerCollisions;
  24837. },
  24838. set: function (enabled) {
  24839. if (!BABYLON.CollisionCoordinatorLegacy) {
  24840. return;
  24841. }
  24842. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24843. this._workerCollisions = enabled;
  24844. if (this.collisionCoordinator) {
  24845. this.collisionCoordinator.destroy();
  24846. }
  24847. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24848. this.collisionCoordinator.init(this);
  24849. },
  24850. enumerable: true,
  24851. configurable: true
  24852. });
  24853. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24854. /**
  24855. * Gets the mesh that is currently under the pointer
  24856. */
  24857. get: function () {
  24858. return this._pointerOverMesh;
  24859. },
  24860. enumerable: true,
  24861. configurable: true
  24862. });
  24863. Object.defineProperty(Scene.prototype, "pointerX", {
  24864. /**
  24865. * Gets the current on-screen X position of the pointer
  24866. */
  24867. get: function () {
  24868. return this._pointerX;
  24869. },
  24870. enumerable: true,
  24871. configurable: true
  24872. });
  24873. Object.defineProperty(Scene.prototype, "pointerY", {
  24874. /**
  24875. * Gets the current on-screen Y position of the pointer
  24876. */
  24877. get: function () {
  24878. return this._pointerY;
  24879. },
  24880. enumerable: true,
  24881. configurable: true
  24882. });
  24883. /**
  24884. * Gets the cached material (ie. the latest rendered one)
  24885. * @returns the cached material
  24886. */
  24887. Scene.prototype.getCachedMaterial = function () {
  24888. return this._cachedMaterial;
  24889. };
  24890. /**
  24891. * Gets the cached effect (ie. the latest rendered one)
  24892. * @returns the cached effect
  24893. */
  24894. Scene.prototype.getCachedEffect = function () {
  24895. return this._cachedEffect;
  24896. };
  24897. /**
  24898. * Gets the cached visibility state (ie. the latest rendered one)
  24899. * @returns the cached visibility state
  24900. */
  24901. Scene.prototype.getCachedVisibility = function () {
  24902. return this._cachedVisibility;
  24903. };
  24904. /**
  24905. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24906. * @param material defines the current material
  24907. * @param effect defines the current effect
  24908. * @param visibility defines the current visibility state
  24909. * @returns true if one parameter is not cached
  24910. */
  24911. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24912. if (visibility === void 0) { visibility = 1; }
  24913. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24914. };
  24915. /**
  24916. * Gets the engine associated with the scene
  24917. * @returns an Engine
  24918. */
  24919. Scene.prototype.getEngine = function () {
  24920. return this._engine;
  24921. };
  24922. /**
  24923. * Gets the total number of vertices rendered per frame
  24924. * @returns the total number of vertices rendered per frame
  24925. */
  24926. Scene.prototype.getTotalVertices = function () {
  24927. return this._totalVertices.current;
  24928. };
  24929. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24930. /**
  24931. * Gets the performance counter for total vertices
  24932. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24933. */
  24934. get: function () {
  24935. return this._totalVertices;
  24936. },
  24937. enumerable: true,
  24938. configurable: true
  24939. });
  24940. /**
  24941. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24942. * @returns the total number of active indices rendered per frame
  24943. */
  24944. Scene.prototype.getActiveIndices = function () {
  24945. return this._activeIndices.current;
  24946. };
  24947. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24948. /**
  24949. * Gets the performance counter for active indices
  24950. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24951. */
  24952. get: function () {
  24953. return this._activeIndices;
  24954. },
  24955. enumerable: true,
  24956. configurable: true
  24957. });
  24958. /**
  24959. * Gets the total number of active particles rendered per frame
  24960. * @returns the total number of active particles rendered per frame
  24961. */
  24962. Scene.prototype.getActiveParticles = function () {
  24963. return this._activeParticles.current;
  24964. };
  24965. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24966. /**
  24967. * Gets the performance counter for active particles
  24968. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24969. */
  24970. get: function () {
  24971. return this._activeParticles;
  24972. },
  24973. enumerable: true,
  24974. configurable: true
  24975. });
  24976. /**
  24977. * Gets the total number of active bones rendered per frame
  24978. * @returns the total number of active bones rendered per frame
  24979. */
  24980. Scene.prototype.getActiveBones = function () {
  24981. return this._activeBones.current;
  24982. };
  24983. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24984. /**
  24985. * Gets the performance counter for active bones
  24986. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24987. */
  24988. get: function () {
  24989. return this._activeBones;
  24990. },
  24991. enumerable: true,
  24992. configurable: true
  24993. });
  24994. /** @hidden */
  24995. Scene.prototype.getInterFramePerfCounter = function () {
  24996. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24997. return 0;
  24998. };
  24999. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25000. /** @hidden */
  25001. get: function () {
  25002. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25003. return null;
  25004. },
  25005. enumerable: true,
  25006. configurable: true
  25007. });
  25008. /** @hidden */
  25009. Scene.prototype.getLastFrameDuration = function () {
  25010. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25011. return 0;
  25012. };
  25013. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25014. /** @hidden */
  25015. get: function () {
  25016. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25017. return null;
  25018. },
  25019. enumerable: true,
  25020. configurable: true
  25021. });
  25022. /** @hidden */
  25023. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25024. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25025. return 0;
  25026. };
  25027. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25028. /** @hidden */
  25029. get: function () {
  25030. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25031. return null;
  25032. },
  25033. enumerable: true,
  25034. configurable: true
  25035. });
  25036. /**
  25037. * Gets the array of active meshes
  25038. * @returns an array of AbstractMesh
  25039. */
  25040. Scene.prototype.getActiveMeshes = function () {
  25041. return this._activeMeshes;
  25042. };
  25043. /** @hidden */
  25044. Scene.prototype.getRenderTargetsDuration = function () {
  25045. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25046. return 0;
  25047. };
  25048. /** @hidden */
  25049. Scene.prototype.getRenderDuration = function () {
  25050. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25051. return 0;
  25052. };
  25053. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25054. /** @hidden */
  25055. get: function () {
  25056. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25057. return null;
  25058. },
  25059. enumerable: true,
  25060. configurable: true
  25061. });
  25062. /** @hidden */
  25063. Scene.prototype.getParticlesDuration = function () {
  25064. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25065. return 0;
  25066. };
  25067. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25068. /** @hidden */
  25069. get: function () {
  25070. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25071. return null;
  25072. },
  25073. enumerable: true,
  25074. configurable: true
  25075. });
  25076. /** @hidden */
  25077. Scene.prototype.getSpritesDuration = function () {
  25078. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25079. return 0;
  25080. };
  25081. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25082. /** @hidden */
  25083. get: function () {
  25084. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25085. return null;
  25086. },
  25087. enumerable: true,
  25088. configurable: true
  25089. });
  25090. /**
  25091. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25092. * @returns a number
  25093. */
  25094. Scene.prototype.getAnimationRatio = function () {
  25095. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25096. };
  25097. /**
  25098. * Gets an unique Id for the current render phase
  25099. * @returns a number
  25100. */
  25101. Scene.prototype.getRenderId = function () {
  25102. return this._renderId;
  25103. };
  25104. /**
  25105. * Gets an unique Id for the current frame
  25106. * @returns a number
  25107. */
  25108. Scene.prototype.getFrameId = function () {
  25109. return this._frameId;
  25110. };
  25111. /** Call this function if you want to manually increment the render Id*/
  25112. Scene.prototype.incrementRenderId = function () {
  25113. this._renderId++;
  25114. };
  25115. Scene.prototype._updatePointerPosition = function (evt) {
  25116. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25117. if (!canvasRect) {
  25118. return;
  25119. }
  25120. this._pointerX = evt.clientX - canvasRect.left;
  25121. this._pointerY = evt.clientY - canvasRect.top;
  25122. this._unTranslatedPointerX = this._pointerX;
  25123. this._unTranslatedPointerY = this._pointerY;
  25124. };
  25125. Scene.prototype._createUbo = function () {
  25126. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25127. this._sceneUbo.addUniform("viewProjection", 16);
  25128. this._sceneUbo.addUniform("view", 16);
  25129. };
  25130. Scene.prototype._createAlternateUbo = function () {
  25131. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25132. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25133. this._alternateSceneUbo.addUniform("view", 16);
  25134. };
  25135. // Pointers handling
  25136. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25137. if (pointerInfo.pickInfo) {
  25138. if (!pointerInfo.pickInfo.ray) {
  25139. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25140. }
  25141. }
  25142. };
  25143. /**
  25144. * Use this method to simulate a pointer move on a mesh
  25145. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25146. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25147. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25148. * @returns the current scene
  25149. */
  25150. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25151. var evt = new PointerEvent("pointermove", pointerEventInit);
  25152. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25153. return this;
  25154. }
  25155. return this._processPointerMove(pickResult, evt);
  25156. };
  25157. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25158. var canvas = this._engine.getRenderingCanvas();
  25159. if (!canvas) {
  25160. return this;
  25161. }
  25162. // Restore pointer
  25163. canvas.style.cursor = this.defaultCursor;
  25164. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  25165. if (isMeshPicked) {
  25166. this.setPointerOverMesh(pickResult.pickedMesh);
  25167. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25168. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25169. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25170. }
  25171. else {
  25172. canvas.style.cursor = this.hoverCursor;
  25173. }
  25174. }
  25175. }
  25176. else {
  25177. this.setPointerOverMesh(null);
  25178. }
  25179. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  25180. var step = _a[_i];
  25181. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  25182. }
  25183. if (pickResult) {
  25184. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25185. if (this.onPointerMove) {
  25186. this.onPointerMove(evt, pickResult, type);
  25187. }
  25188. if (this.onPointerObservable.hasObservers()) {
  25189. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25190. this._setRayOnPointerInfo(pi);
  25191. this.onPointerObservable.notifyObservers(pi, type);
  25192. }
  25193. }
  25194. return this;
  25195. };
  25196. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25197. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25198. if (pickResult) {
  25199. pi.ray = pickResult.ray;
  25200. }
  25201. this.onPrePointerObservable.notifyObservers(pi, type);
  25202. if (pi.skipOnPointerObservable) {
  25203. return true;
  25204. }
  25205. else {
  25206. return false;
  25207. }
  25208. };
  25209. /**
  25210. * Use this method to simulate a pointer down on a mesh
  25211. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25212. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25213. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25214. * @returns the current scene
  25215. */
  25216. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25217. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25218. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25219. return this;
  25220. }
  25221. return this._processPointerDown(pickResult, evt);
  25222. };
  25223. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25224. var _this = this;
  25225. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25226. this._pickedDownMesh = pickResult.pickedMesh;
  25227. var actionManager = pickResult.pickedMesh.actionManager;
  25228. if (actionManager) {
  25229. if (actionManager.hasPickTriggers) {
  25230. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25231. switch (evt.button) {
  25232. case 0:
  25233. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25234. break;
  25235. case 1:
  25236. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25237. break;
  25238. case 2:
  25239. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25240. break;
  25241. }
  25242. }
  25243. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25244. window.setTimeout(function () {
  25245. 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);
  25246. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25247. if (_this._totalPointersPressed !== 0 &&
  25248. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25249. !_this._isPointerSwiping()) {
  25250. _this._startingPointerTime = 0;
  25251. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25252. }
  25253. }
  25254. }, Scene.LongPressDelay);
  25255. }
  25256. }
  25257. }
  25258. else {
  25259. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  25260. var step = _a[_i];
  25261. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25262. }
  25263. }
  25264. if (pickResult) {
  25265. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25266. if (this.onPointerDown) {
  25267. this.onPointerDown(evt, pickResult, type);
  25268. }
  25269. if (this.onPointerObservable.hasObservers()) {
  25270. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25271. this._setRayOnPointerInfo(pi);
  25272. this.onPointerObservable.notifyObservers(pi, type);
  25273. }
  25274. }
  25275. return this;
  25276. };
  25277. /**
  25278. * Use this method to simulate a pointer up on a mesh
  25279. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25280. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25281. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25282. * @returns the current scene
  25283. */
  25284. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25285. var evt = new PointerEvent("pointerup", pointerEventInit);
  25286. var clickInfo = new ClickInfo();
  25287. clickInfo.singleClick = true;
  25288. clickInfo.ignore = true;
  25289. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25290. return this;
  25291. }
  25292. return this._processPointerUp(pickResult, evt, clickInfo);
  25293. };
  25294. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25295. if (pickResult && pickResult && pickResult.pickedMesh) {
  25296. this._pickedUpMesh = pickResult.pickedMesh;
  25297. if (this._pickedDownMesh === this._pickedUpMesh) {
  25298. if (this.onPointerPick) {
  25299. this.onPointerPick(evt, pickResult);
  25300. }
  25301. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25302. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25303. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25304. this._setRayOnPointerInfo(pi);
  25305. this.onPointerObservable.notifyObservers(pi, type_1);
  25306. }
  25307. }
  25308. if (pickResult.pickedMesh.actionManager) {
  25309. if (clickInfo.ignore) {
  25310. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25311. }
  25312. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25313. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25314. }
  25315. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25316. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25317. }
  25318. }
  25319. }
  25320. else {
  25321. if (!clickInfo.ignore) {
  25322. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  25323. var step = _a[_i];
  25324. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25325. }
  25326. }
  25327. }
  25328. if (this._pickedDownMesh &&
  25329. this._pickedDownMesh.actionManager &&
  25330. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25331. this._pickedDownMesh !== this._pickedUpMesh) {
  25332. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25333. }
  25334. var type = BABYLON.PointerEventTypes.POINTERUP;
  25335. if (this.onPointerObservable.hasObservers()) {
  25336. if (!clickInfo.ignore) {
  25337. if (!clickInfo.hasSwiped) {
  25338. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25339. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25340. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25341. this._setRayOnPointerInfo(pi);
  25342. this.onPointerObservable.notifyObservers(pi, type_2);
  25343. }
  25344. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25345. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25346. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25347. this._setRayOnPointerInfo(pi);
  25348. this.onPointerObservable.notifyObservers(pi, type_3);
  25349. }
  25350. }
  25351. }
  25352. else {
  25353. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25354. this._setRayOnPointerInfo(pi);
  25355. this.onPointerObservable.notifyObservers(pi, type);
  25356. }
  25357. }
  25358. if (this.onPointerUp) {
  25359. this.onPointerUp(evt, pickResult, type);
  25360. }
  25361. return this;
  25362. };
  25363. /**
  25364. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25365. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25366. * @returns true if the pointer was captured
  25367. */
  25368. Scene.prototype.isPointerCaptured = function (pointerId) {
  25369. if (pointerId === void 0) { pointerId = 0; }
  25370. return this._pointerCaptures[pointerId];
  25371. };
  25372. /** @hidden */
  25373. Scene.prototype._isPointerSwiping = function () {
  25374. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  25375. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  25376. };
  25377. /**
  25378. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25379. * @param attachUp defines if you want to attach events to pointerup
  25380. * @param attachDown defines if you want to attach events to pointerdown
  25381. * @param attachMove defines if you want to attach events to pointermove
  25382. */
  25383. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25384. var _this = this;
  25385. if (attachUp === void 0) { attachUp = true; }
  25386. if (attachDown === void 0) { attachDown = true; }
  25387. if (attachMove === void 0) { attachMove = true; }
  25388. this._initActionManager = function (act, clickInfo) {
  25389. if (!_this._meshPickProceed) {
  25390. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25391. _this._currentPickResult = pickResult;
  25392. if (pickResult) {
  25393. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25394. }
  25395. _this._meshPickProceed = true;
  25396. }
  25397. return act;
  25398. };
  25399. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25400. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25401. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25402. btn !== _this._previousButtonPressed) {
  25403. _this._doubleClickOccured = false;
  25404. clickInfo.singleClick = true;
  25405. clickInfo.ignore = false;
  25406. cb(clickInfo, _this._currentPickResult);
  25407. }
  25408. };
  25409. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25410. var clickInfo = new ClickInfo();
  25411. _this._currentPickResult = null;
  25412. var act = null;
  25413. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25414. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25415. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25416. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25417. act = _this._initActionManager(act, clickInfo);
  25418. if (act)
  25419. checkPicking = act.hasPickTriggers;
  25420. }
  25421. if (checkPicking) {
  25422. var btn = evt.button;
  25423. clickInfo.hasSwiped = _this._isPointerSwiping();
  25424. if (!clickInfo.hasSwiped) {
  25425. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25426. if (!checkSingleClickImmediately) {
  25427. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25428. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25429. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25430. act = _this._initActionManager(act, clickInfo);
  25431. if (act)
  25432. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25433. }
  25434. }
  25435. if (checkSingleClickImmediately) {
  25436. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25437. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25438. btn !== _this._previousButtonPressed) {
  25439. clickInfo.singleClick = true;
  25440. cb(clickInfo, _this._currentPickResult);
  25441. }
  25442. }
  25443. // at least one double click is required to be check and exclusive double click is enabled
  25444. else {
  25445. // wait that no double click has been raised during the double click delay
  25446. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25447. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25448. }
  25449. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25450. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25451. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25452. act = _this._initActionManager(act, clickInfo);
  25453. if (act)
  25454. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25455. }
  25456. if (checkDoubleClick) {
  25457. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25458. if (btn === _this._previousButtonPressed &&
  25459. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25460. !_this._doubleClickOccured) {
  25461. // pointer has not moved for 2 clicks, it's a double click
  25462. if (!clickInfo.hasSwiped &&
  25463. !_this._isPointerSwiping()) {
  25464. _this._previousStartingPointerTime = 0;
  25465. _this._doubleClickOccured = true;
  25466. clickInfo.doubleClick = true;
  25467. clickInfo.ignore = false;
  25468. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25469. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25470. }
  25471. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25472. cb(clickInfo, _this._currentPickResult);
  25473. }
  25474. // if the two successive clicks are too far, it's just two simple clicks
  25475. else {
  25476. _this._doubleClickOccured = false;
  25477. _this._previousStartingPointerTime = _this._startingPointerTime;
  25478. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25479. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25480. _this._previousButtonPressed = btn;
  25481. if (Scene.ExclusiveDoubleClickMode) {
  25482. if (_this._previousDelayedSimpleClickTimeout) {
  25483. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25484. }
  25485. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25486. cb(clickInfo, _this._previousPickResult);
  25487. }
  25488. else {
  25489. cb(clickInfo, _this._currentPickResult);
  25490. }
  25491. }
  25492. }
  25493. // just the first click of the double has been raised
  25494. else {
  25495. _this._doubleClickOccured = false;
  25496. _this._previousStartingPointerTime = _this._startingPointerTime;
  25497. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25498. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25499. _this._previousButtonPressed = btn;
  25500. }
  25501. }
  25502. }
  25503. }
  25504. clickInfo.ignore = true;
  25505. cb(clickInfo, _this._currentPickResult);
  25506. };
  25507. this._onPointerMove = function (evt) {
  25508. _this._updatePointerPosition(evt);
  25509. // PreObservable support
  25510. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25511. return;
  25512. }
  25513. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25514. return;
  25515. }
  25516. if (!_this.pointerMovePredicate) {
  25517. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25518. }
  25519. // Meshes
  25520. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25521. _this._processPointerMove(pickResult, evt);
  25522. };
  25523. this._onPointerDown = function (evt) {
  25524. _this._totalPointersPressed++;
  25525. _this._pickedDownMesh = null;
  25526. _this._meshPickProceed = false;
  25527. _this._updatePointerPosition(evt);
  25528. if (_this.preventDefaultOnPointerDown && canvas) {
  25529. evt.preventDefault();
  25530. canvas.focus();
  25531. }
  25532. // PreObservable support
  25533. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25534. return;
  25535. }
  25536. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25537. return;
  25538. }
  25539. _this._pointerCaptures[evt.pointerId] = true;
  25540. _this._startingPointerPosition.x = _this._pointerX;
  25541. _this._startingPointerPosition.y = _this._pointerY;
  25542. _this._startingPointerTime = Date.now();
  25543. if (!_this.pointerDownPredicate) {
  25544. _this.pointerDownPredicate = function (mesh) {
  25545. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25546. };
  25547. }
  25548. // Meshes
  25549. _this._pickedDownMesh = null;
  25550. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25551. _this._processPointerDown(pickResult, evt);
  25552. };
  25553. this._onPointerUp = function (evt) {
  25554. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25555. return; // So we need to test it the pointer down was pressed before.
  25556. }
  25557. _this._totalPointersPressed--;
  25558. _this._pickedUpMesh = null;
  25559. _this._meshPickProceed = false;
  25560. _this._updatePointerPosition(evt);
  25561. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25562. // PreObservable support
  25563. if (_this.onPrePointerObservable.hasObservers()) {
  25564. if (!clickInfo.ignore) {
  25565. if (!clickInfo.hasSwiped) {
  25566. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25567. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25568. return;
  25569. }
  25570. }
  25571. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25572. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25573. return;
  25574. }
  25575. }
  25576. }
  25577. }
  25578. else {
  25579. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25580. return;
  25581. }
  25582. }
  25583. }
  25584. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25585. return;
  25586. }
  25587. _this._pointerCaptures[evt.pointerId] = false;
  25588. if (!_this.pointerUpPredicate) {
  25589. _this.pointerUpPredicate = function (mesh) {
  25590. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25591. };
  25592. }
  25593. // Meshes
  25594. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25595. _this._initActionManager(null, clickInfo);
  25596. }
  25597. if (!pickResult) {
  25598. pickResult = _this._currentPickResult;
  25599. }
  25600. _this._processPointerUp(pickResult, evt, clickInfo);
  25601. _this._previousPickResult = _this._currentPickResult;
  25602. });
  25603. };
  25604. this._onKeyDown = function (evt) {
  25605. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25606. if (_this.onPreKeyboardObservable.hasObservers()) {
  25607. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25608. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25609. if (pi.skipOnPointerObservable) {
  25610. return;
  25611. }
  25612. }
  25613. if (_this.onKeyboardObservable.hasObservers()) {
  25614. var pi = new BABYLON.KeyboardInfo(type, evt);
  25615. _this.onKeyboardObservable.notifyObservers(pi, type);
  25616. }
  25617. if (_this.actionManager) {
  25618. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25619. }
  25620. };
  25621. this._onKeyUp = function (evt) {
  25622. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25623. if (_this.onPreKeyboardObservable.hasObservers()) {
  25624. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25625. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25626. if (pi.skipOnPointerObservable) {
  25627. return;
  25628. }
  25629. }
  25630. if (_this.onKeyboardObservable.hasObservers()) {
  25631. var pi = new BABYLON.KeyboardInfo(type, evt);
  25632. _this.onKeyboardObservable.notifyObservers(pi, type);
  25633. }
  25634. if (_this.actionManager) {
  25635. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25636. }
  25637. };
  25638. var engine = this.getEngine();
  25639. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25640. if (!canvas) {
  25641. return;
  25642. }
  25643. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25644. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25645. });
  25646. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25647. if (!canvas) {
  25648. return;
  25649. }
  25650. canvas.removeEventListener("keydown", _this._onKeyDown);
  25651. canvas.removeEventListener("keyup", _this._onKeyUp);
  25652. });
  25653. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25654. var canvas = this._engine.getRenderingCanvas();
  25655. if (!canvas) {
  25656. return;
  25657. }
  25658. if (attachMove) {
  25659. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25660. // Wheel
  25661. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25662. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25663. }
  25664. if (attachDown) {
  25665. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25666. }
  25667. if (attachUp) {
  25668. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25669. }
  25670. canvas.tabIndex = 1;
  25671. };
  25672. /** Detaches all event handlers*/
  25673. Scene.prototype.detachControl = function () {
  25674. var engine = this.getEngine();
  25675. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25676. var canvas = engine.getRenderingCanvas();
  25677. if (!canvas) {
  25678. return;
  25679. }
  25680. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25681. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25682. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25683. if (this._onCanvasBlurObserver) {
  25684. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25685. }
  25686. if (this._onCanvasFocusObserver) {
  25687. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25688. }
  25689. // Wheel
  25690. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25691. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25692. // Keyboard
  25693. canvas.removeEventListener("keydown", this._onKeyDown);
  25694. canvas.removeEventListener("keyup", this._onKeyUp);
  25695. // Observables
  25696. this.onKeyboardObservable.clear();
  25697. this.onPreKeyboardObservable.clear();
  25698. this.onPointerObservable.clear();
  25699. this.onPrePointerObservable.clear();
  25700. };
  25701. /**
  25702. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25703. * Delay loaded resources are not taking in account
  25704. * @return true if all required resources are ready
  25705. */
  25706. Scene.prototype.isReady = function () {
  25707. if (this._isDisposed) {
  25708. return false;
  25709. }
  25710. if (this._pendingData.length > 0) {
  25711. return false;
  25712. }
  25713. var index;
  25714. var engine = this.getEngine();
  25715. // Geometries
  25716. for (index = 0; index < this.geometries.length; index++) {
  25717. var geometry = this.geometries[index];
  25718. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25719. return false;
  25720. }
  25721. }
  25722. // Meshes
  25723. for (index = 0; index < this.meshes.length; index++) {
  25724. var mesh = this.meshes[index];
  25725. if (!mesh.isEnabled()) {
  25726. continue;
  25727. }
  25728. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25729. continue;
  25730. }
  25731. if (!mesh.isReady(true)) {
  25732. return false;
  25733. }
  25734. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25735. // Is Ready For Mesh
  25736. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25737. var step = _a[_i];
  25738. if (!step.action(mesh, hardwareInstancedRendering)) {
  25739. return false;
  25740. }
  25741. }
  25742. }
  25743. // Post-processes
  25744. if (this.activeCameras && this.activeCameras.length > 0) {
  25745. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25746. var camera = _c[_b];
  25747. if (!camera.isReady(true)) {
  25748. return false;
  25749. }
  25750. }
  25751. }
  25752. else if (this.activeCamera) {
  25753. if (!this.activeCamera.isReady(true)) {
  25754. return false;
  25755. }
  25756. }
  25757. // Particles
  25758. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25759. var particleSystem = _e[_d];
  25760. if (!particleSystem.isReady()) {
  25761. return false;
  25762. }
  25763. }
  25764. return true;
  25765. };
  25766. /** Resets all cached information relative to material (including effect and visibility) */
  25767. Scene.prototype.resetCachedMaterial = function () {
  25768. this._cachedMaterial = null;
  25769. this._cachedEffect = null;
  25770. this._cachedVisibility = null;
  25771. };
  25772. /**
  25773. * Registers a function to be called before every frame render
  25774. * @param func defines the function to register
  25775. */
  25776. Scene.prototype.registerBeforeRender = function (func) {
  25777. this.onBeforeRenderObservable.add(func);
  25778. };
  25779. /**
  25780. * Unregisters a function called before every frame render
  25781. * @param func defines the function to unregister
  25782. */
  25783. Scene.prototype.unregisterBeforeRender = function (func) {
  25784. this.onBeforeRenderObservable.removeCallback(func);
  25785. };
  25786. /**
  25787. * Registers a function to be called after every frame render
  25788. * @param func defines the function to register
  25789. */
  25790. Scene.prototype.registerAfterRender = function (func) {
  25791. this.onAfterRenderObservable.add(func);
  25792. };
  25793. /**
  25794. * Unregisters a function called after every frame render
  25795. * @param func defines the function to unregister
  25796. */
  25797. Scene.prototype.unregisterAfterRender = function (func) {
  25798. this.onAfterRenderObservable.removeCallback(func);
  25799. };
  25800. Scene.prototype._executeOnceBeforeRender = function (func) {
  25801. var _this = this;
  25802. var execFunc = function () {
  25803. func();
  25804. setTimeout(function () {
  25805. _this.unregisterBeforeRender(execFunc);
  25806. });
  25807. };
  25808. this.registerBeforeRender(execFunc);
  25809. };
  25810. /**
  25811. * The provided function will run before render once and will be disposed afterwards.
  25812. * A timeout delay can be provided so that the function will be executed in N ms.
  25813. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25814. * @param func The function to be executed.
  25815. * @param timeout optional delay in ms
  25816. */
  25817. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25818. var _this = this;
  25819. if (timeout !== undefined) {
  25820. setTimeout(function () {
  25821. _this._executeOnceBeforeRender(func);
  25822. }, timeout);
  25823. }
  25824. else {
  25825. this._executeOnceBeforeRender(func);
  25826. }
  25827. };
  25828. /** @hidden */
  25829. Scene.prototype._addPendingData = function (data) {
  25830. this._pendingData.push(data);
  25831. };
  25832. /** @hidden */
  25833. Scene.prototype._removePendingData = function (data) {
  25834. var wasLoading = this.isLoading;
  25835. var index = this._pendingData.indexOf(data);
  25836. if (index !== -1) {
  25837. this._pendingData.splice(index, 1);
  25838. }
  25839. if (wasLoading && !this.isLoading) {
  25840. this.onDataLoadedObservable.notifyObservers(this);
  25841. }
  25842. };
  25843. /**
  25844. * Returns the number of items waiting to be loaded
  25845. * @returns the number of items waiting to be loaded
  25846. */
  25847. Scene.prototype.getWaitingItemsCount = function () {
  25848. return this._pendingData.length;
  25849. };
  25850. Object.defineProperty(Scene.prototype, "isLoading", {
  25851. /**
  25852. * Returns a boolean indicating if the scene is still loading data
  25853. */
  25854. get: function () {
  25855. return this._pendingData.length > 0;
  25856. },
  25857. enumerable: true,
  25858. configurable: true
  25859. });
  25860. /**
  25861. * Registers a function to be executed when the scene is ready
  25862. * @param {Function} func - the function to be executed
  25863. */
  25864. Scene.prototype.executeWhenReady = function (func) {
  25865. var _this = this;
  25866. this.onReadyObservable.add(func);
  25867. if (this._executeWhenReadyTimeoutId !== -1) {
  25868. return;
  25869. }
  25870. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25871. _this._checkIsReady();
  25872. }, 150);
  25873. };
  25874. /**
  25875. * Returns a promise that resolves when the scene is ready
  25876. * @returns A promise that resolves when the scene is ready
  25877. */
  25878. Scene.prototype.whenReadyAsync = function () {
  25879. var _this = this;
  25880. return new Promise(function (resolve) {
  25881. _this.executeWhenReady(function () {
  25882. resolve();
  25883. });
  25884. });
  25885. };
  25886. /** @hidden */
  25887. Scene.prototype._checkIsReady = function () {
  25888. var _this = this;
  25889. this._registerTransientComponents();
  25890. if (this.isReady()) {
  25891. this.onReadyObservable.notifyObservers(this);
  25892. this.onReadyObservable.clear();
  25893. this._executeWhenReadyTimeoutId = -1;
  25894. return;
  25895. }
  25896. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25897. _this._checkIsReady();
  25898. }, 150);
  25899. };
  25900. // Animations
  25901. /**
  25902. * Will start the animation sequence of a given target
  25903. * @param target defines the target
  25904. * @param from defines from which frame should animation start
  25905. * @param to defines until which frame should animation run.
  25906. * @param weight defines the weight to apply to the animation (1.0 by default)
  25907. * @param loop defines if the animation loops
  25908. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25909. * @param onAnimationEnd defines the function to be executed when the animation ends
  25910. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25911. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25912. * @returns the animatable object created for this animation
  25913. */
  25914. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25915. if (weight === void 0) { weight = 1.0; }
  25916. if (speedRatio === void 0) { speedRatio = 1.0; }
  25917. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25918. returnedAnimatable.weight = weight;
  25919. return returnedAnimatable;
  25920. };
  25921. /**
  25922. * Will start the animation sequence of a given target
  25923. * @param target defines the target
  25924. * @param from defines from which frame should animation start
  25925. * @param to defines until which frame should animation run.
  25926. * @param loop defines if the animation loops
  25927. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25928. * @param onAnimationEnd defines the function to be executed when the animation ends
  25929. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25930. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25931. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25932. * @returns the animatable object created for this animation
  25933. */
  25934. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25935. if (speedRatio === void 0) { speedRatio = 1.0; }
  25936. if (stopCurrent === void 0) { stopCurrent = true; }
  25937. if (from > to && speedRatio > 0) {
  25938. speedRatio *= -1;
  25939. }
  25940. if (stopCurrent) {
  25941. this.stopAnimation(target, undefined, targetMask);
  25942. }
  25943. if (!animatable) {
  25944. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25945. }
  25946. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  25947. // Local animations
  25948. if (target.animations && shouldRunTargetAnimations) {
  25949. animatable.appendAnimations(target, target.animations);
  25950. }
  25951. // Children animations
  25952. if (target.getAnimatables) {
  25953. var animatables = target.getAnimatables();
  25954. for (var index = 0; index < animatables.length; index++) {
  25955. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  25956. }
  25957. }
  25958. animatable.reset();
  25959. return animatable;
  25960. };
  25961. /**
  25962. * Begin a new animation on a given node
  25963. * @param target defines the target where the animation will take place
  25964. * @param animations defines the list of animations to start
  25965. * @param from defines the initial value
  25966. * @param to defines the final value
  25967. * @param loop defines if you want animation to loop (off by default)
  25968. * @param speedRatio defines the speed ratio to apply to all animations
  25969. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25970. * @returns the list of created animatables
  25971. */
  25972. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25973. if (speedRatio === undefined) {
  25974. speedRatio = 1.0;
  25975. }
  25976. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25977. return animatable;
  25978. };
  25979. /**
  25980. * Begin a new animation on a given node and its hierarchy
  25981. * @param target defines the root node where the animation will take place
  25982. * @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.
  25983. * @param animations defines the list of animations to start
  25984. * @param from defines the initial value
  25985. * @param to defines the final value
  25986. * @param loop defines if you want animation to loop (off by default)
  25987. * @param speedRatio defines the speed ratio to apply to all animations
  25988. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25989. * @returns the list of animatables created for all nodes
  25990. */
  25991. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25992. var children = target.getDescendants(directDescendantsOnly);
  25993. var result = [];
  25994. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25995. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25996. var child = children_1[_i];
  25997. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25998. }
  25999. return result;
  26000. };
  26001. /**
  26002. * Gets the animatable associated with a specific target
  26003. * @param target defines the target of the animatable
  26004. * @returns the required animatable if found
  26005. */
  26006. Scene.prototype.getAnimatableByTarget = function (target) {
  26007. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26008. if (this._activeAnimatables[index].target === target) {
  26009. return this._activeAnimatables[index];
  26010. }
  26011. }
  26012. return null;
  26013. };
  26014. /**
  26015. * Gets all animatables associated with a given target
  26016. * @param target defines the target to look animatables for
  26017. * @returns an array of Animatables
  26018. */
  26019. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26020. var result = [];
  26021. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26022. if (this._activeAnimatables[index].target === target) {
  26023. result.push(this._activeAnimatables[index]);
  26024. }
  26025. }
  26026. return result;
  26027. };
  26028. Object.defineProperty(Scene.prototype, "animatables", {
  26029. /**
  26030. * Gets all animatable attached to the scene
  26031. */
  26032. get: function () {
  26033. return this._activeAnimatables;
  26034. },
  26035. enumerable: true,
  26036. configurable: true
  26037. });
  26038. /**
  26039. * Will stop the animation of the given target
  26040. * @param target - the target
  26041. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26042. * @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)
  26043. */
  26044. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26045. var animatables = this.getAllAnimatablesByTarget(target);
  26046. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26047. var animatable = animatables_1[_i];
  26048. animatable.stop(animationName, targetMask);
  26049. }
  26050. };
  26051. /**
  26052. * Stops and removes all animations that have been applied to the scene
  26053. */
  26054. Scene.prototype.stopAllAnimations = function () {
  26055. if (this._activeAnimatables) {
  26056. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26057. this._activeAnimatables[i].stop();
  26058. }
  26059. this._activeAnimatables = [];
  26060. }
  26061. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26062. var group = _a[_i];
  26063. group.stop();
  26064. }
  26065. };
  26066. Scene.prototype._animate = function () {
  26067. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26068. return;
  26069. }
  26070. // Getting time
  26071. var now = BABYLON.Tools.Now;
  26072. if (!this._animationTimeLast) {
  26073. if (this._pendingData.length > 0) {
  26074. return;
  26075. }
  26076. this._animationTimeLast = now;
  26077. }
  26078. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26079. this._animationTime += deltaTime;
  26080. this._animationTimeLast = now;
  26081. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26082. this._activeAnimatables[index]._animate(this._animationTime);
  26083. }
  26084. // Late animation bindings
  26085. this._processLateAnimationBindings();
  26086. };
  26087. /** @hidden */
  26088. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26089. var target = runtimeAnimation.target;
  26090. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26091. if (!target._lateAnimationHolders) {
  26092. target._lateAnimationHolders = {};
  26093. }
  26094. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26095. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26096. totalWeight: 0,
  26097. animations: [],
  26098. originalValue: originalValue
  26099. };
  26100. }
  26101. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26102. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26103. };
  26104. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26105. var normalizer = 1.0;
  26106. var finalPosition = BABYLON.Tmp.Vector3[0];
  26107. var finalScaling = BABYLON.Tmp.Vector3[1];
  26108. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26109. var startIndex = 0;
  26110. var originalAnimation = holder.animations[0];
  26111. var originalValue = holder.originalValue;
  26112. var scale = 1;
  26113. if (holder.totalWeight < 1.0) {
  26114. // We need to mix the original value in
  26115. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26116. scale = 1.0 - holder.totalWeight;
  26117. }
  26118. else {
  26119. startIndex = 1;
  26120. // We need to normalize the weights
  26121. normalizer = holder.totalWeight;
  26122. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26123. scale = originalAnimation.weight / normalizer;
  26124. if (scale == 1) {
  26125. return originalAnimation.currentValue;
  26126. }
  26127. }
  26128. finalScaling.scaleInPlace(scale);
  26129. finalPosition.scaleInPlace(scale);
  26130. finalQuaternion.scaleInPlace(scale);
  26131. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26132. var runtimeAnimation = holder.animations[animIndex];
  26133. var scale = runtimeAnimation.weight / normalizer;
  26134. var currentPosition = BABYLON.Tmp.Vector3[2];
  26135. var currentScaling = BABYLON.Tmp.Vector3[3];
  26136. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26137. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26138. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26139. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26140. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26141. }
  26142. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26143. return originalAnimation._workValue;
  26144. };
  26145. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26146. var originalAnimation = holder.animations[0];
  26147. var originalValue = holder.originalValue;
  26148. if (holder.animations.length === 1) {
  26149. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26150. return refQuaternion;
  26151. }
  26152. var normalizer = 1.0;
  26153. var quaternions;
  26154. var weights;
  26155. if (holder.totalWeight < 1.0) {
  26156. var scale = 1.0 - holder.totalWeight;
  26157. quaternions = [];
  26158. weights = [];
  26159. quaternions.push(originalValue);
  26160. weights.push(scale);
  26161. }
  26162. else {
  26163. if (holder.animations.length === 2) { // Slerp as soon as we can
  26164. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26165. return refQuaternion;
  26166. }
  26167. quaternions = [];
  26168. weights = [];
  26169. normalizer = holder.totalWeight;
  26170. }
  26171. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26172. var runtimeAnimation = holder.animations[animIndex];
  26173. quaternions.push(runtimeAnimation.currentValue);
  26174. weights.push(runtimeAnimation.weight / normalizer);
  26175. }
  26176. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26177. var cumulativeAmount = 0;
  26178. var cumulativeQuaternion = null;
  26179. for (var index = 0; index < quaternions.length;) {
  26180. if (!cumulativeQuaternion) {
  26181. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26182. cumulativeQuaternion = refQuaternion;
  26183. cumulativeAmount = weights[index] + weights[index + 1];
  26184. index += 2;
  26185. continue;
  26186. }
  26187. cumulativeAmount += weights[index];
  26188. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26189. index++;
  26190. }
  26191. return cumulativeQuaternion;
  26192. };
  26193. Scene.prototype._processLateAnimationBindings = function () {
  26194. if (!this._registeredForLateAnimationBindings.length) {
  26195. return;
  26196. }
  26197. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26198. var target = this._registeredForLateAnimationBindings.data[index];
  26199. for (var path in target._lateAnimationHolders) {
  26200. var holder = target._lateAnimationHolders[path];
  26201. var originalAnimation = holder.animations[0];
  26202. var originalValue = holder.originalValue;
  26203. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26204. var finalValue = target[path];
  26205. if (matrixDecomposeMode) {
  26206. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26207. }
  26208. else {
  26209. var quaternionMode = originalValue.w !== undefined;
  26210. if (quaternionMode) {
  26211. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26212. }
  26213. else {
  26214. var startIndex = 0;
  26215. var normalizer = 1.0;
  26216. if (holder.totalWeight < 1.0) {
  26217. // We need to mix the original value in
  26218. if (originalValue.scale) {
  26219. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26220. }
  26221. else {
  26222. finalValue = originalValue * (1.0 - holder.totalWeight);
  26223. }
  26224. }
  26225. else {
  26226. // We need to normalize the weights
  26227. normalizer = holder.totalWeight;
  26228. var scale_1 = originalAnimation.weight / normalizer;
  26229. if (scale_1 !== 1) {
  26230. if (originalAnimation.currentValue.scale) {
  26231. finalValue = originalAnimation.currentValue.scale(scale_1);
  26232. }
  26233. else {
  26234. finalValue = originalAnimation.currentValue * scale_1;
  26235. }
  26236. }
  26237. else {
  26238. finalValue = originalAnimation.currentValue;
  26239. }
  26240. startIndex = 1;
  26241. }
  26242. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26243. var runtimeAnimation = holder.animations[animIndex];
  26244. var scale = runtimeAnimation.weight / normalizer;
  26245. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26246. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26247. }
  26248. else {
  26249. finalValue += runtimeAnimation.currentValue * scale;
  26250. }
  26251. }
  26252. }
  26253. }
  26254. target[path] = finalValue;
  26255. }
  26256. target._lateAnimationHolders = {};
  26257. }
  26258. this._registeredForLateAnimationBindings.reset();
  26259. };
  26260. // Matrix
  26261. /** @hidden */
  26262. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26263. this._useAlternateCameraConfiguration = active;
  26264. };
  26265. /**
  26266. * Gets the current view matrix
  26267. * @returns a Matrix
  26268. */
  26269. Scene.prototype.getViewMatrix = function () {
  26270. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26271. };
  26272. /**
  26273. * Gets the current projection matrix
  26274. * @returns a Matrix
  26275. */
  26276. Scene.prototype.getProjectionMatrix = function () {
  26277. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26278. };
  26279. /**
  26280. * Gets the current transform matrix
  26281. * @returns a Matrix made of View * Projection
  26282. */
  26283. Scene.prototype.getTransformMatrix = function () {
  26284. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26285. };
  26286. /**
  26287. * Sets the current transform matrix
  26288. * @param view defines the View matrix to use
  26289. * @param projection defines the Projection matrix to use
  26290. */
  26291. Scene.prototype.setTransformMatrix = function (view, projection) {
  26292. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26293. return;
  26294. }
  26295. this._viewUpdateFlag = view.updateFlag;
  26296. this._projectionUpdateFlag = projection.updateFlag;
  26297. this._viewMatrix = view;
  26298. this._projectionMatrix = projection;
  26299. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26300. // Update frustum
  26301. if (!this._frustumPlanes) {
  26302. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26303. }
  26304. else {
  26305. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26306. }
  26307. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26308. var otherCamera = this.activeCamera._alternateCamera;
  26309. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26310. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26311. }
  26312. if (this._sceneUbo.useUbo) {
  26313. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26314. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26315. this._sceneUbo.update();
  26316. }
  26317. };
  26318. /** @hidden */
  26319. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26320. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26321. return;
  26322. }
  26323. this._alternateViewUpdateFlag = view.updateFlag;
  26324. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26325. this._alternateViewMatrix = view;
  26326. this._alternateProjectionMatrix = projection;
  26327. if (!this._alternateTransformMatrix) {
  26328. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26329. }
  26330. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26331. if (!this._alternateSceneUbo) {
  26332. this._createAlternateUbo();
  26333. }
  26334. if (this._alternateSceneUbo.useUbo) {
  26335. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26336. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26337. this._alternateSceneUbo.update();
  26338. }
  26339. };
  26340. /**
  26341. * Gets the uniform buffer used to store scene data
  26342. * @returns a UniformBuffer
  26343. */
  26344. Scene.prototype.getSceneUniformBuffer = function () {
  26345. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26346. };
  26347. /**
  26348. * Gets an unique (relatively to the current scene) Id
  26349. * @returns an unique number for the scene
  26350. */
  26351. Scene.prototype.getUniqueId = function () {
  26352. var result = Scene._uniqueIdCounter;
  26353. Scene._uniqueIdCounter++;
  26354. return result;
  26355. };
  26356. /**
  26357. * Add a mesh to the list of scene's meshes
  26358. * @param newMesh defines the mesh to add
  26359. * @param recursive if all child meshes should also be added to the scene
  26360. */
  26361. Scene.prototype.addMesh = function (newMesh, recursive) {
  26362. var _this = this;
  26363. if (recursive === void 0) { recursive = false; }
  26364. this.meshes.push(newMesh);
  26365. //notify the collision coordinator
  26366. if (this.collisionCoordinator) {
  26367. this.collisionCoordinator.onMeshAdded(newMesh);
  26368. }
  26369. newMesh._resyncLightSources();
  26370. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26371. if (recursive) {
  26372. newMesh.getChildMeshes().forEach(function (m) {
  26373. _this.addMesh(m);
  26374. });
  26375. }
  26376. };
  26377. /**
  26378. * Remove a mesh for the list of scene's meshes
  26379. * @param toRemove defines the mesh to remove
  26380. * @param recursive if all child meshes should also be removed from the scene
  26381. * @returns the index where the mesh was in the mesh list
  26382. */
  26383. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26384. var _this = this;
  26385. if (recursive === void 0) { recursive = false; }
  26386. var index = this.meshes.indexOf(toRemove);
  26387. if (index !== -1) {
  26388. // Remove from the scene if mesh found
  26389. this.meshes.splice(index, 1);
  26390. }
  26391. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26392. if (recursive) {
  26393. toRemove.getChildMeshes().forEach(function (m) {
  26394. _this.removeMesh(m);
  26395. });
  26396. }
  26397. return index;
  26398. };
  26399. /**
  26400. * Add a transform node to the list of scene's transform nodes
  26401. * @param newTransformNode defines the transform node to add
  26402. */
  26403. Scene.prototype.addTransformNode = function (newTransformNode) {
  26404. this.transformNodes.push(newTransformNode);
  26405. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26406. };
  26407. /**
  26408. * Remove a transform node for the list of scene's transform nodes
  26409. * @param toRemove defines the transform node to remove
  26410. * @returns the index where the transform node was in the transform node list
  26411. */
  26412. Scene.prototype.removeTransformNode = function (toRemove) {
  26413. var index = this.transformNodes.indexOf(toRemove);
  26414. if (index !== -1) {
  26415. // Remove from the scene if found
  26416. this.transformNodes.splice(index, 1);
  26417. }
  26418. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26419. return index;
  26420. };
  26421. /**
  26422. * Remove a skeleton for the list of scene's skeletons
  26423. * @param toRemove defines the skeleton to remove
  26424. * @returns the index where the skeleton was in the skeleton list
  26425. */
  26426. Scene.prototype.removeSkeleton = function (toRemove) {
  26427. var index = this.skeletons.indexOf(toRemove);
  26428. if (index !== -1) {
  26429. // Remove from the scene if found
  26430. this.skeletons.splice(index, 1);
  26431. }
  26432. return index;
  26433. };
  26434. /**
  26435. * Remove a morph target for the list of scene's morph targets
  26436. * @param toRemove defines the morph target to remove
  26437. * @returns the index where the morph target was in the morph target list
  26438. */
  26439. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26440. var index = this.morphTargetManagers.indexOf(toRemove);
  26441. if (index !== -1) {
  26442. // Remove from the scene if found
  26443. this.morphTargetManagers.splice(index, 1);
  26444. }
  26445. return index;
  26446. };
  26447. /**
  26448. * Remove a light for the list of scene's lights
  26449. * @param toRemove defines the light to remove
  26450. * @returns the index where the light was in the light list
  26451. */
  26452. Scene.prototype.removeLight = function (toRemove) {
  26453. var index = this.lights.indexOf(toRemove);
  26454. if (index !== -1) {
  26455. // Remove from meshes
  26456. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26457. var mesh = _a[_i];
  26458. mesh._removeLightSource(toRemove);
  26459. }
  26460. // Remove from the scene if mesh found
  26461. this.lights.splice(index, 1);
  26462. this.sortLightsByPriority();
  26463. }
  26464. this.onLightRemovedObservable.notifyObservers(toRemove);
  26465. return index;
  26466. };
  26467. /**
  26468. * Remove a camera for the list of scene's cameras
  26469. * @param toRemove defines the camera to remove
  26470. * @returns the index where the camera was in the camera list
  26471. */
  26472. Scene.prototype.removeCamera = function (toRemove) {
  26473. var index = this.cameras.indexOf(toRemove);
  26474. if (index !== -1) {
  26475. // Remove from the scene if mesh found
  26476. this.cameras.splice(index, 1);
  26477. }
  26478. // Remove from activeCameras
  26479. var index2 = this.activeCameras.indexOf(toRemove);
  26480. if (index2 !== -1) {
  26481. // Remove from the scene if mesh found
  26482. this.activeCameras.splice(index2, 1);
  26483. }
  26484. // Reset the activeCamera
  26485. if (this.activeCamera === toRemove) {
  26486. if (this.cameras.length > 0) {
  26487. this.activeCamera = this.cameras[0];
  26488. }
  26489. else {
  26490. this.activeCamera = null;
  26491. }
  26492. }
  26493. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26494. return index;
  26495. };
  26496. /**
  26497. * Remove a particle system for the list of scene's particle systems
  26498. * @param toRemove defines the particle system to remove
  26499. * @returns the index where the particle system was in the particle system list
  26500. */
  26501. Scene.prototype.removeParticleSystem = function (toRemove) {
  26502. var index = this.particleSystems.indexOf(toRemove);
  26503. if (index !== -1) {
  26504. this.particleSystems.splice(index, 1);
  26505. }
  26506. return index;
  26507. };
  26508. /**
  26509. * Remove a animation for the list of scene's animations
  26510. * @param toRemove defines the animation to remove
  26511. * @returns the index where the animation was in the animation list
  26512. */
  26513. Scene.prototype.removeAnimation = function (toRemove) {
  26514. var index = this.animations.indexOf(toRemove);
  26515. if (index !== -1) {
  26516. this.animations.splice(index, 1);
  26517. }
  26518. return index;
  26519. };
  26520. /**
  26521. * Removes the given animation group from this scene.
  26522. * @param toRemove The animation group to remove
  26523. * @returns The index of the removed animation group
  26524. */
  26525. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26526. var index = this.animationGroups.indexOf(toRemove);
  26527. if (index !== -1) {
  26528. this.animationGroups.splice(index, 1);
  26529. }
  26530. return index;
  26531. };
  26532. /**
  26533. * Removes the given multi-material from this scene.
  26534. * @param toRemove The multi-material to remove
  26535. * @returns The index of the removed multi-material
  26536. */
  26537. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26538. var index = this.multiMaterials.indexOf(toRemove);
  26539. if (index !== -1) {
  26540. this.multiMaterials.splice(index, 1);
  26541. }
  26542. return index;
  26543. };
  26544. /**
  26545. * Removes the given material from this scene.
  26546. * @param toRemove The material to remove
  26547. * @returns The index of the removed material
  26548. */
  26549. Scene.prototype.removeMaterial = function (toRemove) {
  26550. var index = this.materials.indexOf(toRemove);
  26551. if (index !== -1) {
  26552. this.materials.splice(index, 1);
  26553. }
  26554. return index;
  26555. };
  26556. /**
  26557. * Removes the given action manager from this scene.
  26558. * @param toRemove The action manager to remove
  26559. * @returns The index of the removed action manager
  26560. */
  26561. Scene.prototype.removeActionManager = function (toRemove) {
  26562. var index = this.actionManagers.indexOf(toRemove);
  26563. if (index !== -1) {
  26564. this.actionManagers.splice(index, 1);
  26565. }
  26566. return index;
  26567. };
  26568. /**
  26569. * Removes the given texture from this scene.
  26570. * @param toRemove The texture to remove
  26571. * @returns The index of the removed texture
  26572. */
  26573. Scene.prototype.removeTexture = function (toRemove) {
  26574. var index = this.textures.indexOf(toRemove);
  26575. if (index !== -1) {
  26576. this.textures.splice(index, 1);
  26577. }
  26578. return index;
  26579. };
  26580. /**
  26581. * Adds the given light to this scene
  26582. * @param newLight The light to add
  26583. */
  26584. Scene.prototype.addLight = function (newLight) {
  26585. this.lights.push(newLight);
  26586. this.sortLightsByPriority();
  26587. // Add light to all meshes (To support if the light is removed and then readded)
  26588. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26589. var mesh = _a[_i];
  26590. if (mesh._lightSources.indexOf(newLight) === -1) {
  26591. mesh._lightSources.push(newLight);
  26592. mesh._resyncLightSources();
  26593. }
  26594. }
  26595. this.onNewLightAddedObservable.notifyObservers(newLight);
  26596. };
  26597. /**
  26598. * Sorts the list list based on light priorities
  26599. */
  26600. Scene.prototype.sortLightsByPriority = function () {
  26601. if (this.requireLightSorting) {
  26602. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26603. }
  26604. };
  26605. /**
  26606. * Adds the given camera to this scene
  26607. * @param newCamera The camera to add
  26608. */
  26609. Scene.prototype.addCamera = function (newCamera) {
  26610. this.cameras.push(newCamera);
  26611. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26612. };
  26613. /**
  26614. * Adds the given skeleton to this scene
  26615. * @param newSkeleton The skeleton to add
  26616. */
  26617. Scene.prototype.addSkeleton = function (newSkeleton) {
  26618. this.skeletons.push(newSkeleton);
  26619. };
  26620. /**
  26621. * Adds the given particle system to this scene
  26622. * @param newParticleSystem The particle system to add
  26623. */
  26624. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26625. this.particleSystems.push(newParticleSystem);
  26626. };
  26627. /**
  26628. * Adds the given animation to this scene
  26629. * @param newAnimation The animation to add
  26630. */
  26631. Scene.prototype.addAnimation = function (newAnimation) {
  26632. this.animations.push(newAnimation);
  26633. };
  26634. /**
  26635. * Adds the given animation group to this scene.
  26636. * @param newAnimationGroup The animation group to add
  26637. */
  26638. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26639. this.animationGroups.push(newAnimationGroup);
  26640. };
  26641. /**
  26642. * Adds the given multi-material to this scene
  26643. * @param newMultiMaterial The multi-material to add
  26644. */
  26645. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26646. this.multiMaterials.push(newMultiMaterial);
  26647. };
  26648. /**
  26649. * Adds the given material to this scene
  26650. * @param newMaterial The material to add
  26651. */
  26652. Scene.prototype.addMaterial = function (newMaterial) {
  26653. this.materials.push(newMaterial);
  26654. };
  26655. /**
  26656. * Adds the given morph target to this scene
  26657. * @param newMorphTargetManager The morph target to add
  26658. */
  26659. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26660. this.morphTargetManagers.push(newMorphTargetManager);
  26661. };
  26662. /**
  26663. * Adds the given geometry to this scene
  26664. * @param newGeometry The geometry to add
  26665. */
  26666. Scene.prototype.addGeometry = function (newGeometry) {
  26667. this.geometries.push(newGeometry);
  26668. };
  26669. /**
  26670. * Adds the given action manager to this scene
  26671. * @param newActionManager The action manager to add
  26672. */
  26673. Scene.prototype.addActionManager = function (newActionManager) {
  26674. this.actionManagers.push(newActionManager);
  26675. };
  26676. /**
  26677. * Adds the given texture to this scene.
  26678. * @param newTexture The texture to add
  26679. */
  26680. Scene.prototype.addTexture = function (newTexture) {
  26681. this.textures.push(newTexture);
  26682. };
  26683. /**
  26684. * Switch active camera
  26685. * @param newCamera defines the new active camera
  26686. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26687. */
  26688. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26689. if (attachControl === void 0) { attachControl = true; }
  26690. var canvas = this._engine.getRenderingCanvas();
  26691. if (!canvas) {
  26692. return;
  26693. }
  26694. if (this.activeCamera) {
  26695. this.activeCamera.detachControl(canvas);
  26696. }
  26697. this.activeCamera = newCamera;
  26698. if (attachControl) {
  26699. newCamera.attachControl(canvas);
  26700. }
  26701. };
  26702. /**
  26703. * sets the active camera of the scene using its ID
  26704. * @param id defines the camera's ID
  26705. * @return the new active camera or null if none found.
  26706. */
  26707. Scene.prototype.setActiveCameraByID = function (id) {
  26708. var camera = this.getCameraByID(id);
  26709. if (camera) {
  26710. this.activeCamera = camera;
  26711. return camera;
  26712. }
  26713. return null;
  26714. };
  26715. /**
  26716. * sets the active camera of the scene using its name
  26717. * @param name defines the camera's name
  26718. * @returns the new active camera or null if none found.
  26719. */
  26720. Scene.prototype.setActiveCameraByName = function (name) {
  26721. var camera = this.getCameraByName(name);
  26722. if (camera) {
  26723. this.activeCamera = camera;
  26724. return camera;
  26725. }
  26726. return null;
  26727. };
  26728. /**
  26729. * get an animation group using its name
  26730. * @param name defines the material's name
  26731. * @return the animation group or null if none found.
  26732. */
  26733. Scene.prototype.getAnimationGroupByName = function (name) {
  26734. for (var index = 0; index < this.animationGroups.length; index++) {
  26735. if (this.animationGroups[index].name === name) {
  26736. return this.animationGroups[index];
  26737. }
  26738. }
  26739. return null;
  26740. };
  26741. /**
  26742. * get a material using its id
  26743. * @param id defines the material's ID
  26744. * @return the material or null if none found.
  26745. */
  26746. Scene.prototype.getMaterialByID = function (id) {
  26747. for (var index = 0; index < this.materials.length; index++) {
  26748. if (this.materials[index].id === id) {
  26749. return this.materials[index];
  26750. }
  26751. }
  26752. return null;
  26753. };
  26754. /**
  26755. * Gets a material using its name
  26756. * @param name defines the material's name
  26757. * @return the material or null if none found.
  26758. */
  26759. Scene.prototype.getMaterialByName = function (name) {
  26760. for (var index = 0; index < this.materials.length; index++) {
  26761. if (this.materials[index].name === name) {
  26762. return this.materials[index];
  26763. }
  26764. }
  26765. return null;
  26766. };
  26767. /**
  26768. * Gets a camera using its id
  26769. * @param id defines the id to look for
  26770. * @returns the camera or null if not found
  26771. */
  26772. Scene.prototype.getCameraByID = function (id) {
  26773. for (var index = 0; index < this.cameras.length; index++) {
  26774. if (this.cameras[index].id === id) {
  26775. return this.cameras[index];
  26776. }
  26777. }
  26778. return null;
  26779. };
  26780. /**
  26781. * Gets a camera using its unique id
  26782. * @param uniqueId defines the unique id to look for
  26783. * @returns the camera or null if not found
  26784. */
  26785. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26786. for (var index = 0; index < this.cameras.length; index++) {
  26787. if (this.cameras[index].uniqueId === uniqueId) {
  26788. return this.cameras[index];
  26789. }
  26790. }
  26791. return null;
  26792. };
  26793. /**
  26794. * Gets a camera using its name
  26795. * @param name defines the camera's name
  26796. * @return the camera or null if none found.
  26797. */
  26798. Scene.prototype.getCameraByName = function (name) {
  26799. for (var index = 0; index < this.cameras.length; index++) {
  26800. if (this.cameras[index].name === name) {
  26801. return this.cameras[index];
  26802. }
  26803. }
  26804. return null;
  26805. };
  26806. /**
  26807. * Gets a bone using its id
  26808. * @param id defines the bone's id
  26809. * @return the bone or null if not found
  26810. */
  26811. Scene.prototype.getBoneByID = function (id) {
  26812. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26813. var skeleton = this.skeletons[skeletonIndex];
  26814. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26815. if (skeleton.bones[boneIndex].id === id) {
  26816. return skeleton.bones[boneIndex];
  26817. }
  26818. }
  26819. }
  26820. return null;
  26821. };
  26822. /**
  26823. * Gets a bone using its id
  26824. * @param name defines the bone's name
  26825. * @return the bone or null if not found
  26826. */
  26827. Scene.prototype.getBoneByName = function (name) {
  26828. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26829. var skeleton = this.skeletons[skeletonIndex];
  26830. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26831. if (skeleton.bones[boneIndex].name === name) {
  26832. return skeleton.bones[boneIndex];
  26833. }
  26834. }
  26835. }
  26836. return null;
  26837. };
  26838. /**
  26839. * Gets a light node using its name
  26840. * @param name defines the the light's name
  26841. * @return the light or null if none found.
  26842. */
  26843. Scene.prototype.getLightByName = function (name) {
  26844. for (var index = 0; index < this.lights.length; index++) {
  26845. if (this.lights[index].name === name) {
  26846. return this.lights[index];
  26847. }
  26848. }
  26849. return null;
  26850. };
  26851. /**
  26852. * Gets a light node using its id
  26853. * @param id defines the light's id
  26854. * @return the light or null if none found.
  26855. */
  26856. Scene.prototype.getLightByID = function (id) {
  26857. for (var index = 0; index < this.lights.length; index++) {
  26858. if (this.lights[index].id === id) {
  26859. return this.lights[index];
  26860. }
  26861. }
  26862. return null;
  26863. };
  26864. /**
  26865. * Gets a light node using its scene-generated unique ID
  26866. * @param uniqueId defines the light's unique id
  26867. * @return the light or null if none found.
  26868. */
  26869. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26870. for (var index = 0; index < this.lights.length; index++) {
  26871. if (this.lights[index].uniqueId === uniqueId) {
  26872. return this.lights[index];
  26873. }
  26874. }
  26875. return null;
  26876. };
  26877. /**
  26878. * Gets a particle system by id
  26879. * @param id defines the particle system id
  26880. * @return the corresponding system or null if none found
  26881. */
  26882. Scene.prototype.getParticleSystemByID = function (id) {
  26883. for (var index = 0; index < this.particleSystems.length; index++) {
  26884. if (this.particleSystems[index].id === id) {
  26885. return this.particleSystems[index];
  26886. }
  26887. }
  26888. return null;
  26889. };
  26890. /**
  26891. * Gets a geometry using its ID
  26892. * @param id defines the geometry's id
  26893. * @return the geometry or null if none found.
  26894. */
  26895. Scene.prototype.getGeometryByID = function (id) {
  26896. for (var index = 0; index < this.geometries.length; index++) {
  26897. if (this.geometries[index].id === id) {
  26898. return this.geometries[index];
  26899. }
  26900. }
  26901. return null;
  26902. };
  26903. /**
  26904. * Add a new geometry to this scene
  26905. * @param geometry defines the geometry to be added to the scene.
  26906. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26907. * @return a boolean defining if the geometry was added or not
  26908. */
  26909. Scene.prototype.pushGeometry = function (geometry, force) {
  26910. if (!force && this.getGeometryByID(geometry.id)) {
  26911. return false;
  26912. }
  26913. this.geometries.push(geometry);
  26914. //notify the collision coordinator
  26915. if (this.collisionCoordinator) {
  26916. this.collisionCoordinator.onGeometryAdded(geometry);
  26917. }
  26918. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26919. return true;
  26920. };
  26921. /**
  26922. * Removes an existing geometry
  26923. * @param geometry defines the geometry to be removed from the scene
  26924. * @return a boolean defining if the geometry was removed or not
  26925. */
  26926. Scene.prototype.removeGeometry = function (geometry) {
  26927. var index = this.geometries.indexOf(geometry);
  26928. if (index > -1) {
  26929. this.geometries.splice(index, 1);
  26930. //notify the collision coordinator
  26931. if (this.collisionCoordinator) {
  26932. this.collisionCoordinator.onGeometryDeleted(geometry);
  26933. }
  26934. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26935. return true;
  26936. }
  26937. return false;
  26938. };
  26939. /**
  26940. * Gets the list of geometries attached to the scene
  26941. * @returns an array of Geometry
  26942. */
  26943. Scene.prototype.getGeometries = function () {
  26944. return this.geometries;
  26945. };
  26946. /**
  26947. * Gets the first added mesh found of a given ID
  26948. * @param id defines the id to search for
  26949. * @return the mesh found or null if not found at all
  26950. */
  26951. Scene.prototype.getMeshByID = function (id) {
  26952. for (var index = 0; index < this.meshes.length; index++) {
  26953. if (this.meshes[index].id === id) {
  26954. return this.meshes[index];
  26955. }
  26956. }
  26957. return null;
  26958. };
  26959. /**
  26960. * Gets a list of meshes using their id
  26961. * @param id defines the id to search for
  26962. * @returns a list of meshes
  26963. */
  26964. Scene.prototype.getMeshesByID = function (id) {
  26965. return this.meshes.filter(function (m) {
  26966. return m.id === id;
  26967. });
  26968. };
  26969. /**
  26970. * Gets the first added transform node found of a given ID
  26971. * @param id defines the id to search for
  26972. * @return the found transform node or null if not found at all.
  26973. */
  26974. Scene.prototype.getTransformNodeByID = function (id) {
  26975. for (var index = 0; index < this.transformNodes.length; index++) {
  26976. if (this.transformNodes[index].id === id) {
  26977. return this.transformNodes[index];
  26978. }
  26979. }
  26980. return null;
  26981. };
  26982. /**
  26983. * Gets a list of transform nodes using their id
  26984. * @param id defines the id to search for
  26985. * @returns a list of transform nodes
  26986. */
  26987. Scene.prototype.getTransformNodesByID = function (id) {
  26988. return this.transformNodes.filter(function (m) {
  26989. return m.id === id;
  26990. });
  26991. };
  26992. /**
  26993. * Gets a mesh with its auto-generated unique id
  26994. * @param uniqueId defines the unique id to search for
  26995. * @return the found mesh or null if not found at all.
  26996. */
  26997. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26998. for (var index = 0; index < this.meshes.length; index++) {
  26999. if (this.meshes[index].uniqueId === uniqueId) {
  27000. return this.meshes[index];
  27001. }
  27002. }
  27003. return null;
  27004. };
  27005. /**
  27006. * Gets a the last added mesh using a given id
  27007. * @param id defines the id to search for
  27008. * @return the found mesh or null if not found at all.
  27009. */
  27010. Scene.prototype.getLastMeshByID = function (id) {
  27011. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27012. if (this.meshes[index].id === id) {
  27013. return this.meshes[index];
  27014. }
  27015. }
  27016. return null;
  27017. };
  27018. /**
  27019. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27020. * @param id defines the id to search for
  27021. * @return the found node or null if not found at all
  27022. */
  27023. Scene.prototype.getLastEntryByID = function (id) {
  27024. var index;
  27025. for (index = this.meshes.length - 1; index >= 0; index--) {
  27026. if (this.meshes[index].id === id) {
  27027. return this.meshes[index];
  27028. }
  27029. }
  27030. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27031. if (this.transformNodes[index].id === id) {
  27032. return this.transformNodes[index];
  27033. }
  27034. }
  27035. for (index = this.cameras.length - 1; index >= 0; index--) {
  27036. if (this.cameras[index].id === id) {
  27037. return this.cameras[index];
  27038. }
  27039. }
  27040. for (index = this.lights.length - 1; index >= 0; index--) {
  27041. if (this.lights[index].id === id) {
  27042. return this.lights[index];
  27043. }
  27044. }
  27045. return null;
  27046. };
  27047. /**
  27048. * Gets a node (Mesh, Camera, Light) using a given id
  27049. * @param id defines the id to search for
  27050. * @return the found node or null if not found at all
  27051. */
  27052. Scene.prototype.getNodeByID = function (id) {
  27053. var mesh = this.getMeshByID(id);
  27054. if (mesh) {
  27055. return mesh;
  27056. }
  27057. var light = this.getLightByID(id);
  27058. if (light) {
  27059. return light;
  27060. }
  27061. var camera = this.getCameraByID(id);
  27062. if (camera) {
  27063. return camera;
  27064. }
  27065. var bone = this.getBoneByID(id);
  27066. return bone;
  27067. };
  27068. /**
  27069. * Gets a node (Mesh, Camera, Light) using a given name
  27070. * @param name defines the name to search for
  27071. * @return the found node or null if not found at all.
  27072. */
  27073. Scene.prototype.getNodeByName = function (name) {
  27074. var mesh = this.getMeshByName(name);
  27075. if (mesh) {
  27076. return mesh;
  27077. }
  27078. var light = this.getLightByName(name);
  27079. if (light) {
  27080. return light;
  27081. }
  27082. var camera = this.getCameraByName(name);
  27083. if (camera) {
  27084. return camera;
  27085. }
  27086. var bone = this.getBoneByName(name);
  27087. return bone;
  27088. };
  27089. /**
  27090. * Gets a mesh using a given name
  27091. * @param name defines the name to search for
  27092. * @return the found mesh or null if not found at all.
  27093. */
  27094. Scene.prototype.getMeshByName = function (name) {
  27095. for (var index = 0; index < this.meshes.length; index++) {
  27096. if (this.meshes[index].name === name) {
  27097. return this.meshes[index];
  27098. }
  27099. }
  27100. return null;
  27101. };
  27102. /**
  27103. * Gets a transform node using a given name
  27104. * @param name defines the name to search for
  27105. * @return the found transform node or null if not found at all.
  27106. */
  27107. Scene.prototype.getTransformNodeByName = function (name) {
  27108. for (var index = 0; index < this.transformNodes.length; index++) {
  27109. if (this.transformNodes[index].name === name) {
  27110. return this.transformNodes[index];
  27111. }
  27112. }
  27113. return null;
  27114. };
  27115. /**
  27116. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27117. * @param id defines the id to search for
  27118. * @return the found skeleton or null if not found at all.
  27119. */
  27120. Scene.prototype.getLastSkeletonByID = function (id) {
  27121. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27122. if (this.skeletons[index].id === id) {
  27123. return this.skeletons[index];
  27124. }
  27125. }
  27126. return null;
  27127. };
  27128. /**
  27129. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27130. * @param id defines the id to search for
  27131. * @return the found skeleton or null if not found at all.
  27132. */
  27133. Scene.prototype.getSkeletonById = function (id) {
  27134. for (var index = 0; index < this.skeletons.length; index++) {
  27135. if (this.skeletons[index].id === id) {
  27136. return this.skeletons[index];
  27137. }
  27138. }
  27139. return null;
  27140. };
  27141. /**
  27142. * Gets a skeleton using a given name
  27143. * @param name defines the name to search for
  27144. * @return the found skeleton or null if not found at all.
  27145. */
  27146. Scene.prototype.getSkeletonByName = function (name) {
  27147. for (var index = 0; index < this.skeletons.length; index++) {
  27148. if (this.skeletons[index].name === name) {
  27149. return this.skeletons[index];
  27150. }
  27151. }
  27152. return null;
  27153. };
  27154. /**
  27155. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27156. * @param id defines the id to search for
  27157. * @return the found morph target manager or null if not found at all.
  27158. */
  27159. Scene.prototype.getMorphTargetManagerById = function (id) {
  27160. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27161. if (this.morphTargetManagers[index].uniqueId === id) {
  27162. return this.morphTargetManagers[index];
  27163. }
  27164. }
  27165. return null;
  27166. };
  27167. /**
  27168. * Gets a boolean indicating if the given mesh is active
  27169. * @param mesh defines the mesh to look for
  27170. * @returns true if the mesh is in the active list
  27171. */
  27172. Scene.prototype.isActiveMesh = function (mesh) {
  27173. return (this._activeMeshes.indexOf(mesh) !== -1);
  27174. };
  27175. Object.defineProperty(Scene.prototype, "uid", {
  27176. /**
  27177. * Return a unique id as a string which can serve as an identifier for the scene
  27178. */
  27179. get: function () {
  27180. if (!this._uid) {
  27181. this._uid = BABYLON.Tools.RandomId();
  27182. }
  27183. return this._uid;
  27184. },
  27185. enumerable: true,
  27186. configurable: true
  27187. });
  27188. /**
  27189. * Add an externaly attached data from its key.
  27190. * This method call will fail and return false, if such key already exists.
  27191. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27192. * @param key the unique key that identifies the data
  27193. * @param data the data object to associate to the key for this Engine instance
  27194. * @return true if no such key were already present and the data was added successfully, false otherwise
  27195. */
  27196. Scene.prototype.addExternalData = function (key, data) {
  27197. if (!this._externalData) {
  27198. this._externalData = new BABYLON.StringDictionary();
  27199. }
  27200. return this._externalData.add(key, data);
  27201. };
  27202. /**
  27203. * Get an externaly attached data from its key
  27204. * @param key the unique key that identifies the data
  27205. * @return the associated data, if present (can be null), or undefined if not present
  27206. */
  27207. Scene.prototype.getExternalData = function (key) {
  27208. if (!this._externalData) {
  27209. return null;
  27210. }
  27211. return this._externalData.get(key);
  27212. };
  27213. /**
  27214. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27215. * @param key the unique key that identifies the data
  27216. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27217. * @return the associated data, can be null if the factory returned null.
  27218. */
  27219. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27220. if (!this._externalData) {
  27221. this._externalData = new BABYLON.StringDictionary();
  27222. }
  27223. return this._externalData.getOrAddWithFactory(key, factory);
  27224. };
  27225. /**
  27226. * Remove an externaly attached data from the Engine instance
  27227. * @param key the unique key that identifies the data
  27228. * @return true if the data was successfully removed, false if it doesn't exist
  27229. */
  27230. Scene.prototype.removeExternalData = function (key) {
  27231. return this._externalData.remove(key);
  27232. };
  27233. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27234. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27235. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27236. var step = _a[_i];
  27237. step.action(mesh, subMesh);
  27238. }
  27239. var material = subMesh.getMaterial();
  27240. if (material !== null && material !== undefined) {
  27241. // Render targets
  27242. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  27243. if (this._processedMaterials.indexOf(material) === -1) {
  27244. this._processedMaterials.push(material);
  27245. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27246. }
  27247. }
  27248. // Dispatch
  27249. this._activeIndices.addCount(subMesh.indexCount, false);
  27250. this._renderingManager.dispatch(subMesh, mesh, material);
  27251. }
  27252. }
  27253. };
  27254. /**
  27255. * Clear the processed materials smart array preventing retention point in material dispose.
  27256. */
  27257. Scene.prototype.freeProcessedMaterials = function () {
  27258. this._processedMaterials.dispose();
  27259. };
  27260. /**
  27261. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27262. */
  27263. Scene.prototype.freeActiveMeshes = function () {
  27264. this._activeMeshes.dispose();
  27265. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27266. this.activeCamera._activeMeshes.dispose();
  27267. }
  27268. if (this.activeCameras) {
  27269. for (var i = 0; i < this.activeCameras.length; i++) {
  27270. var activeCamera = this.activeCameras[i];
  27271. if (activeCamera && activeCamera._activeMeshes) {
  27272. activeCamera._activeMeshes.dispose();
  27273. }
  27274. }
  27275. }
  27276. };
  27277. /**
  27278. * Clear the info related to rendering groups preventing retention points during dispose.
  27279. */
  27280. Scene.prototype.freeRenderingGroups = function () {
  27281. if (this._renderingManager) {
  27282. this._renderingManager.freeRenderingGroups();
  27283. }
  27284. if (this.textures) {
  27285. for (var i = 0; i < this.textures.length; i++) {
  27286. var texture = this.textures[i];
  27287. if (texture && texture.renderList) {
  27288. texture.freeRenderingGroups();
  27289. }
  27290. }
  27291. }
  27292. };
  27293. /** @hidden */
  27294. Scene.prototype._isInIntermediateRendering = function () {
  27295. return this._intermediateRendering;
  27296. };
  27297. /**
  27298. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27299. * @returns the current scene
  27300. */
  27301. Scene.prototype.freezeActiveMeshes = function () {
  27302. if (!this.activeCamera) {
  27303. return this;
  27304. }
  27305. if (!this._frustumPlanes) {
  27306. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27307. }
  27308. this._evaluateActiveMeshes();
  27309. this._activeMeshesFrozen = true;
  27310. return this;
  27311. };
  27312. /**
  27313. * Use this function to restart evaluating active meshes on every frame
  27314. * @returns the current scene
  27315. */
  27316. Scene.prototype.unfreezeActiveMeshes = function () {
  27317. this._activeMeshesFrozen = false;
  27318. return this;
  27319. };
  27320. Scene.prototype._evaluateActiveMeshes = function () {
  27321. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27322. return;
  27323. }
  27324. if (!this.activeCamera) {
  27325. return;
  27326. }
  27327. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27328. this.activeCamera._activeMeshes.reset();
  27329. this._activeMeshes.reset();
  27330. this._renderingManager.reset();
  27331. this._processedMaterials.reset();
  27332. this._activeParticleSystems.reset();
  27333. this._activeSkeletons.reset();
  27334. this._softwareSkinnedMeshes.reset();
  27335. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27336. var step = _a[_i];
  27337. step.action();
  27338. }
  27339. // Determine mesh candidates
  27340. var meshes = this.getActiveMeshCandidates();
  27341. // Check each mesh
  27342. var len = meshes.length;
  27343. for (var i = 0; i < len; i++) {
  27344. var mesh = meshes.data[i];
  27345. if (mesh.isBlocked) {
  27346. continue;
  27347. }
  27348. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27349. if (!mesh.isReady() || !mesh.isEnabled()) {
  27350. continue;
  27351. }
  27352. mesh.computeWorldMatrix();
  27353. // Intersections
  27354. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27355. this._meshesForIntersections.pushNoDuplicate(mesh);
  27356. }
  27357. // Switch to current LOD
  27358. var meshLOD = mesh.getLOD(this.activeCamera);
  27359. if (meshLOD === undefined || meshLOD === null) {
  27360. continue;
  27361. }
  27362. mesh._preActivate();
  27363. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27364. this._activeMeshes.push(mesh);
  27365. this.activeCamera._activeMeshes.push(mesh);
  27366. mesh._activate(this._renderId);
  27367. if (meshLOD !== mesh) {
  27368. meshLOD._activate(this._renderId);
  27369. }
  27370. this._activeMesh(mesh, meshLOD);
  27371. }
  27372. }
  27373. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27374. // Particle systems
  27375. if (this.particlesEnabled) {
  27376. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27377. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27378. var particleSystem = this.particleSystems[particleIndex];
  27379. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27380. continue;
  27381. }
  27382. var emitter = particleSystem.emitter;
  27383. if (!emitter.position || emitter.isEnabled()) {
  27384. this._activeParticleSystems.push(particleSystem);
  27385. particleSystem.animate();
  27386. this._renderingManager.dispatchParticles(particleSystem);
  27387. }
  27388. }
  27389. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27390. }
  27391. };
  27392. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27393. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27394. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27395. mesh.skeleton.prepare();
  27396. }
  27397. if (!mesh.computeBonesUsingShaders) {
  27398. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27399. }
  27400. }
  27401. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27402. var step = _a[_i];
  27403. step.action(sourceMesh, mesh);
  27404. }
  27405. if (mesh !== undefined && mesh !== null
  27406. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27407. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  27408. var len = subMeshes.length;
  27409. for (var i = 0; i < len; i++) {
  27410. var subMesh = subMeshes.data[i];
  27411. this._evaluateSubMesh(subMesh, mesh);
  27412. }
  27413. }
  27414. };
  27415. /**
  27416. * Update the transform matrix to update from the current active camera
  27417. * @param force defines a boolean used to force the update even if cache is up to date
  27418. */
  27419. Scene.prototype.updateTransformMatrix = function (force) {
  27420. if (!this.activeCamera) {
  27421. return;
  27422. }
  27423. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27424. };
  27425. /**
  27426. * 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)
  27427. * @param alternateCamera defines the camera to use
  27428. */
  27429. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27430. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27431. };
  27432. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27433. if (camera && camera._skipRendering) {
  27434. return;
  27435. }
  27436. var engine = this._engine;
  27437. this.activeCamera = camera;
  27438. if (!this.activeCamera)
  27439. throw new Error("Active camera not set");
  27440. // Viewport
  27441. engine.setViewport(this.activeCamera.viewport);
  27442. // Camera
  27443. this.resetCachedMaterial();
  27444. this._renderId++;
  27445. this.updateTransformMatrix();
  27446. if (camera._alternateCamera) {
  27447. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27448. this._alternateRendering = true;
  27449. }
  27450. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27451. // Meshes
  27452. this._evaluateActiveMeshes();
  27453. // Software skinning
  27454. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27455. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27456. mesh.applySkeleton(mesh.skeleton);
  27457. }
  27458. // Render targets
  27459. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27460. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27461. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27462. }
  27463. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27464. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27465. }
  27466. // Collects render targets from external components.
  27467. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  27468. var step = _a[_i];
  27469. step.action(this._renderTargets);
  27470. }
  27471. if (this.renderTargetsEnabled) {
  27472. this._intermediateRendering = true;
  27473. if (this._renderTargets.length > 0) {
  27474. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27475. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27476. var renderTarget = this._renderTargets.data[renderIndex];
  27477. if (renderTarget._shouldRender()) {
  27478. this._renderId++;
  27479. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27480. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27481. }
  27482. }
  27483. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27484. this._renderId++;
  27485. }
  27486. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  27487. var step = _c[_b];
  27488. step.action(this.activeCamera);
  27489. }
  27490. this._intermediateRendering = false;
  27491. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27492. }
  27493. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27494. // Prepare Frame
  27495. if (this.postProcessManager) {
  27496. this.postProcessManager._prepareFrame();
  27497. }
  27498. // Before Camera Draw
  27499. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  27500. var step = _e[_d];
  27501. step.action(this.activeCamera);
  27502. }
  27503. // Render
  27504. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27505. this._renderingManager.render(null, null, true, true);
  27506. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27507. // After Camera Draw
  27508. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  27509. var step = _g[_f];
  27510. step.action(this.activeCamera);
  27511. }
  27512. // Finalize frame
  27513. if (this.postProcessManager) {
  27514. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27515. }
  27516. // Reset some special arrays
  27517. this._renderTargets.reset();
  27518. this._alternateRendering = false;
  27519. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27520. };
  27521. Scene.prototype._processSubCameras = function (camera) {
  27522. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27523. this._renderForCamera(camera);
  27524. return;
  27525. }
  27526. // rig cameras
  27527. for (var index = 0; index < camera._rigCameras.length; index++) {
  27528. this._renderForCamera(camera._rigCameras[index], camera);
  27529. }
  27530. this.activeCamera = camera;
  27531. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27532. };
  27533. Scene.prototype._checkIntersections = function () {
  27534. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27535. var sourceMesh = this._meshesForIntersections.data[index];
  27536. if (!sourceMesh.actionManager) {
  27537. continue;
  27538. }
  27539. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27540. var action = sourceMesh.actionManager.actions[actionIndex];
  27541. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27542. var parameters = action.getTriggerParameter();
  27543. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27544. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27545. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27546. if (areIntersecting && currentIntersectionInProgress === -1) {
  27547. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27548. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27549. sourceMesh._intersectionsInProgress.push(otherMesh);
  27550. }
  27551. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27552. sourceMesh._intersectionsInProgress.push(otherMesh);
  27553. }
  27554. }
  27555. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27556. //They intersected, and now they don't.
  27557. //is this trigger an exit trigger? execute an event.
  27558. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27559. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27560. }
  27561. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27562. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27563. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27564. return otherMesh === parameterMesh;
  27565. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27566. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27567. }
  27568. }
  27569. }
  27570. }
  27571. }
  27572. };
  27573. /** @hidden */
  27574. Scene.prototype._advancePhysicsEngineStep = function (step) {
  27575. // Do nothing. Code will be replaced if physics engine component is referenced
  27576. };
  27577. /**
  27578. * Render the scene
  27579. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27580. */
  27581. Scene.prototype.render = function (updateCameras) {
  27582. if (updateCameras === void 0) { updateCameras = true; }
  27583. if (this.isDisposed) {
  27584. return;
  27585. }
  27586. this._frameId++;
  27587. // Register components that have been associated lately to the scene.
  27588. this._registerTransientComponents();
  27589. this._activeParticles.fetchNewFrame();
  27590. this._totalVertices.fetchNewFrame();
  27591. this._activeIndices.fetchNewFrame();
  27592. this._activeBones.fetchNewFrame();
  27593. this._meshesForIntersections.reset();
  27594. this.resetCachedMaterial();
  27595. this.onBeforeAnimationsObservable.notifyObservers(this);
  27596. // Actions
  27597. if (this.actionManager) {
  27598. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27599. }
  27600. if (this._engine.isDeterministicLockStep()) {
  27601. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27602. var defaultFPS = (60.0 / 1000.0);
  27603. var defaultFrameTime = this.getDeterministicFrameTime();
  27604. var stepsTaken = 0;
  27605. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27606. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27607. internalSteps = Math.min(internalSteps, maxSubSteps);
  27608. do {
  27609. this.onBeforeStepObservable.notifyObservers(this);
  27610. // Animations
  27611. this._animationRatio = defaultFrameTime * defaultFPS;
  27612. this._animate();
  27613. this.onAfterAnimationsObservable.notifyObservers(this);
  27614. // Physics
  27615. this._advancePhysicsEngineStep(defaultFrameTime);
  27616. this.onAfterStepObservable.notifyObservers(this);
  27617. this._currentStepId++;
  27618. stepsTaken++;
  27619. deltaTime -= defaultFrameTime;
  27620. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27621. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27622. }
  27623. else {
  27624. // Animations
  27625. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27626. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27627. this._animate();
  27628. this.onAfterAnimationsObservable.notifyObservers(this);
  27629. // Physics
  27630. this._advancePhysicsEngineStep(deltaTime);
  27631. }
  27632. // Before camera update steps
  27633. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27634. var step = _a[_i];
  27635. step.action();
  27636. }
  27637. // Update Cameras
  27638. if (updateCameras) {
  27639. if (this.activeCameras.length > 0) {
  27640. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27641. var camera = this.activeCameras[cameraIndex];
  27642. camera.update();
  27643. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27644. // rig cameras
  27645. for (var index = 0; index < camera._rigCameras.length; index++) {
  27646. camera._rigCameras[index].update();
  27647. }
  27648. }
  27649. }
  27650. }
  27651. else if (this.activeCamera) {
  27652. this.activeCamera.update();
  27653. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27654. // rig cameras
  27655. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27656. this.activeCamera._rigCameras[index].update();
  27657. }
  27658. }
  27659. }
  27660. }
  27661. // Before render
  27662. this.onBeforeRenderObservable.notifyObservers(this);
  27663. // Customs render targets
  27664. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27665. var engine = this.getEngine();
  27666. var currentActiveCamera = this.activeCamera;
  27667. if (this.renderTargetsEnabled) {
  27668. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27669. this._intermediateRendering = true;
  27670. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27671. var renderTarget = this.customRenderTargets[customIndex];
  27672. if (renderTarget._shouldRender()) {
  27673. this._renderId++;
  27674. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27675. if (!this.activeCamera)
  27676. throw new Error("Active camera not set");
  27677. // Viewport
  27678. engine.setViewport(this.activeCamera.viewport);
  27679. // Camera
  27680. this.updateTransformMatrix();
  27681. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27682. }
  27683. }
  27684. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27685. this._intermediateRendering = false;
  27686. this._renderId++;
  27687. }
  27688. // Restore back buffer
  27689. if (this.customRenderTargets.length > 0) {
  27690. engine.restoreDefaultFramebuffer();
  27691. }
  27692. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27693. this.activeCamera = currentActiveCamera;
  27694. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  27695. var step = _c[_b];
  27696. step.action();
  27697. }
  27698. // Clear
  27699. if (this.autoClearDepthAndStencil || this.autoClear) {
  27700. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27701. }
  27702. // Collects render targets from external components.
  27703. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  27704. var step = _e[_d];
  27705. step.action(this._renderTargets);
  27706. }
  27707. // Multi-cameras?
  27708. if (this.activeCameras.length > 0) {
  27709. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27710. if (cameraIndex > 0) {
  27711. this._engine.clear(null, false, true, true);
  27712. }
  27713. this._processSubCameras(this.activeCameras[cameraIndex]);
  27714. }
  27715. }
  27716. else {
  27717. if (!this.activeCamera) {
  27718. throw new Error("No camera defined");
  27719. }
  27720. this._processSubCameras(this.activeCamera);
  27721. }
  27722. // Intersection checks
  27723. this._checkIntersections();
  27724. // Executes the after render stage actions.
  27725. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  27726. var step = _g[_f];
  27727. step.action();
  27728. }
  27729. // After render
  27730. if (this.afterRender) {
  27731. this.afterRender();
  27732. }
  27733. this.onAfterRenderObservable.notifyObservers(this);
  27734. // Cleaning
  27735. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27736. var data = this._toBeDisposed.data[index];
  27737. if (data) {
  27738. data.dispose();
  27739. }
  27740. }
  27741. this._toBeDisposed.reset();
  27742. if (this.dumpNextRenderTargets) {
  27743. this.dumpNextRenderTargets = false;
  27744. }
  27745. this._activeBones.addCount(0, true);
  27746. this._activeIndices.addCount(0, true);
  27747. this._activeParticles.addCount(0, true);
  27748. };
  27749. /**
  27750. * Freeze all materials
  27751. * A frozen material will not be updatable but should be faster to render
  27752. */
  27753. Scene.prototype.freezeMaterials = function () {
  27754. for (var i = 0; i < this.materials.length; i++) {
  27755. this.materials[i].freeze();
  27756. }
  27757. };
  27758. /**
  27759. * Unfreeze all materials
  27760. * A frozen material will not be updatable but should be faster to render
  27761. */
  27762. Scene.prototype.unfreezeMaterials = function () {
  27763. for (var i = 0; i < this.materials.length; i++) {
  27764. this.materials[i].unfreeze();
  27765. }
  27766. };
  27767. /**
  27768. * Releases all held ressources
  27769. */
  27770. Scene.prototype.dispose = function () {
  27771. this.beforeRender = null;
  27772. this.afterRender = null;
  27773. this.skeletons = [];
  27774. this.morphTargetManagers = [];
  27775. this._transientComponents = [];
  27776. this._isReadyForMeshStage.clear();
  27777. this._beforeEvaluateActiveMeshStage.clear();
  27778. this._evaluateSubMeshStage.clear();
  27779. this._activeMeshStage.clear();
  27780. this._cameraDrawRenderTargetStage.clear();
  27781. this._beforeCameraDrawStage.clear();
  27782. this._beforeRenderingGroupDrawStage.clear();
  27783. this._beforeRenderingMeshStage.clear();
  27784. this._afterRenderingMeshStage.clear();
  27785. this._afterRenderingGroupDrawStage.clear();
  27786. this._afterCameraDrawStage.clear();
  27787. this._afterRenderStage.clear();
  27788. this._beforeCameraUpdateStage.clear();
  27789. this._beforeClearStage.clear();
  27790. this._gatherRenderTargetsStage.clear();
  27791. this._gatherActiveCameraRenderTargetsStage.clear();
  27792. this._pointerMoveStage.clear();
  27793. this._pointerDownStage.clear();
  27794. this._pointerUpStage.clear();
  27795. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  27796. var component = _a[_i];
  27797. component.dispose();
  27798. }
  27799. this.importedMeshesFiles = new Array();
  27800. this.stopAllAnimations();
  27801. this.resetCachedMaterial();
  27802. // Smart arrays
  27803. if (this.activeCamera) {
  27804. this.activeCamera._activeMeshes.dispose();
  27805. this.activeCamera = null;
  27806. }
  27807. this._activeMeshes.dispose();
  27808. this._renderingManager.dispose();
  27809. this._processedMaterials.dispose();
  27810. this._activeParticleSystems.dispose();
  27811. this._activeSkeletons.dispose();
  27812. this._softwareSkinnedMeshes.dispose();
  27813. this._renderTargets.dispose();
  27814. this._registeredForLateAnimationBindings.dispose();
  27815. this._meshesForIntersections.dispose();
  27816. this._toBeDisposed.dispose();
  27817. // Abort active requests
  27818. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  27819. var request = _c[_b];
  27820. request.abort();
  27821. }
  27822. // Events
  27823. this.onDisposeObservable.notifyObservers(this);
  27824. this.onDisposeObservable.clear();
  27825. this.onBeforeRenderObservable.clear();
  27826. this.onAfterRenderObservable.clear();
  27827. this.onBeforeRenderTargetsRenderObservable.clear();
  27828. this.onAfterRenderTargetsRenderObservable.clear();
  27829. this.onAfterStepObservable.clear();
  27830. this.onBeforeStepObservable.clear();
  27831. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27832. this.onAfterActiveMeshesEvaluationObservable.clear();
  27833. this.onBeforeParticlesRenderingObservable.clear();
  27834. this.onAfterParticlesRenderingObservable.clear();
  27835. this.onBeforeDrawPhaseObservable.clear();
  27836. this.onAfterDrawPhaseObservable.clear();
  27837. this.onBeforeAnimationsObservable.clear();
  27838. this.onAfterAnimationsObservable.clear();
  27839. this.onDataLoadedObservable.clear();
  27840. this.onBeforeRenderingGroupObservable.clear();
  27841. this.onAfterRenderingGroupObservable.clear();
  27842. this.onMeshImportedObservable.clear();
  27843. this.detachControl();
  27844. // Detach cameras
  27845. var canvas = this._engine.getRenderingCanvas();
  27846. if (canvas) {
  27847. var index;
  27848. for (index = 0; index < this.cameras.length; index++) {
  27849. this.cameras[index].detachControl(canvas);
  27850. }
  27851. }
  27852. // Release animation groups
  27853. while (this.animationGroups.length) {
  27854. this.animationGroups[0].dispose();
  27855. }
  27856. // Release lights
  27857. while (this.lights.length) {
  27858. this.lights[0].dispose();
  27859. }
  27860. // Release meshes
  27861. while (this.meshes.length) {
  27862. this.meshes[0].dispose(true);
  27863. }
  27864. while (this.transformNodes.length) {
  27865. this.removeTransformNode(this.transformNodes[0]);
  27866. }
  27867. // Release cameras
  27868. while (this.cameras.length) {
  27869. this.cameras[0].dispose();
  27870. }
  27871. // Release materials
  27872. if (this.defaultMaterial) {
  27873. this.defaultMaterial.dispose();
  27874. }
  27875. while (this.multiMaterials.length) {
  27876. this.multiMaterials[0].dispose();
  27877. }
  27878. while (this.materials.length) {
  27879. this.materials[0].dispose();
  27880. }
  27881. // Release particles
  27882. while (this.particleSystems.length) {
  27883. this.particleSystems[0].dispose();
  27884. }
  27885. // Release postProcesses
  27886. while (this.postProcesses.length) {
  27887. this.postProcesses[0].dispose();
  27888. }
  27889. // Release textures
  27890. while (this.textures.length) {
  27891. this.textures[0].dispose();
  27892. }
  27893. // Release UBO
  27894. this._sceneUbo.dispose();
  27895. if (this._alternateSceneUbo) {
  27896. this._alternateSceneUbo.dispose();
  27897. }
  27898. // Post-processes
  27899. this.postProcessManager.dispose();
  27900. // Remove from engine
  27901. index = this._engine.scenes.indexOf(this);
  27902. if (index > -1) {
  27903. this._engine.scenes.splice(index, 1);
  27904. }
  27905. this._engine.wipeCaches(true);
  27906. this._isDisposed = true;
  27907. };
  27908. Object.defineProperty(Scene.prototype, "isDisposed", {
  27909. /**
  27910. * Gets if the scene is already disposed
  27911. */
  27912. get: function () {
  27913. return this._isDisposed;
  27914. },
  27915. enumerable: true,
  27916. configurable: true
  27917. });
  27918. /**
  27919. * Call this function to reduce memory footprint of the scene.
  27920. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  27921. */
  27922. Scene.prototype.clearCachedVertexData = function () {
  27923. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27924. var mesh = this.meshes[meshIndex];
  27925. var geometry = mesh.geometry;
  27926. if (geometry) {
  27927. geometry._indices = [];
  27928. for (var vbName in geometry._vertexBuffers) {
  27929. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  27930. continue;
  27931. }
  27932. geometry._vertexBuffers[vbName]._buffer._data = null;
  27933. }
  27934. }
  27935. }
  27936. };
  27937. /**
  27938. * This function will remove the local cached buffer data from texture.
  27939. * It will save memory but will prevent the texture from being rebuilt
  27940. */
  27941. Scene.prototype.cleanCachedTextureBuffer = function () {
  27942. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  27943. var baseTexture = _a[_i];
  27944. var buffer = baseTexture._buffer;
  27945. if (buffer) {
  27946. baseTexture._buffer = null;
  27947. }
  27948. }
  27949. };
  27950. /**
  27951. * Get the world extend vectors with an optional filter
  27952. *
  27953. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  27954. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  27955. */
  27956. Scene.prototype.getWorldExtends = function (filterPredicate) {
  27957. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  27958. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  27959. filterPredicate = filterPredicate || (function () { return true; });
  27960. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  27961. mesh.computeWorldMatrix(true);
  27962. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  27963. return;
  27964. }
  27965. var boundingInfo = mesh.getBoundingInfo();
  27966. var minBox = boundingInfo.boundingBox.minimumWorld;
  27967. var maxBox = boundingInfo.boundingBox.maximumWorld;
  27968. BABYLON.Tools.CheckExtends(minBox, min, max);
  27969. BABYLON.Tools.CheckExtends(maxBox, min, max);
  27970. });
  27971. return {
  27972. min: min,
  27973. max: max
  27974. };
  27975. };
  27976. // Picking
  27977. /**
  27978. * Creates a ray that can be used to pick in the scene
  27979. * @param x defines the x coordinate of the origin (on-screen)
  27980. * @param y defines the y coordinate of the origin (on-screen)
  27981. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27982. * @param camera defines the camera to use for the picking
  27983. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27984. * @returns a Ray
  27985. */
  27986. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  27987. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27988. var result = BABYLON.Ray.Zero();
  27989. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  27990. return result;
  27991. };
  27992. /**
  27993. * Creates a ray that can be used to pick in the scene
  27994. * @param x defines the x coordinate of the origin (on-screen)
  27995. * @param y defines the y coordinate of the origin (on-screen)
  27996. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27997. * @param result defines the ray where to store the picking ray
  27998. * @param camera defines the camera to use for the picking
  27999. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28000. * @returns the current scene
  28001. */
  28002. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28003. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28004. var engine = this._engine;
  28005. if (!camera) {
  28006. if (!this.activeCamera)
  28007. throw new Error("Active camera not set");
  28008. camera = this.activeCamera;
  28009. }
  28010. var cameraViewport = camera.viewport;
  28011. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28012. // Moving coordinates to local viewport world
  28013. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28014. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28015. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28016. return this;
  28017. };
  28018. /**
  28019. * Creates a ray that can be used to pick in the scene
  28020. * @param x defines the x coordinate of the origin (on-screen)
  28021. * @param y defines the y coordinate of the origin (on-screen)
  28022. * @param camera defines the camera to use for the picking
  28023. * @returns a Ray
  28024. */
  28025. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28026. var result = BABYLON.Ray.Zero();
  28027. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28028. return result;
  28029. };
  28030. /**
  28031. * Creates a ray that can be used to pick in the scene
  28032. * @param x defines the x coordinate of the origin (on-screen)
  28033. * @param y defines the y coordinate of the origin (on-screen)
  28034. * @param result defines the ray where to store the picking ray
  28035. * @param camera defines the camera to use for the picking
  28036. * @returns the current scene
  28037. */
  28038. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28039. if (!BABYLON.PickingInfo) {
  28040. return this;
  28041. }
  28042. var engine = this._engine;
  28043. if (!camera) {
  28044. if (!this.activeCamera)
  28045. throw new Error("Active camera not set");
  28046. camera = this.activeCamera;
  28047. }
  28048. var cameraViewport = camera.viewport;
  28049. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28050. var identity = BABYLON.Matrix.Identity();
  28051. // Moving coordinates to local viewport world
  28052. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28053. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28054. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28055. return this;
  28056. };
  28057. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28058. if (!BABYLON.PickingInfo) {
  28059. return null;
  28060. }
  28061. var pickingInfo = null;
  28062. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28063. var mesh = this.meshes[meshIndex];
  28064. if (predicate) {
  28065. if (!predicate(mesh)) {
  28066. continue;
  28067. }
  28068. }
  28069. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28070. continue;
  28071. }
  28072. var world = mesh.getWorldMatrix();
  28073. var ray = rayFunction(world);
  28074. var result = mesh.intersects(ray, fastCheck);
  28075. if (!result || !result.hit)
  28076. continue;
  28077. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28078. continue;
  28079. pickingInfo = result;
  28080. if (fastCheck) {
  28081. break;
  28082. }
  28083. }
  28084. return pickingInfo || new BABYLON.PickingInfo();
  28085. };
  28086. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28087. if (!BABYLON.PickingInfo) {
  28088. return null;
  28089. }
  28090. var pickingInfos = new Array();
  28091. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28092. var mesh = this.meshes[meshIndex];
  28093. if (predicate) {
  28094. if (!predicate(mesh)) {
  28095. continue;
  28096. }
  28097. }
  28098. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28099. continue;
  28100. }
  28101. var world = mesh.getWorldMatrix();
  28102. var ray = rayFunction(world);
  28103. var result = mesh.intersects(ray, false);
  28104. if (!result || !result.hit)
  28105. continue;
  28106. pickingInfos.push(result);
  28107. }
  28108. return pickingInfos;
  28109. };
  28110. /** Launch a ray to try to pick a mesh in the scene
  28111. * @param x position on screen
  28112. * @param y position on screen
  28113. * @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
  28114. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28115. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28116. * @returns a PickingInfo
  28117. */
  28118. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28119. var _this = this;
  28120. if (!BABYLON.PickingInfo) {
  28121. return null;
  28122. }
  28123. var result = this._internalPick(function (world) {
  28124. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28125. return _this._tempPickingRay;
  28126. }, predicate, fastCheck);
  28127. if (result) {
  28128. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28129. }
  28130. return result;
  28131. };
  28132. /** Use the given ray to pick a mesh in the scene
  28133. * @param ray The ray to use to pick meshes
  28134. * @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
  28135. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28136. * @returns a PickingInfo
  28137. */
  28138. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28139. var _this = this;
  28140. var result = this._internalPick(function (world) {
  28141. if (!_this._pickWithRayInverseMatrix) {
  28142. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28143. }
  28144. world.invertToRef(_this._pickWithRayInverseMatrix);
  28145. if (!_this._cachedRayForTransform) {
  28146. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28147. }
  28148. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28149. return _this._cachedRayForTransform;
  28150. }, predicate, fastCheck);
  28151. if (result) {
  28152. result.ray = ray;
  28153. }
  28154. return result;
  28155. };
  28156. /**
  28157. * Launch a ray to try to pick a mesh in the scene
  28158. * @param x X position on screen
  28159. * @param y Y position on screen
  28160. * @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
  28161. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28162. * @returns an array of PickingInfo
  28163. */
  28164. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28165. var _this = this;
  28166. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28167. };
  28168. /**
  28169. * Launch a ray to try to pick a mesh in the scene
  28170. * @param ray Ray to use
  28171. * @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
  28172. * @returns an array of PickingInfo
  28173. */
  28174. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28175. var _this = this;
  28176. return this._internalMultiPick(function (world) {
  28177. if (!_this._pickWithRayInverseMatrix) {
  28178. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28179. }
  28180. world.invertToRef(_this._pickWithRayInverseMatrix);
  28181. if (!_this._cachedRayForTransform) {
  28182. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28183. }
  28184. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28185. return _this._cachedRayForTransform;
  28186. }, predicate);
  28187. };
  28188. /**
  28189. * Force the value of meshUnderPointer
  28190. * @param mesh defines the mesh to use
  28191. */
  28192. Scene.prototype.setPointerOverMesh = function (mesh) {
  28193. if (this._pointerOverMesh === mesh) {
  28194. return;
  28195. }
  28196. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28197. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28198. }
  28199. this._pointerOverMesh = mesh;
  28200. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28201. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28202. }
  28203. };
  28204. /**
  28205. * Gets the mesh under the pointer
  28206. * @returns a Mesh or null if no mesh is under the pointer
  28207. */
  28208. Scene.prototype.getPointerOverMesh = function () {
  28209. return this._pointerOverMesh;
  28210. };
  28211. // Misc.
  28212. /** @hidden */
  28213. Scene.prototype._rebuildGeometries = function () {
  28214. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28215. var geometry = _a[_i];
  28216. geometry._rebuild();
  28217. }
  28218. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28219. var mesh = _c[_b];
  28220. mesh._rebuild();
  28221. }
  28222. if (this.postProcessManager) {
  28223. this.postProcessManager._rebuild();
  28224. }
  28225. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28226. var component = _e[_d];
  28227. component.rebuild();
  28228. }
  28229. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28230. var system = _g[_f];
  28231. system.rebuild();
  28232. }
  28233. };
  28234. /** @hidden */
  28235. Scene.prototype._rebuildTextures = function () {
  28236. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28237. var texture = _a[_i];
  28238. texture._rebuild();
  28239. }
  28240. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28241. };
  28242. // Tags
  28243. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28244. if (tagsQuery === undefined) {
  28245. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28246. return list;
  28247. }
  28248. var listByTags = [];
  28249. forEach = forEach || (function (item) { return; });
  28250. for (var i in list) {
  28251. var item = list[i];
  28252. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28253. listByTags.push(item);
  28254. forEach(item);
  28255. }
  28256. }
  28257. return listByTags;
  28258. };
  28259. /**
  28260. * Get a list of meshes by tags
  28261. * @param tagsQuery defines the tags query to use
  28262. * @param forEach defines a predicate used to filter results
  28263. * @returns an array of Mesh
  28264. */
  28265. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28266. return this._getByTags(this.meshes, tagsQuery, forEach);
  28267. };
  28268. /**
  28269. * Get a list of cameras by tags
  28270. * @param tagsQuery defines the tags query to use
  28271. * @param forEach defines a predicate used to filter results
  28272. * @returns an array of Camera
  28273. */
  28274. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28275. return this._getByTags(this.cameras, tagsQuery, forEach);
  28276. };
  28277. /**
  28278. * Get a list of lights by tags
  28279. * @param tagsQuery defines the tags query to use
  28280. * @param forEach defines a predicate used to filter results
  28281. * @returns an array of Light
  28282. */
  28283. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28284. return this._getByTags(this.lights, tagsQuery, forEach);
  28285. };
  28286. /**
  28287. * Get a list of materials by tags
  28288. * @param tagsQuery defines the tags query to use
  28289. * @param forEach defines a predicate used to filter results
  28290. * @returns an array of Material
  28291. */
  28292. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28293. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28294. };
  28295. /**
  28296. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28297. * This allowed control for front to back rendering or reversly depending of the special needs.
  28298. *
  28299. * @param renderingGroupId The rendering group id corresponding to its index
  28300. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28301. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28302. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28303. */
  28304. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28305. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28306. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28307. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28308. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28309. };
  28310. /**
  28311. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28312. *
  28313. * @param renderingGroupId The rendering group id corresponding to its index
  28314. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28315. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28316. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28317. */
  28318. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28319. if (depth === void 0) { depth = true; }
  28320. if (stencil === void 0) { stencil = true; }
  28321. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28322. };
  28323. /**
  28324. * Gets the current auto clear configuration for one rendering group of the rendering
  28325. * manager.
  28326. * @param index the rendering group index to get the information for
  28327. * @returns The auto clear setup for the requested rendering group
  28328. */
  28329. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28330. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28331. };
  28332. /**
  28333. * Will flag all materials as dirty to trigger new shader compilation
  28334. * @param flag defines the flag used to specify which material part must be marked as dirty
  28335. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28336. */
  28337. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28338. if (this.blockMaterialDirtyMechanism) {
  28339. return;
  28340. }
  28341. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28342. var material = _a[_i];
  28343. if (predicate && !predicate(material)) {
  28344. continue;
  28345. }
  28346. material.markAsDirty(flag);
  28347. }
  28348. };
  28349. /** @hidden */
  28350. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28351. var _this = this;
  28352. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28353. this._activeRequests.push(request);
  28354. request.onCompleteObservable.add(function (request) {
  28355. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28356. });
  28357. return request;
  28358. };
  28359. /** @hidden */
  28360. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28361. var _this = this;
  28362. return new Promise(function (resolve, reject) {
  28363. _this._loadFile(url, function (data) {
  28364. resolve(data);
  28365. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28366. reject(exception);
  28367. });
  28368. });
  28369. };
  28370. // Statics
  28371. Scene._uniqueIdCounter = 0;
  28372. /** The fog is deactivated */
  28373. Scene.FOGMODE_NONE = 0;
  28374. /** The fog density is following an exponential function */
  28375. Scene.FOGMODE_EXP = 1;
  28376. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  28377. Scene.FOGMODE_EXP2 = 2;
  28378. /** The fog density is following a linear function. */
  28379. Scene.FOGMODE_LINEAR = 3;
  28380. /**
  28381. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28382. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28383. */
  28384. Scene.MinDeltaTime = 1.0;
  28385. /**
  28386. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28387. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28388. */
  28389. Scene.MaxDeltaTime = 1000.0;
  28390. /** The distance in pixel that you have to move to prevent some events */
  28391. Scene.DragMovementThreshold = 10; // in pixels
  28392. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28393. Scene.LongPressDelay = 500; // in milliseconds
  28394. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28395. Scene.DoubleClickDelay = 300; // in milliseconds
  28396. /** If you need to check double click without raising a single click at first click, enable this flag */
  28397. Scene.ExclusiveDoubleClickMode = false;
  28398. return Scene;
  28399. }(BABYLON.AbstractScene));
  28400. BABYLON.Scene = Scene;
  28401. })(BABYLON || (BABYLON = {}));
  28402. //# sourceMappingURL=babylon.scene.js.map
  28403. var BABYLON;
  28404. (function (BABYLON) {
  28405. /**
  28406. * Set of assets to keep when moving a scene into an asset container.
  28407. */
  28408. var KeepAssets = /** @class */ (function (_super) {
  28409. __extends(KeepAssets, _super);
  28410. function KeepAssets() {
  28411. return _super !== null && _super.apply(this, arguments) || this;
  28412. }
  28413. return KeepAssets;
  28414. }(BABYLON.AbstractScene));
  28415. BABYLON.KeepAssets = KeepAssets;
  28416. /**
  28417. * Container with a set of assets that can be added or removed from a scene.
  28418. */
  28419. var AssetContainer = /** @class */ (function (_super) {
  28420. __extends(AssetContainer, _super);
  28421. /**
  28422. * Instantiates an AssetContainer.
  28423. * @param scene The scene the AssetContainer belongs to.
  28424. */
  28425. function AssetContainer(scene) {
  28426. var _this = _super.call(this) || this;
  28427. _this.scene = scene;
  28428. return _this;
  28429. }
  28430. /**
  28431. * Adds all the assets from the container to the scene.
  28432. */
  28433. AssetContainer.prototype.addAllToScene = function () {
  28434. var _this = this;
  28435. this.cameras.forEach(function (o) {
  28436. _this.scene.addCamera(o);
  28437. });
  28438. this.lights.forEach(function (o) {
  28439. _this.scene.addLight(o);
  28440. });
  28441. this.meshes.forEach(function (o) {
  28442. _this.scene.addMesh(o);
  28443. });
  28444. this.skeletons.forEach(function (o) {
  28445. _this.scene.addSkeleton(o);
  28446. });
  28447. this.animations.forEach(function (o) {
  28448. _this.scene.addAnimation(o);
  28449. });
  28450. this.animationGroups.forEach(function (o) {
  28451. _this.scene.addAnimationGroup(o);
  28452. });
  28453. this.multiMaterials.forEach(function (o) {
  28454. _this.scene.addMultiMaterial(o);
  28455. });
  28456. this.materials.forEach(function (o) {
  28457. _this.scene.addMaterial(o);
  28458. });
  28459. this.morphTargetManagers.forEach(function (o) {
  28460. _this.scene.addMorphTargetManager(o);
  28461. });
  28462. this.geometries.forEach(function (o) {
  28463. _this.scene.addGeometry(o);
  28464. });
  28465. this.transformNodes.forEach(function (o) {
  28466. _this.scene.addTransformNode(o);
  28467. });
  28468. this.actionManagers.forEach(function (o) {
  28469. _this.scene.addActionManager(o);
  28470. });
  28471. this.textures.forEach(function (o) {
  28472. _this.scene.addTexture(o);
  28473. });
  28474. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28475. var component = _a[_i];
  28476. component.addFromContainer(this.scene);
  28477. }
  28478. };
  28479. /**
  28480. * Removes all the assets in the container from the scene
  28481. */
  28482. AssetContainer.prototype.removeAllFromScene = function () {
  28483. var _this = this;
  28484. this.cameras.forEach(function (o) {
  28485. _this.scene.removeCamera(o);
  28486. });
  28487. this.lights.forEach(function (o) {
  28488. _this.scene.removeLight(o);
  28489. });
  28490. this.meshes.forEach(function (o) {
  28491. _this.scene.removeMesh(o);
  28492. });
  28493. this.skeletons.forEach(function (o) {
  28494. _this.scene.removeSkeleton(o);
  28495. });
  28496. this.animations.forEach(function (o) {
  28497. _this.scene.removeAnimation(o);
  28498. });
  28499. this.animationGroups.forEach(function (o) {
  28500. _this.scene.removeAnimationGroup(o);
  28501. });
  28502. this.multiMaterials.forEach(function (o) {
  28503. _this.scene.removeMultiMaterial(o);
  28504. });
  28505. this.materials.forEach(function (o) {
  28506. _this.scene.removeMaterial(o);
  28507. });
  28508. this.morphTargetManagers.forEach(function (o) {
  28509. _this.scene.removeMorphTargetManager(o);
  28510. });
  28511. this.geometries.forEach(function (o) {
  28512. _this.scene.removeGeometry(o);
  28513. });
  28514. this.transformNodes.forEach(function (o) {
  28515. _this.scene.removeTransformNode(o);
  28516. });
  28517. this.actionManagers.forEach(function (o) {
  28518. _this.scene.removeActionManager(o);
  28519. });
  28520. this.textures.forEach(function (o) {
  28521. _this.scene.removeTexture(o);
  28522. });
  28523. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28524. var component = _a[_i];
  28525. component.removeFromContainer(this.scene);
  28526. }
  28527. };
  28528. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28529. if (!sourceAssets) {
  28530. return;
  28531. }
  28532. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28533. var asset = sourceAssets_1[_i];
  28534. var move = true;
  28535. if (keepAssets) {
  28536. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28537. var keepAsset = keepAssets_1[_a];
  28538. if (asset === keepAsset) {
  28539. move = false;
  28540. break;
  28541. }
  28542. }
  28543. }
  28544. if (move) {
  28545. targetAssets.push(asset);
  28546. }
  28547. }
  28548. };
  28549. /**
  28550. * Removes all the assets contained in the scene and adds them to the container.
  28551. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28552. */
  28553. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28554. if (keepAssets === undefined) {
  28555. keepAssets = new KeepAssets();
  28556. }
  28557. for (var key in this) {
  28558. if (this.hasOwnProperty(key)) {
  28559. this[key] = this[key] || [];
  28560. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  28561. }
  28562. }
  28563. this.removeAllFromScene();
  28564. };
  28565. /**
  28566. * 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.
  28567. * @returns the root mesh
  28568. */
  28569. AssetContainer.prototype.createRootMesh = function () {
  28570. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  28571. this.meshes.forEach(function (m) {
  28572. if (!m.parent) {
  28573. rootMesh.addChild(m);
  28574. }
  28575. });
  28576. this.meshes.unshift(rootMesh);
  28577. return rootMesh;
  28578. };
  28579. return AssetContainer;
  28580. }(BABYLON.AbstractScene));
  28581. BABYLON.AssetContainer = AssetContainer;
  28582. })(BABYLON || (BABYLON = {}));
  28583. //# sourceMappingURL=babylon.assetContainer.js.map
  28584. var BABYLON;
  28585. (function (BABYLON) {
  28586. var Buffer = /** @class */ (function () {
  28587. /**
  28588. * Constructor
  28589. * @param engine the engine
  28590. * @param data the data to use for this buffer
  28591. * @param updatable whether the data is updatable
  28592. * @param stride the stride (optional)
  28593. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28594. * @param instanced whether the buffer is instanced (optional)
  28595. * @param useBytes set to true if the stride in in bytes (optional)
  28596. */
  28597. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28598. if (stride === void 0) { stride = 0; }
  28599. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28600. if (instanced === void 0) { instanced = false; }
  28601. if (useBytes === void 0) { useBytes = false; }
  28602. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28603. this._engine = engine.getScene().getEngine();
  28604. }
  28605. else {
  28606. this._engine = engine;
  28607. }
  28608. this._updatable = updatable;
  28609. this._instanced = instanced;
  28610. this._data = data;
  28611. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28612. if (!postponeInternalCreation) { // by default
  28613. this.create();
  28614. }
  28615. }
  28616. /**
  28617. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28618. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28619. * @param offset defines offset in the buffer (0 by default)
  28620. * @param size defines the size in floats of attributes (position is 3 for instance)
  28621. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28622. * @param instanced defines if the vertex buffer contains indexed data
  28623. * @param useBytes defines if the offset and stride are in bytes
  28624. * @returns the new vertex buffer
  28625. */
  28626. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28627. if (useBytes === void 0) { useBytes = false; }
  28628. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28629. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28630. // a lot of these parameters are ignored as they are overriden by the buffer
  28631. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28632. };
  28633. // Properties
  28634. Buffer.prototype.isUpdatable = function () {
  28635. return this._updatable;
  28636. };
  28637. Buffer.prototype.getData = function () {
  28638. return this._data;
  28639. };
  28640. Buffer.prototype.getBuffer = function () {
  28641. return this._buffer;
  28642. };
  28643. /**
  28644. * Gets the stride in float32 units (i.e. byte stride / 4).
  28645. * May not be an integer if the byte stride is not divisible by 4.
  28646. * DEPRECATED. Use byteStride instead.
  28647. * @returns the stride in float32 units
  28648. */
  28649. Buffer.prototype.getStrideSize = function () {
  28650. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  28651. };
  28652. // Methods
  28653. Buffer.prototype.create = function (data) {
  28654. if (data === void 0) { data = null; }
  28655. if (!data && this._buffer) {
  28656. return; // nothing to do
  28657. }
  28658. data = data || this._data;
  28659. if (!data) {
  28660. return;
  28661. }
  28662. if (!this._buffer) { // create buffer
  28663. if (this._updatable) {
  28664. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28665. this._data = data;
  28666. }
  28667. else {
  28668. this._buffer = this._engine.createVertexBuffer(data);
  28669. }
  28670. }
  28671. else if (this._updatable) { // update buffer
  28672. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28673. this._data = data;
  28674. }
  28675. };
  28676. /** @hidden */
  28677. Buffer.prototype._rebuild = function () {
  28678. this._buffer = null;
  28679. this.create(this._data);
  28680. };
  28681. Buffer.prototype.update = function (data) {
  28682. this.create(data);
  28683. };
  28684. /**
  28685. * Updates the data directly.
  28686. * @param data the new data
  28687. * @param offset the new offset
  28688. * @param vertexCount the vertex count (optional)
  28689. * @param useBytes set to true if the offset is in bytes
  28690. */
  28691. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28692. if (useBytes === void 0) { useBytes = false; }
  28693. if (!this._buffer) {
  28694. return;
  28695. }
  28696. if (this._updatable) { // update buffer
  28697. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  28698. this._data = null;
  28699. }
  28700. };
  28701. Buffer.prototype.dispose = function () {
  28702. if (!this._buffer) {
  28703. return;
  28704. }
  28705. if (this._engine._releaseBuffer(this._buffer)) {
  28706. this._buffer = null;
  28707. }
  28708. };
  28709. return Buffer;
  28710. }());
  28711. BABYLON.Buffer = Buffer;
  28712. })(BABYLON || (BABYLON = {}));
  28713. //# sourceMappingURL=babylon.buffer.js.map
  28714. var BABYLON;
  28715. (function (BABYLON) {
  28716. var VertexBuffer = /** @class */ (function () {
  28717. /**
  28718. * Constructor
  28719. * @param engine the engine
  28720. * @param data the data to use for this vertex buffer
  28721. * @param kind the vertex buffer kind
  28722. * @param updatable whether the data is updatable
  28723. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28724. * @param stride the stride (optional)
  28725. * @param instanced whether the buffer is instanced (optional)
  28726. * @param offset the offset of the data (optional)
  28727. * @param size the number of components (optional)
  28728. * @param type the type of the component (optional)
  28729. * @param normalized whether the data contains normalized data (optional)
  28730. * @param useBytes set to true if stride and offset are in bytes (optional)
  28731. */
  28732. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  28733. if (normalized === void 0) { normalized = false; }
  28734. if (useBytes === void 0) { useBytes = false; }
  28735. if (data instanceof BABYLON.Buffer) {
  28736. this._buffer = data;
  28737. this._ownsBuffer = false;
  28738. }
  28739. else {
  28740. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  28741. this._ownsBuffer = true;
  28742. }
  28743. this._kind = kind;
  28744. if (type == undefined) {
  28745. var data_1 = this.getData();
  28746. this.type = VertexBuffer.FLOAT;
  28747. if (data_1 instanceof Int8Array)
  28748. this.type = VertexBuffer.BYTE;
  28749. else if (data_1 instanceof Uint8Array)
  28750. this.type = VertexBuffer.UNSIGNED_BYTE;
  28751. else if (data_1 instanceof Int16Array)
  28752. this.type = VertexBuffer.SHORT;
  28753. else if (data_1 instanceof Uint16Array)
  28754. this.type = VertexBuffer.UNSIGNED_SHORT;
  28755. else if (data_1 instanceof Int32Array)
  28756. this.type = VertexBuffer.INT;
  28757. else if (data_1 instanceof Uint32Array)
  28758. this.type = VertexBuffer.UNSIGNED_INT;
  28759. }
  28760. else {
  28761. this.type = type;
  28762. }
  28763. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  28764. if (useBytes) {
  28765. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  28766. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  28767. this.byteOffset = offset || 0;
  28768. }
  28769. else {
  28770. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  28771. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  28772. this.byteOffset = (offset || 0) * typeByteLength;
  28773. }
  28774. this.normalized = normalized;
  28775. this._instanced = instanced !== undefined ? instanced : false;
  28776. this._instanceDivisor = instanced ? 1 : 0;
  28777. }
  28778. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  28779. /**
  28780. * Gets or sets the instance divisor when in instanced mode
  28781. */
  28782. get: function () {
  28783. return this._instanceDivisor;
  28784. },
  28785. set: function (value) {
  28786. this._instanceDivisor = value;
  28787. if (value == 0) {
  28788. this._instanced = false;
  28789. }
  28790. else {
  28791. this._instanced = true;
  28792. }
  28793. },
  28794. enumerable: true,
  28795. configurable: true
  28796. });
  28797. /** @hidden */
  28798. VertexBuffer.prototype._rebuild = function () {
  28799. if (!this._buffer) {
  28800. return;
  28801. }
  28802. this._buffer._rebuild();
  28803. };
  28804. /**
  28805. * Returns the kind of the VertexBuffer (string).
  28806. */
  28807. VertexBuffer.prototype.getKind = function () {
  28808. return this._kind;
  28809. };
  28810. // Properties
  28811. /**
  28812. * Boolean : is the VertexBuffer updatable ?
  28813. */
  28814. VertexBuffer.prototype.isUpdatable = function () {
  28815. return this._buffer.isUpdatable();
  28816. };
  28817. /**
  28818. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  28819. */
  28820. VertexBuffer.prototype.getData = function () {
  28821. return this._buffer.getData();
  28822. };
  28823. /**
  28824. * Returns the WebGLBuffer associated to the VertexBuffer.
  28825. */
  28826. VertexBuffer.prototype.getBuffer = function () {
  28827. return this._buffer.getBuffer();
  28828. };
  28829. /**
  28830. * Returns the stride as a multiple of the type byte length.
  28831. * DEPRECATED. Use byteStride instead.
  28832. */
  28833. VertexBuffer.prototype.getStrideSize = function () {
  28834. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  28835. };
  28836. /**
  28837. * Returns the offset as a multiple of the type byte length.
  28838. * DEPRECATED. Use byteOffset instead.
  28839. */
  28840. VertexBuffer.prototype.getOffset = function () {
  28841. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  28842. };
  28843. /**
  28844. * Returns the number of components per vertex attribute (integer).
  28845. */
  28846. VertexBuffer.prototype.getSize = function () {
  28847. return this._size;
  28848. };
  28849. /**
  28850. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  28851. */
  28852. VertexBuffer.prototype.getIsInstanced = function () {
  28853. return this._instanced;
  28854. };
  28855. /**
  28856. * Returns the instancing divisor, zero for non-instanced (integer).
  28857. */
  28858. VertexBuffer.prototype.getInstanceDivisor = function () {
  28859. return this._instanceDivisor;
  28860. };
  28861. // Methods
  28862. /**
  28863. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  28864. * Returns the created WebGLBuffer.
  28865. */
  28866. VertexBuffer.prototype.create = function (data) {
  28867. return this._buffer.create(data);
  28868. };
  28869. /**
  28870. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28871. * This function will create a new buffer if the current one is not updatable
  28872. * Returns the updated WebGLBuffer.
  28873. */
  28874. VertexBuffer.prototype.update = function (data) {
  28875. return this._buffer.update(data);
  28876. };
  28877. /**
  28878. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28879. * Returns the directly updated WebGLBuffer.
  28880. * @param data the new data
  28881. * @param offset the new offset
  28882. * @param useBytes set to true if the offset is in bytes
  28883. */
  28884. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  28885. if (useBytes === void 0) { useBytes = false; }
  28886. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  28887. };
  28888. /**
  28889. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  28890. */
  28891. VertexBuffer.prototype.dispose = function () {
  28892. if (this._ownsBuffer) {
  28893. this._buffer.dispose();
  28894. }
  28895. };
  28896. /**
  28897. * Enumerates each value of this vertex buffer as numbers.
  28898. * @param count the number of values to enumerate
  28899. * @param callback the callback function called for each value
  28900. */
  28901. VertexBuffer.prototype.forEach = function (count, callback) {
  28902. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  28903. };
  28904. Object.defineProperty(VertexBuffer, "PositionKind", {
  28905. get: function () {
  28906. return VertexBuffer._PositionKind;
  28907. },
  28908. enumerable: true,
  28909. configurable: true
  28910. });
  28911. Object.defineProperty(VertexBuffer, "NormalKind", {
  28912. get: function () {
  28913. return VertexBuffer._NormalKind;
  28914. },
  28915. enumerable: true,
  28916. configurable: true
  28917. });
  28918. Object.defineProperty(VertexBuffer, "TangentKind", {
  28919. get: function () {
  28920. return VertexBuffer._TangentKind;
  28921. },
  28922. enumerable: true,
  28923. configurable: true
  28924. });
  28925. Object.defineProperty(VertexBuffer, "UVKind", {
  28926. get: function () {
  28927. return VertexBuffer._UVKind;
  28928. },
  28929. enumerable: true,
  28930. configurable: true
  28931. });
  28932. Object.defineProperty(VertexBuffer, "UV2Kind", {
  28933. get: function () {
  28934. return VertexBuffer._UV2Kind;
  28935. },
  28936. enumerable: true,
  28937. configurable: true
  28938. });
  28939. Object.defineProperty(VertexBuffer, "UV3Kind", {
  28940. get: function () {
  28941. return VertexBuffer._UV3Kind;
  28942. },
  28943. enumerable: true,
  28944. configurable: true
  28945. });
  28946. Object.defineProperty(VertexBuffer, "UV4Kind", {
  28947. get: function () {
  28948. return VertexBuffer._UV4Kind;
  28949. },
  28950. enumerable: true,
  28951. configurable: true
  28952. });
  28953. Object.defineProperty(VertexBuffer, "UV5Kind", {
  28954. get: function () {
  28955. return VertexBuffer._UV5Kind;
  28956. },
  28957. enumerable: true,
  28958. configurable: true
  28959. });
  28960. Object.defineProperty(VertexBuffer, "UV6Kind", {
  28961. get: function () {
  28962. return VertexBuffer._UV6Kind;
  28963. },
  28964. enumerable: true,
  28965. configurable: true
  28966. });
  28967. Object.defineProperty(VertexBuffer, "ColorKind", {
  28968. get: function () {
  28969. return VertexBuffer._ColorKind;
  28970. },
  28971. enumerable: true,
  28972. configurable: true
  28973. });
  28974. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  28975. get: function () {
  28976. return VertexBuffer._MatricesIndicesKind;
  28977. },
  28978. enumerable: true,
  28979. configurable: true
  28980. });
  28981. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  28982. get: function () {
  28983. return VertexBuffer._MatricesWeightsKind;
  28984. },
  28985. enumerable: true,
  28986. configurable: true
  28987. });
  28988. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  28989. get: function () {
  28990. return VertexBuffer._MatricesIndicesExtraKind;
  28991. },
  28992. enumerable: true,
  28993. configurable: true
  28994. });
  28995. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  28996. get: function () {
  28997. return VertexBuffer._MatricesWeightsExtraKind;
  28998. },
  28999. enumerable: true,
  29000. configurable: true
  29001. });
  29002. /**
  29003. * Deduces the stride given a kind.
  29004. * @param kind The kind string to deduce
  29005. * @returns The deduced stride
  29006. */
  29007. VertexBuffer.DeduceStride = function (kind) {
  29008. switch (kind) {
  29009. case VertexBuffer.UVKind:
  29010. case VertexBuffer.UV2Kind:
  29011. case VertexBuffer.UV3Kind:
  29012. case VertexBuffer.UV4Kind:
  29013. case VertexBuffer.UV5Kind:
  29014. case VertexBuffer.UV6Kind:
  29015. return 2;
  29016. case VertexBuffer.NormalKind:
  29017. case VertexBuffer.PositionKind:
  29018. return 3;
  29019. case VertexBuffer.ColorKind:
  29020. case VertexBuffer.MatricesIndicesKind:
  29021. case VertexBuffer.MatricesIndicesExtraKind:
  29022. case VertexBuffer.MatricesWeightsKind:
  29023. case VertexBuffer.MatricesWeightsExtraKind:
  29024. case VertexBuffer.TangentKind:
  29025. return 4;
  29026. default:
  29027. throw new Error("Invalid kind '" + kind + "'");
  29028. }
  29029. };
  29030. /**
  29031. * Gets the byte length of the given type.
  29032. * @param type the type
  29033. * @returns the number of bytes
  29034. */
  29035. VertexBuffer.GetTypeByteLength = function (type) {
  29036. switch (type) {
  29037. case VertexBuffer.BYTE:
  29038. case VertexBuffer.UNSIGNED_BYTE:
  29039. return 1;
  29040. case VertexBuffer.SHORT:
  29041. case VertexBuffer.UNSIGNED_SHORT:
  29042. return 2;
  29043. case VertexBuffer.INT:
  29044. case VertexBuffer.FLOAT:
  29045. return 4;
  29046. default:
  29047. throw new Error("Invalid type '" + type + "'");
  29048. }
  29049. };
  29050. /**
  29051. * Enumerates each value of the given parameters as numbers.
  29052. * @param data the data to enumerate
  29053. * @param byteOffset the byte offset of the data
  29054. * @param byteStride the byte stride of the data
  29055. * @param componentCount the number of components per element
  29056. * @param componentType the type of the component
  29057. * @param count the total number of components
  29058. * @param normalized whether the data is normalized
  29059. * @param callback the callback function called for each value
  29060. */
  29061. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29062. if (data instanceof Array) {
  29063. var offset = byteOffset / 4;
  29064. var stride = byteStride / 4;
  29065. for (var index = 0; index < count; index += componentCount) {
  29066. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29067. callback(data[offset + componentIndex], index + componentIndex);
  29068. }
  29069. offset += stride;
  29070. }
  29071. }
  29072. else {
  29073. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29074. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29075. for (var index = 0; index < count; index += componentCount) {
  29076. var componentByteOffset = byteOffset;
  29077. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29078. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29079. callback(value, index + componentIndex);
  29080. componentByteOffset += componentByteLength;
  29081. }
  29082. byteOffset += byteStride;
  29083. }
  29084. }
  29085. };
  29086. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29087. switch (type) {
  29088. case VertexBuffer.BYTE: {
  29089. var value = dataView.getInt8(byteOffset);
  29090. if (normalized) {
  29091. value = Math.max(value / 127, -1);
  29092. }
  29093. return value;
  29094. }
  29095. case VertexBuffer.UNSIGNED_BYTE: {
  29096. var value = dataView.getUint8(byteOffset);
  29097. if (normalized) {
  29098. value = value / 255;
  29099. }
  29100. return value;
  29101. }
  29102. case VertexBuffer.SHORT: {
  29103. var value = dataView.getInt16(byteOffset, true);
  29104. if (normalized) {
  29105. value = Math.max(value / 16383, -1);
  29106. }
  29107. return value;
  29108. }
  29109. case VertexBuffer.UNSIGNED_SHORT: {
  29110. var value = dataView.getUint16(byteOffset, true);
  29111. if (normalized) {
  29112. value = value / 65535;
  29113. }
  29114. return value;
  29115. }
  29116. case VertexBuffer.FLOAT: {
  29117. return dataView.getFloat32(byteOffset, true);
  29118. }
  29119. default: {
  29120. throw new Error("Invalid component type " + type);
  29121. }
  29122. }
  29123. };
  29124. /**
  29125. * The byte type.
  29126. */
  29127. VertexBuffer.BYTE = 5120;
  29128. /**
  29129. * The unsigned byte type.
  29130. */
  29131. VertexBuffer.UNSIGNED_BYTE = 5121;
  29132. /**
  29133. * The short type.
  29134. */
  29135. VertexBuffer.SHORT = 5122;
  29136. /**
  29137. * The unsigned short type.
  29138. */
  29139. VertexBuffer.UNSIGNED_SHORT = 5123;
  29140. /**
  29141. * The integer type.
  29142. */
  29143. VertexBuffer.INT = 5124;
  29144. /**
  29145. * The unsigned integer type.
  29146. */
  29147. VertexBuffer.UNSIGNED_INT = 5125;
  29148. /**
  29149. * The float type.
  29150. */
  29151. VertexBuffer.FLOAT = 5126;
  29152. // Enums
  29153. VertexBuffer._PositionKind = "position";
  29154. VertexBuffer._NormalKind = "normal";
  29155. VertexBuffer._TangentKind = "tangent";
  29156. VertexBuffer._UVKind = "uv";
  29157. VertexBuffer._UV2Kind = "uv2";
  29158. VertexBuffer._UV3Kind = "uv3";
  29159. VertexBuffer._UV4Kind = "uv4";
  29160. VertexBuffer._UV5Kind = "uv5";
  29161. VertexBuffer._UV6Kind = "uv6";
  29162. VertexBuffer._ColorKind = "color";
  29163. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29164. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29165. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29166. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29167. return VertexBuffer;
  29168. }());
  29169. BABYLON.VertexBuffer = VertexBuffer;
  29170. })(BABYLON || (BABYLON = {}));
  29171. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29172. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29173. var BABYLON;
  29174. (function (BABYLON) {
  29175. /**
  29176. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29177. */
  29178. var DummyInternalTextureTracker = /** @class */ (function () {
  29179. function DummyInternalTextureTracker() {
  29180. /**
  29181. * Gets or set the previous tracker in the list
  29182. */
  29183. this.previous = null;
  29184. /**
  29185. * Gets or set the next tracker in the list
  29186. */
  29187. this.next = null;
  29188. }
  29189. return DummyInternalTextureTracker;
  29190. }());
  29191. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29192. })(BABYLON || (BABYLON = {}));
  29193. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29194. var BABYLON;
  29195. (function (BABYLON) {
  29196. /**
  29197. * Class used to store data associated with WebGL texture data for the engine
  29198. * This class should not be used directly
  29199. */
  29200. var InternalTexture = /** @class */ (function () {
  29201. /**
  29202. * Creates a new InternalTexture
  29203. * @param engine defines the engine to use
  29204. * @param dataSource defines the type of data that will be used
  29205. */
  29206. function InternalTexture(engine, dataSource) {
  29207. /**
  29208. * Observable called when the texture is loaded
  29209. */
  29210. this.onLoadedObservable = new BABYLON.Observable();
  29211. /**
  29212. * Gets or set the previous tracker in the list
  29213. */
  29214. this.previous = null;
  29215. /**
  29216. * Gets or set the next tracker in the list
  29217. */
  29218. this.next = null;
  29219. // Private
  29220. /** @hidden */
  29221. this._initialSlot = -1;
  29222. /** @hidden */
  29223. this._designatedSlot = -1;
  29224. /** @hidden */
  29225. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29226. /** @hidden */
  29227. this._comparisonFunction = 0;
  29228. /** @hidden */
  29229. this._sphericalPolynomial = null;
  29230. /** @hidden */
  29231. this._lodGenerationScale = 0;
  29232. /** @hidden */
  29233. this._lodGenerationOffset = 0;
  29234. /** @hidden */
  29235. this._isRGBD = false;
  29236. /** @hidden */
  29237. this._references = 1;
  29238. this._engine = engine;
  29239. this._dataSource = dataSource;
  29240. this._webGLTexture = engine._createTexture();
  29241. }
  29242. /**
  29243. * Gets the Engine the texture belongs to.
  29244. * @returns The babylon engine
  29245. */
  29246. InternalTexture.prototype.getEngine = function () {
  29247. return this._engine;
  29248. };
  29249. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29250. /**
  29251. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29252. */
  29253. get: function () {
  29254. return this._dataSource;
  29255. },
  29256. enumerable: true,
  29257. configurable: true
  29258. });
  29259. /**
  29260. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29261. */
  29262. InternalTexture.prototype.incrementReferences = function () {
  29263. this._references++;
  29264. };
  29265. /**
  29266. * Change the size of the texture (not the size of the content)
  29267. * @param width defines the new width
  29268. * @param height defines the new height
  29269. * @param depth defines the new depth (1 by default)
  29270. */
  29271. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29272. if (depth === void 0) { depth = 1; }
  29273. this.width = width;
  29274. this.height = height;
  29275. this.depth = depth;
  29276. this.baseWidth = width;
  29277. this.baseHeight = height;
  29278. this.baseDepth = depth;
  29279. this._size = width * height * depth;
  29280. };
  29281. /** @hidden */
  29282. InternalTexture.prototype._rebuild = function () {
  29283. var _this = this;
  29284. var proxy;
  29285. this.isReady = false;
  29286. this._cachedCoordinatesMode = null;
  29287. this._cachedWrapU = null;
  29288. this._cachedWrapV = null;
  29289. this._cachedAnisotropicFilteringLevel = null;
  29290. switch (this._dataSource) {
  29291. case InternalTexture.DATASOURCE_TEMP:
  29292. return;
  29293. case InternalTexture.DATASOURCE_URL:
  29294. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29295. _this.isReady = true;
  29296. }, null, this._buffer, undefined, this.format);
  29297. proxy._swapAndDie(this);
  29298. return;
  29299. case InternalTexture.DATASOURCE_RAW:
  29300. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29301. proxy._swapAndDie(this);
  29302. this.isReady = true;
  29303. return;
  29304. case InternalTexture.DATASOURCE_RAW3D:
  29305. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29306. proxy._swapAndDie(this);
  29307. this.isReady = true;
  29308. return;
  29309. case InternalTexture.DATASOURCE_DYNAMIC:
  29310. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29311. proxy._swapAndDie(this);
  29312. // The engine will make sure to update content so no need to flag it as isReady = true
  29313. return;
  29314. case InternalTexture.DATASOURCE_RENDERTARGET:
  29315. var options = new BABYLON.RenderTargetCreationOptions();
  29316. options.generateDepthBuffer = this._generateDepthBuffer;
  29317. options.generateMipMaps = this.generateMipMaps;
  29318. options.generateStencilBuffer = this._generateStencilBuffer;
  29319. options.samplingMode = this.samplingMode;
  29320. options.type = this.type;
  29321. if (this.isCube) {
  29322. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29323. }
  29324. else {
  29325. var size = {
  29326. width: this.width,
  29327. height: this.height
  29328. };
  29329. proxy = this._engine.createRenderTargetTexture(size, options);
  29330. }
  29331. proxy._swapAndDie(this);
  29332. this.isReady = true;
  29333. return;
  29334. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29335. var depthTextureOptions = {
  29336. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29337. comparisonFunction: this._comparisonFunction,
  29338. generateStencil: this._generateStencilBuffer,
  29339. isCube: this.isCube
  29340. };
  29341. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29342. proxy._swapAndDie(this);
  29343. this.isReady = true;
  29344. return;
  29345. case InternalTexture.DATASOURCE_CUBE:
  29346. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29347. _this.isReady = true;
  29348. }, null, this.format, this._extension);
  29349. proxy._swapAndDie(this);
  29350. return;
  29351. case InternalTexture.DATASOURCE_CUBERAW:
  29352. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29353. proxy._swapAndDie(this);
  29354. this.isReady = true;
  29355. return;
  29356. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29357. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29358. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29359. _this.isReady = true;
  29360. });
  29361. proxy._swapAndDie(this);
  29362. return;
  29363. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29364. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29365. if (proxy) {
  29366. proxy._swapAndDie(_this);
  29367. }
  29368. _this.isReady = true;
  29369. }, null, this.format, this._extension);
  29370. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29371. return;
  29372. }
  29373. };
  29374. /** @hidden */
  29375. InternalTexture.prototype._swapAndDie = function (target) {
  29376. target._webGLTexture = this._webGLTexture;
  29377. if (this._framebuffer) {
  29378. target._framebuffer = this._framebuffer;
  29379. }
  29380. if (this._depthStencilBuffer) {
  29381. target._depthStencilBuffer = this._depthStencilBuffer;
  29382. }
  29383. if (this._lodTextureHigh) {
  29384. if (target._lodTextureHigh) {
  29385. target._lodTextureHigh.dispose();
  29386. }
  29387. target._lodTextureHigh = this._lodTextureHigh;
  29388. }
  29389. if (this._lodTextureMid) {
  29390. if (target._lodTextureMid) {
  29391. target._lodTextureMid.dispose();
  29392. }
  29393. target._lodTextureMid = this._lodTextureMid;
  29394. }
  29395. if (this._lodTextureLow) {
  29396. if (target._lodTextureLow) {
  29397. target._lodTextureLow.dispose();
  29398. }
  29399. target._lodTextureLow = this._lodTextureLow;
  29400. }
  29401. var cache = this._engine.getLoadedTexturesCache();
  29402. var index = cache.indexOf(this);
  29403. if (index !== -1) {
  29404. cache.splice(index, 1);
  29405. }
  29406. };
  29407. /**
  29408. * Dispose the current allocated resources
  29409. */
  29410. InternalTexture.prototype.dispose = function () {
  29411. if (!this._webGLTexture) {
  29412. return;
  29413. }
  29414. this._references--;
  29415. if (this._references === 0) {
  29416. this._engine._releaseTexture(this);
  29417. this._webGLTexture = null;
  29418. this.previous = null;
  29419. this.next = null;
  29420. }
  29421. };
  29422. /**
  29423. * The source of the texture data is unknown
  29424. */
  29425. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29426. /**
  29427. * Texture data comes from an URL
  29428. */
  29429. InternalTexture.DATASOURCE_URL = 1;
  29430. /**
  29431. * Texture data is only used for temporary storage
  29432. */
  29433. InternalTexture.DATASOURCE_TEMP = 2;
  29434. /**
  29435. * Texture data comes from raw data (ArrayBuffer)
  29436. */
  29437. InternalTexture.DATASOURCE_RAW = 3;
  29438. /**
  29439. * Texture content is dynamic (video or dynamic texture)
  29440. */
  29441. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29442. /**
  29443. * Texture content is generated by rendering to it
  29444. */
  29445. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29446. /**
  29447. * Texture content is part of a multi render target process
  29448. */
  29449. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29450. /**
  29451. * Texture data comes from a cube data file
  29452. */
  29453. InternalTexture.DATASOURCE_CUBE = 7;
  29454. /**
  29455. * Texture data comes from a raw cube data
  29456. */
  29457. InternalTexture.DATASOURCE_CUBERAW = 8;
  29458. /**
  29459. * Texture data come from a prefiltered cube data file
  29460. */
  29461. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29462. /**
  29463. * Texture content is raw 3D data
  29464. */
  29465. InternalTexture.DATASOURCE_RAW3D = 10;
  29466. /**
  29467. * Texture content is a depth texture
  29468. */
  29469. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29470. /**
  29471. * Texture data comes from a raw cube data encoded with RGBD
  29472. */
  29473. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29474. return InternalTexture;
  29475. }());
  29476. BABYLON.InternalTexture = InternalTexture;
  29477. })(BABYLON || (BABYLON = {}));
  29478. //# sourceMappingURL=babylon.internalTexture.js.map
  29479. var BABYLON;
  29480. (function (BABYLON) {
  29481. var BaseTexture = /** @class */ (function () {
  29482. function BaseTexture(scene) {
  29483. this._hasAlpha = false;
  29484. this.getAlphaFromRGB = false;
  29485. this.level = 1;
  29486. this.coordinatesIndex = 0;
  29487. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29488. /**
  29489. * | Value | Type | Description |
  29490. * | ----- | ------------------ | ----------- |
  29491. * | 0 | CLAMP_ADDRESSMODE | |
  29492. * | 1 | WRAP_ADDRESSMODE | |
  29493. * | 2 | MIRROR_ADDRESSMODE | |
  29494. */
  29495. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29496. /**
  29497. * | Value | Type | Description |
  29498. * | ----- | ------------------ | ----------- |
  29499. * | 0 | CLAMP_ADDRESSMODE | |
  29500. * | 1 | WRAP_ADDRESSMODE | |
  29501. * | 2 | MIRROR_ADDRESSMODE | |
  29502. */
  29503. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29504. /**
  29505. * | Value | Type | Description |
  29506. * | ----- | ------------------ | ----------- |
  29507. * | 0 | CLAMP_ADDRESSMODE | |
  29508. * | 1 | WRAP_ADDRESSMODE | |
  29509. * | 2 | MIRROR_ADDRESSMODE | |
  29510. */
  29511. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29512. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29513. this.isCube = false;
  29514. this.is3D = false;
  29515. this.gammaSpace = true;
  29516. this.invertZ = false;
  29517. this.lodLevelInAlpha = false;
  29518. this.isRenderTarget = false;
  29519. this.animations = new Array();
  29520. /**
  29521. * An event triggered when the texture is disposed.
  29522. */
  29523. this.onDisposeObservable = new BABYLON.Observable();
  29524. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29525. this._cachedSize = BABYLON.Size.Zero();
  29526. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29527. if (this._scene) {
  29528. this._scene.textures.push(this);
  29529. }
  29530. this._uid = null;
  29531. }
  29532. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29533. get: function () {
  29534. return this._hasAlpha;
  29535. },
  29536. set: function (value) {
  29537. if (this._hasAlpha === value) {
  29538. return;
  29539. }
  29540. this._hasAlpha = value;
  29541. if (this._scene) {
  29542. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29543. }
  29544. },
  29545. enumerable: true,
  29546. configurable: true
  29547. });
  29548. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29549. get: function () {
  29550. return this._coordinatesMode;
  29551. },
  29552. /**
  29553. * How a texture is mapped.
  29554. *
  29555. * | Value | Type | Description |
  29556. * | ----- | ----------------------------------- | ----------- |
  29557. * | 0 | EXPLICIT_MODE | |
  29558. * | 1 | SPHERICAL_MODE | |
  29559. * | 2 | PLANAR_MODE | |
  29560. * | 3 | CUBIC_MODE | |
  29561. * | 4 | PROJECTION_MODE | |
  29562. * | 5 | SKYBOX_MODE | |
  29563. * | 6 | INVCUBIC_MODE | |
  29564. * | 7 | EQUIRECTANGULAR_MODE | |
  29565. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29566. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29567. */
  29568. set: function (value) {
  29569. if (this._coordinatesMode === value) {
  29570. return;
  29571. }
  29572. this._coordinatesMode = value;
  29573. if (this._scene) {
  29574. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29575. }
  29576. },
  29577. enumerable: true,
  29578. configurable: true
  29579. });
  29580. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  29581. /**
  29582. * Gets whether or not the texture contains RGBD data.
  29583. */
  29584. get: function () {
  29585. return this._texture != null && this._texture._isRGBD;
  29586. },
  29587. enumerable: true,
  29588. configurable: true
  29589. });
  29590. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  29591. get: function () {
  29592. if (this._texture)
  29593. return this._texture._lodGenerationOffset;
  29594. return 0.0;
  29595. },
  29596. set: function (value) {
  29597. if (this._texture)
  29598. this._texture._lodGenerationOffset = value;
  29599. },
  29600. enumerable: true,
  29601. configurable: true
  29602. });
  29603. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  29604. get: function () {
  29605. if (this._texture)
  29606. return this._texture._lodGenerationScale;
  29607. return 0.0;
  29608. },
  29609. set: function (value) {
  29610. if (this._texture)
  29611. this._texture._lodGenerationScale = value;
  29612. },
  29613. enumerable: true,
  29614. configurable: true
  29615. });
  29616. Object.defineProperty(BaseTexture.prototype, "uid", {
  29617. get: function () {
  29618. if (!this._uid) {
  29619. this._uid = BABYLON.Tools.RandomId();
  29620. }
  29621. return this._uid;
  29622. },
  29623. enumerable: true,
  29624. configurable: true
  29625. });
  29626. BaseTexture.prototype.toString = function () {
  29627. return this.name;
  29628. };
  29629. BaseTexture.prototype.getClassName = function () {
  29630. return "BaseTexture";
  29631. };
  29632. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29633. set: function (callback) {
  29634. if (this._onDisposeObserver) {
  29635. this.onDisposeObservable.remove(this._onDisposeObserver);
  29636. }
  29637. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29638. },
  29639. enumerable: true,
  29640. configurable: true
  29641. });
  29642. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29643. get: function () {
  29644. return true;
  29645. },
  29646. enumerable: true,
  29647. configurable: true
  29648. });
  29649. BaseTexture.prototype.getScene = function () {
  29650. return this._scene;
  29651. };
  29652. BaseTexture.prototype.getTextureMatrix = function () {
  29653. return BABYLON.Matrix.IdentityReadOnly;
  29654. };
  29655. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29656. return BABYLON.Matrix.IdentityReadOnly;
  29657. };
  29658. BaseTexture.prototype.getInternalTexture = function () {
  29659. return this._texture;
  29660. };
  29661. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29662. return !this.isBlocking || this.isReady();
  29663. };
  29664. BaseTexture.prototype.isReady = function () {
  29665. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29666. this.delayLoad();
  29667. return false;
  29668. }
  29669. if (this._texture) {
  29670. return this._texture.isReady;
  29671. }
  29672. return false;
  29673. };
  29674. BaseTexture.prototype.getSize = function () {
  29675. if (this._texture) {
  29676. if (this._texture.width) {
  29677. this._cachedSize.width = this._texture.width;
  29678. this._cachedSize.height = this._texture.height;
  29679. return this._cachedSize;
  29680. }
  29681. if (this._texture._size) {
  29682. this._cachedSize.width = this._texture._size;
  29683. this._cachedSize.height = this._texture._size;
  29684. return this._cachedSize;
  29685. }
  29686. }
  29687. return this._cachedSize;
  29688. };
  29689. BaseTexture.prototype.getBaseSize = function () {
  29690. if (!this.isReady() || !this._texture)
  29691. return BABYLON.Size.Zero();
  29692. if (this._texture._size) {
  29693. return new BABYLON.Size(this._texture._size, this._texture._size);
  29694. }
  29695. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29696. };
  29697. BaseTexture.prototype.scale = function (ratio) {
  29698. };
  29699. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29700. get: function () {
  29701. return false;
  29702. },
  29703. enumerable: true,
  29704. configurable: true
  29705. });
  29706. /** @hidden */
  29707. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29708. if (!this._scene) {
  29709. return null;
  29710. }
  29711. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  29712. for (var index = 0; index < texturesCache.length; index++) {
  29713. var texturesCacheEntry = texturesCache[index];
  29714. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  29715. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  29716. texturesCacheEntry.incrementReferences();
  29717. return texturesCacheEntry;
  29718. }
  29719. }
  29720. }
  29721. return null;
  29722. };
  29723. /** @hidden */
  29724. BaseTexture.prototype._rebuild = function () {
  29725. };
  29726. BaseTexture.prototype.delayLoad = function () {
  29727. };
  29728. BaseTexture.prototype.clone = function () {
  29729. return null;
  29730. };
  29731. Object.defineProperty(BaseTexture.prototype, "textureType", {
  29732. get: function () {
  29733. if (!this._texture) {
  29734. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29735. }
  29736. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29737. },
  29738. enumerable: true,
  29739. configurable: true
  29740. });
  29741. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  29742. get: function () {
  29743. if (!this._texture) {
  29744. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29745. }
  29746. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29747. },
  29748. enumerable: true,
  29749. configurable: true
  29750. });
  29751. /**
  29752. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  29753. * This will returns an RGBA array buffer containing either in values (0-255) or
  29754. * float values (0-1) depending of the underlying buffer type.
  29755. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  29756. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  29757. * @param buffer defines a user defined buffer to fill with data (can be null)
  29758. * @returns The Array buffer containing the pixels data.
  29759. */
  29760. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  29761. if (faceIndex === void 0) { faceIndex = 0; }
  29762. if (level === void 0) { level = 0; }
  29763. if (buffer === void 0) { buffer = null; }
  29764. if (!this._texture) {
  29765. return null;
  29766. }
  29767. var size = this.getSize();
  29768. var width = size.width;
  29769. var height = size.height;
  29770. var scene = this.getScene();
  29771. if (!scene) {
  29772. return null;
  29773. }
  29774. var engine = scene.getEngine();
  29775. if (level != 0) {
  29776. width = width / Math.pow(2, level);
  29777. height = height / Math.pow(2, level);
  29778. width = Math.round(width);
  29779. height = Math.round(height);
  29780. }
  29781. if (this._texture.isCube) {
  29782. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  29783. }
  29784. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  29785. };
  29786. BaseTexture.prototype.releaseInternalTexture = function () {
  29787. if (this._texture) {
  29788. this._texture.dispose();
  29789. this._texture = null;
  29790. }
  29791. };
  29792. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  29793. get: function () {
  29794. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  29795. return null;
  29796. }
  29797. if (!this._texture._sphericalPolynomial) {
  29798. this._texture._sphericalPolynomial =
  29799. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  29800. }
  29801. return this._texture._sphericalPolynomial;
  29802. },
  29803. set: function (value) {
  29804. if (this._texture) {
  29805. this._texture._sphericalPolynomial = value;
  29806. }
  29807. },
  29808. enumerable: true,
  29809. configurable: true
  29810. });
  29811. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  29812. get: function () {
  29813. if (this._texture) {
  29814. return this._texture._lodTextureHigh;
  29815. }
  29816. return null;
  29817. },
  29818. enumerable: true,
  29819. configurable: true
  29820. });
  29821. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  29822. get: function () {
  29823. if (this._texture) {
  29824. return this._texture._lodTextureMid;
  29825. }
  29826. return null;
  29827. },
  29828. enumerable: true,
  29829. configurable: true
  29830. });
  29831. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  29832. get: function () {
  29833. if (this._texture) {
  29834. return this._texture._lodTextureLow;
  29835. }
  29836. return null;
  29837. },
  29838. enumerable: true,
  29839. configurable: true
  29840. });
  29841. BaseTexture.prototype.dispose = function () {
  29842. if (!this._scene) {
  29843. return;
  29844. }
  29845. // Animations
  29846. this._scene.stopAnimation(this);
  29847. // Remove from scene
  29848. this._scene._removePendingData(this);
  29849. var index = this._scene.textures.indexOf(this);
  29850. if (index >= 0) {
  29851. this._scene.textures.splice(index, 1);
  29852. }
  29853. if (this._texture === undefined) {
  29854. return;
  29855. }
  29856. // Release
  29857. this.releaseInternalTexture();
  29858. // Callback
  29859. this.onDisposeObservable.notifyObservers(this);
  29860. this.onDisposeObservable.clear();
  29861. };
  29862. BaseTexture.prototype.serialize = function () {
  29863. if (!this.name) {
  29864. return null;
  29865. }
  29866. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29867. // Animations
  29868. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29869. return serializationObject;
  29870. };
  29871. BaseTexture.WhenAllReady = function (textures, callback) {
  29872. var numRemaining = textures.length;
  29873. if (numRemaining === 0) {
  29874. callback();
  29875. return;
  29876. }
  29877. var _loop_1 = function () {
  29878. texture = textures[i];
  29879. if (texture.isReady()) {
  29880. if (--numRemaining === 0) {
  29881. callback();
  29882. }
  29883. }
  29884. else {
  29885. onLoadObservable = texture.onLoadObservable;
  29886. var onLoadCallback_1 = function () {
  29887. onLoadObservable.removeCallback(onLoadCallback_1);
  29888. if (--numRemaining === 0) {
  29889. callback();
  29890. }
  29891. };
  29892. onLoadObservable.add(onLoadCallback_1);
  29893. }
  29894. };
  29895. var texture, onLoadObservable;
  29896. for (var i = 0; i < textures.length; i++) {
  29897. _loop_1();
  29898. }
  29899. };
  29900. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  29901. __decorate([
  29902. BABYLON.serialize()
  29903. ], BaseTexture.prototype, "name", void 0);
  29904. __decorate([
  29905. BABYLON.serialize("hasAlpha")
  29906. ], BaseTexture.prototype, "_hasAlpha", void 0);
  29907. __decorate([
  29908. BABYLON.serialize()
  29909. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  29910. __decorate([
  29911. BABYLON.serialize()
  29912. ], BaseTexture.prototype, "level", void 0);
  29913. __decorate([
  29914. BABYLON.serialize()
  29915. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  29916. __decorate([
  29917. BABYLON.serialize("coordinatesMode")
  29918. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  29919. __decorate([
  29920. BABYLON.serialize()
  29921. ], BaseTexture.prototype, "wrapU", void 0);
  29922. __decorate([
  29923. BABYLON.serialize()
  29924. ], BaseTexture.prototype, "wrapV", void 0);
  29925. __decorate([
  29926. BABYLON.serialize()
  29927. ], BaseTexture.prototype, "wrapR", void 0);
  29928. __decorate([
  29929. BABYLON.serialize()
  29930. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  29931. __decorate([
  29932. BABYLON.serialize()
  29933. ], BaseTexture.prototype, "isCube", void 0);
  29934. __decorate([
  29935. BABYLON.serialize()
  29936. ], BaseTexture.prototype, "is3D", void 0);
  29937. __decorate([
  29938. BABYLON.serialize()
  29939. ], BaseTexture.prototype, "gammaSpace", void 0);
  29940. __decorate([
  29941. BABYLON.serialize()
  29942. ], BaseTexture.prototype, "invertZ", void 0);
  29943. __decorate([
  29944. BABYLON.serialize()
  29945. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  29946. __decorate([
  29947. BABYLON.serialize()
  29948. ], BaseTexture.prototype, "lodGenerationOffset", null);
  29949. __decorate([
  29950. BABYLON.serialize()
  29951. ], BaseTexture.prototype, "lodGenerationScale", null);
  29952. __decorate([
  29953. BABYLON.serialize()
  29954. ], BaseTexture.prototype, "isRenderTarget", void 0);
  29955. return BaseTexture;
  29956. }());
  29957. BABYLON.BaseTexture = BaseTexture;
  29958. })(BABYLON || (BABYLON = {}));
  29959. //# sourceMappingURL=babylon.baseTexture.js.map
  29960. var BABYLON;
  29961. (function (BABYLON) {
  29962. var Texture = /** @class */ (function (_super) {
  29963. __extends(Texture, _super);
  29964. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  29965. if (noMipmap === void 0) { noMipmap = false; }
  29966. if (invertY === void 0) { invertY = true; }
  29967. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  29968. if (onLoad === void 0) { onLoad = null; }
  29969. if (onError === void 0) { onError = null; }
  29970. if (buffer === void 0) { buffer = null; }
  29971. if (deleteBuffer === void 0) { deleteBuffer = false; }
  29972. var _this = _super.call(this, scene) || this;
  29973. _this.uOffset = 0;
  29974. _this.vOffset = 0;
  29975. _this.uScale = 1.0;
  29976. _this.vScale = 1.0;
  29977. _this.uAng = 0;
  29978. _this.vAng = 0;
  29979. _this.wAng = 0;
  29980. /**
  29981. * Defines the center of rotation (U)
  29982. */
  29983. _this.uRotationCenter = 0.5;
  29984. /**
  29985. * Defines the center of rotation (V)
  29986. */
  29987. _this.vRotationCenter = 0.5;
  29988. /**
  29989. * Defines the center of rotation (W)
  29990. */
  29991. _this.wRotationCenter = 0.5;
  29992. _this._isBlocking = true;
  29993. _this.name = url || "";
  29994. _this.url = url;
  29995. _this._noMipmap = noMipmap;
  29996. _this._invertY = invertY;
  29997. _this._samplingMode = samplingMode;
  29998. _this._buffer = buffer;
  29999. _this._deleteBuffer = deleteBuffer;
  30000. if (format) {
  30001. _this._format = format;
  30002. }
  30003. scene = _this.getScene();
  30004. if (!scene) {
  30005. return _this;
  30006. }
  30007. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30008. var load = function () {
  30009. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30010. _this.onLoadObservable.notifyObservers(_this);
  30011. }
  30012. if (onLoad) {
  30013. onLoad();
  30014. }
  30015. if (!_this.isBlocking && scene) {
  30016. scene.resetCachedMaterial();
  30017. }
  30018. };
  30019. if (!_this.url) {
  30020. _this._delayedOnLoad = load;
  30021. _this._delayedOnError = onError;
  30022. return _this;
  30023. }
  30024. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30025. if (!_this._texture) {
  30026. if (!scene.useDelayedTextureLoading) {
  30027. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30028. if (deleteBuffer) {
  30029. delete _this._buffer;
  30030. }
  30031. }
  30032. else {
  30033. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30034. _this._delayedOnLoad = load;
  30035. _this._delayedOnError = onError;
  30036. }
  30037. }
  30038. else {
  30039. if (_this._texture.isReady) {
  30040. BABYLON.Tools.SetImmediate(function () { return load(); });
  30041. }
  30042. else {
  30043. _this._texture.onLoadedObservable.add(load);
  30044. }
  30045. }
  30046. return _this;
  30047. }
  30048. Object.defineProperty(Texture.prototype, "noMipmap", {
  30049. get: function () {
  30050. return this._noMipmap;
  30051. },
  30052. enumerable: true,
  30053. configurable: true
  30054. });
  30055. Object.defineProperty(Texture.prototype, "isBlocking", {
  30056. get: function () {
  30057. return this._isBlocking;
  30058. },
  30059. set: function (value) {
  30060. this._isBlocking = value;
  30061. },
  30062. enumerable: true,
  30063. configurable: true
  30064. });
  30065. Object.defineProperty(Texture.prototype, "samplingMode", {
  30066. get: function () {
  30067. return this._samplingMode;
  30068. },
  30069. enumerable: true,
  30070. configurable: true
  30071. });
  30072. /**
  30073. * Update the url (and optional buffer) of this texture if url was null during construction.
  30074. * @param url the url of the texture
  30075. * @param buffer the buffer of the texture (defaults to null)
  30076. */
  30077. Texture.prototype.updateURL = function (url, buffer) {
  30078. if (buffer === void 0) { buffer = null; }
  30079. if (this.url) {
  30080. throw new Error("URL is already set");
  30081. }
  30082. this.url = url;
  30083. this._buffer = buffer;
  30084. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30085. this.delayLoad();
  30086. };
  30087. Texture.prototype.delayLoad = function () {
  30088. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30089. return;
  30090. }
  30091. var scene = this.getScene();
  30092. if (!scene) {
  30093. return;
  30094. }
  30095. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30096. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30097. if (!this._texture) {
  30098. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30099. if (this._deleteBuffer) {
  30100. delete this._buffer;
  30101. }
  30102. }
  30103. else {
  30104. if (this._delayedOnLoad) {
  30105. if (this._texture.isReady) {
  30106. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30107. }
  30108. else {
  30109. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30110. }
  30111. }
  30112. }
  30113. this._delayedOnLoad = null;
  30114. this._delayedOnError = null;
  30115. };
  30116. /**
  30117. * Default is Trilinear mode.
  30118. *
  30119. * | Value | Type | Description |
  30120. * | ----- | ------------------ | ----------- |
  30121. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30122. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30123. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30124. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30125. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30126. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30127. * | 7 | NEAREST_LINEAR | |
  30128. * | 8 | NEAREST_NEAREST | |
  30129. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30130. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30131. * | 11 | LINEAR_LINEAR | |
  30132. * | 12 | LINEAR_NEAREST | |
  30133. *
  30134. * > _mag_: magnification filter (close to the viewer)
  30135. * > _min_: minification filter (far from the viewer)
  30136. * > _mip_: filter used between mip map levels
  30137. *
  30138. */
  30139. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30140. if (!this._texture) {
  30141. return;
  30142. }
  30143. var scene = this.getScene();
  30144. if (!scene) {
  30145. return;
  30146. }
  30147. this._samplingMode = samplingMode;
  30148. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30149. };
  30150. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30151. x *= this.uScale;
  30152. y *= this.vScale;
  30153. x -= this.uRotationCenter * this.uScale;
  30154. y -= this.vRotationCenter * this.vScale;
  30155. z -= this.wRotationCenter;
  30156. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30157. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30158. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30159. t.z += this.wRotationCenter;
  30160. };
  30161. Texture.prototype.getTextureMatrix = function () {
  30162. var _this = this;
  30163. if (this.uOffset === this._cachedUOffset &&
  30164. this.vOffset === this._cachedVOffset &&
  30165. this.uScale === this._cachedUScale &&
  30166. this.vScale === this._cachedVScale &&
  30167. this.uAng === this._cachedUAng &&
  30168. this.vAng === this._cachedVAng &&
  30169. this.wAng === this._cachedWAng) {
  30170. return this._cachedTextureMatrix;
  30171. }
  30172. this._cachedUOffset = this.uOffset;
  30173. this._cachedVOffset = this.vOffset;
  30174. this._cachedUScale = this.uScale;
  30175. this._cachedVScale = this.vScale;
  30176. this._cachedUAng = this.uAng;
  30177. this._cachedVAng = this.vAng;
  30178. this._cachedWAng = this.wAng;
  30179. if (!this._cachedTextureMatrix) {
  30180. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30181. this._rowGenerationMatrix = new BABYLON.Matrix();
  30182. this._t0 = BABYLON.Vector3.Zero();
  30183. this._t1 = BABYLON.Vector3.Zero();
  30184. this._t2 = BABYLON.Vector3.Zero();
  30185. }
  30186. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30187. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30188. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30189. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30190. this._t1.subtractInPlace(this._t0);
  30191. this._t2.subtractInPlace(this._t0);
  30192. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30193. this._cachedTextureMatrix.m[0] = this._t1.x;
  30194. this._cachedTextureMatrix.m[1] = this._t1.y;
  30195. this._cachedTextureMatrix.m[2] = this._t1.z;
  30196. this._cachedTextureMatrix.m[4] = this._t2.x;
  30197. this._cachedTextureMatrix.m[5] = this._t2.y;
  30198. this._cachedTextureMatrix.m[6] = this._t2.z;
  30199. this._cachedTextureMatrix.m[8] = this._t0.x;
  30200. this._cachedTextureMatrix.m[9] = this._t0.y;
  30201. this._cachedTextureMatrix.m[10] = this._t0.z;
  30202. var scene = this.getScene();
  30203. if (!scene) {
  30204. return this._cachedTextureMatrix;
  30205. }
  30206. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30207. return mat.hasTexture(_this);
  30208. });
  30209. return this._cachedTextureMatrix;
  30210. };
  30211. Texture.prototype.getReflectionTextureMatrix = function () {
  30212. var _this = this;
  30213. var scene = this.getScene();
  30214. if (!scene) {
  30215. return this._cachedTextureMatrix;
  30216. }
  30217. if (this.uOffset === this._cachedUOffset &&
  30218. this.vOffset === this._cachedVOffset &&
  30219. this.uScale === this._cachedUScale &&
  30220. this.vScale === this._cachedVScale &&
  30221. this.coordinatesMode === this._cachedCoordinatesMode) {
  30222. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30223. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30224. return this._cachedTextureMatrix;
  30225. }
  30226. }
  30227. else {
  30228. return this._cachedTextureMatrix;
  30229. }
  30230. }
  30231. if (!this._cachedTextureMatrix) {
  30232. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30233. }
  30234. if (!this._projectionModeMatrix) {
  30235. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30236. }
  30237. this._cachedUOffset = this.uOffset;
  30238. this._cachedVOffset = this.vOffset;
  30239. this._cachedUScale = this.uScale;
  30240. this._cachedVScale = this.vScale;
  30241. this._cachedCoordinatesMode = this.coordinatesMode;
  30242. switch (this.coordinatesMode) {
  30243. case Texture.PLANAR_MODE:
  30244. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30245. this._cachedTextureMatrix[0] = this.uScale;
  30246. this._cachedTextureMatrix[5] = this.vScale;
  30247. this._cachedTextureMatrix[12] = this.uOffset;
  30248. this._cachedTextureMatrix[13] = this.vOffset;
  30249. break;
  30250. case Texture.PROJECTION_MODE:
  30251. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30252. this._projectionModeMatrix.m[0] = 0.5;
  30253. this._projectionModeMatrix.m[5] = -0.5;
  30254. this._projectionModeMatrix.m[10] = 0.0;
  30255. this._projectionModeMatrix.m[12] = 0.5;
  30256. this._projectionModeMatrix.m[13] = 0.5;
  30257. this._projectionModeMatrix.m[14] = 1.0;
  30258. this._projectionModeMatrix.m[15] = 1.0;
  30259. var projectionMatrix = scene.getProjectionMatrix();
  30260. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30261. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30262. break;
  30263. default:
  30264. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30265. break;
  30266. }
  30267. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30268. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30269. });
  30270. return this._cachedTextureMatrix;
  30271. };
  30272. Texture.prototype.clone = function () {
  30273. var _this = this;
  30274. return BABYLON.SerializationHelper.Clone(function () {
  30275. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30276. }, this);
  30277. };
  30278. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30279. get: function () {
  30280. if (!this._onLoadObservable) {
  30281. this._onLoadObservable = new BABYLON.Observable();
  30282. }
  30283. return this._onLoadObservable;
  30284. },
  30285. enumerable: true,
  30286. configurable: true
  30287. });
  30288. Texture.prototype.serialize = function () {
  30289. var serializationObject = _super.prototype.serialize.call(this);
  30290. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30291. serializationObject.base64String = this._buffer;
  30292. serializationObject.name = serializationObject.name.replace("data:", "");
  30293. }
  30294. serializationObject.invertY = this._invertY;
  30295. serializationObject.samplingMode = this.samplingMode;
  30296. return serializationObject;
  30297. };
  30298. Texture.prototype.getClassName = function () {
  30299. return "Texture";
  30300. };
  30301. Texture.prototype.dispose = function () {
  30302. _super.prototype.dispose.call(this);
  30303. if (this._onLoadObservable) {
  30304. this._onLoadObservable.clear();
  30305. this._onLoadObservable = null;
  30306. }
  30307. this._delayedOnLoad = null;
  30308. this._delayedOnError = null;
  30309. };
  30310. // Statics
  30311. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30312. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30313. if (onLoad === void 0) { onLoad = null; }
  30314. if (onError === void 0) { onError = null; }
  30315. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30316. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30317. };
  30318. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30319. if (parsedTexture.customType) {
  30320. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30321. // Update Sampling Mode
  30322. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30323. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30324. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30325. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30326. }
  30327. }
  30328. return parsedCustomTexture;
  30329. }
  30330. if (parsedTexture.isCube) {
  30331. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30332. }
  30333. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30334. return null;
  30335. }
  30336. var texture = BABYLON.SerializationHelper.Parse(function () {
  30337. var generateMipMaps = true;
  30338. if (parsedTexture.noMipmap) {
  30339. generateMipMaps = false;
  30340. }
  30341. if (parsedTexture.mirrorPlane) {
  30342. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30343. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30344. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30345. return mirrorTexture;
  30346. }
  30347. else if (parsedTexture.isRenderTarget) {
  30348. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30349. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30350. return renderTargetTexture;
  30351. }
  30352. else {
  30353. var texture;
  30354. if (parsedTexture.base64String) {
  30355. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30356. }
  30357. else {
  30358. var url = rootUrl + parsedTexture.name;
  30359. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30360. url = parsedTexture.url;
  30361. }
  30362. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30363. }
  30364. return texture;
  30365. }
  30366. }, parsedTexture, scene);
  30367. // Update Sampling Mode
  30368. if (parsedTexture.samplingMode) {
  30369. var sampling = parsedTexture.samplingMode;
  30370. if (texture._samplingMode !== sampling) {
  30371. texture.updateSamplingMode(sampling);
  30372. }
  30373. }
  30374. // Animations
  30375. if (parsedTexture.animations) {
  30376. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30377. var parsedAnimation = parsedTexture.animations[animationIndex];
  30378. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30379. }
  30380. }
  30381. return texture;
  30382. };
  30383. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30384. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30385. if (noMipmap === void 0) { noMipmap = false; }
  30386. if (invertY === void 0) { invertY = true; }
  30387. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30388. if (onLoad === void 0) { onLoad = null; }
  30389. if (onError === void 0) { onError = null; }
  30390. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30391. if (name.substr(0, 5) !== "data:") {
  30392. name = "data:" + name;
  30393. }
  30394. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30395. };
  30396. // Constants
  30397. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30398. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30399. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30400. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30401. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30402. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30403. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30404. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30405. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30406. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30407. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30408. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30409. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30410. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30411. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30412. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30413. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30414. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30415. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30416. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30417. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30418. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30419. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30420. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30421. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30422. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30423. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30424. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30425. /**
  30426. * 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
  30427. */
  30428. Texture.UseSerializedUrlIfAny = false;
  30429. __decorate([
  30430. BABYLON.serialize()
  30431. ], Texture.prototype, "url", void 0);
  30432. __decorate([
  30433. BABYLON.serialize()
  30434. ], Texture.prototype, "uOffset", void 0);
  30435. __decorate([
  30436. BABYLON.serialize()
  30437. ], Texture.prototype, "vOffset", void 0);
  30438. __decorate([
  30439. BABYLON.serialize()
  30440. ], Texture.prototype, "uScale", void 0);
  30441. __decorate([
  30442. BABYLON.serialize()
  30443. ], Texture.prototype, "vScale", void 0);
  30444. __decorate([
  30445. BABYLON.serialize()
  30446. ], Texture.prototype, "uAng", void 0);
  30447. __decorate([
  30448. BABYLON.serialize()
  30449. ], Texture.prototype, "vAng", void 0);
  30450. __decorate([
  30451. BABYLON.serialize()
  30452. ], Texture.prototype, "wAng", void 0);
  30453. __decorate([
  30454. BABYLON.serialize()
  30455. ], Texture.prototype, "uRotationCenter", void 0);
  30456. __decorate([
  30457. BABYLON.serialize()
  30458. ], Texture.prototype, "vRotationCenter", void 0);
  30459. __decorate([
  30460. BABYLON.serialize()
  30461. ], Texture.prototype, "wRotationCenter", void 0);
  30462. __decorate([
  30463. BABYLON.serialize()
  30464. ], Texture.prototype, "isBlocking", null);
  30465. return Texture;
  30466. }(BABYLON.BaseTexture));
  30467. BABYLON.Texture = Texture;
  30468. })(BABYLON || (BABYLON = {}));
  30469. //# sourceMappingURL=babylon.texture.js.map
  30470. var BABYLON;
  30471. (function (BABYLON) {
  30472. /**
  30473. * @hidden
  30474. **/
  30475. var _InstancesBatch = /** @class */ (function () {
  30476. function _InstancesBatch() {
  30477. this.mustReturn = false;
  30478. this.visibleInstances = new Array();
  30479. this.renderSelf = new Array();
  30480. }
  30481. return _InstancesBatch;
  30482. }());
  30483. BABYLON._InstancesBatch = _InstancesBatch;
  30484. var Mesh = /** @class */ (function (_super) {
  30485. __extends(Mesh, _super);
  30486. /**
  30487. * @constructor
  30488. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30489. * @param {Scene} scene The scene to add this mesh to.
  30490. * @param {Node} parent The parent of this mesh, if it has one
  30491. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30492. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30493. * When false, achieved by calling a clone(), also passing False.
  30494. * This will make creation of children, recursive.
  30495. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30496. */
  30497. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30498. if (scene === void 0) { scene = null; }
  30499. if (parent === void 0) { parent = null; }
  30500. if (source === void 0) { source = null; }
  30501. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30502. var _this = _super.call(this, name, scene) || this;
  30503. // Members
  30504. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30505. _this.instances = new Array();
  30506. _this._LODLevels = new Array();
  30507. /** @hidden */
  30508. _this._visibleInstances = {};
  30509. _this._renderIdForInstances = new Array();
  30510. _this._batchCache = new _InstancesBatch();
  30511. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30512. // Use by builder only to know what orientation were the mesh build in.
  30513. /** @hidden */
  30514. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30515. _this.overrideMaterialSideOrientation = null;
  30516. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30517. // Will be used to save a source mesh reference, If any
  30518. _this._source = null;
  30519. scene = _this.getScene();
  30520. if (source) {
  30521. // Geometry
  30522. if (source._geometry) {
  30523. source._geometry.applyToMesh(_this);
  30524. }
  30525. // Deep copy
  30526. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30527. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  30528. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  30529. ], ["_poseMatrix"]);
  30530. // Source mesh
  30531. _this._source = source;
  30532. // Construction Params
  30533. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  30534. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  30535. var myAnyThis = _this;
  30536. var myAnySource = source;
  30537. myAnyThis._closePath = myAnySource._closePath;
  30538. myAnyThis._idx = myAnySource._idx;
  30539. myAnyThis.dashSize = myAnySource.dashSize;
  30540. myAnyThis.gapSize = myAnySource.gapSize;
  30541. myAnyThis.path3D = myAnySource.path3D;
  30542. myAnyThis.pathArray = myAnySource.pathArray;
  30543. myAnyThis.arc = myAnySource.arc;
  30544. myAnyThis.radius = myAnySource.radius;
  30545. // Animation ranges
  30546. if (_this._source._ranges) {
  30547. var ranges = _this._source._ranges;
  30548. for (var name in ranges) {
  30549. if (!ranges.hasOwnProperty(name)) {
  30550. continue;
  30551. }
  30552. if (!ranges[name]) {
  30553. continue;
  30554. }
  30555. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  30556. }
  30557. }
  30558. // Metadata
  30559. if (source.metadata && source.metadata.clone) {
  30560. _this.metadata = source.metadata.clone();
  30561. }
  30562. else {
  30563. _this.metadata = source.metadata;
  30564. }
  30565. // Tags
  30566. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30567. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30568. }
  30569. // Parent
  30570. _this.parent = source.parent;
  30571. // Pivot
  30572. _this.setPivotMatrix(source.getPivotMatrix());
  30573. _this.id = name + "." + source.id;
  30574. // Material
  30575. _this.material = source.material;
  30576. var index;
  30577. if (!doNotCloneChildren) {
  30578. // Children
  30579. var directDescendants = source.getDescendants(true);
  30580. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30581. var child = directDescendants[index_1];
  30582. if (child.clone) {
  30583. child.clone(name + "." + child.name, _this);
  30584. }
  30585. }
  30586. }
  30587. // Physics clone
  30588. var physicsEngine = _this.getScene().getPhysicsEngine();
  30589. if (clonePhysicsImpostor && physicsEngine) {
  30590. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30591. if (impostor) {
  30592. _this.physicsImpostor = impostor.clone(_this);
  30593. }
  30594. }
  30595. // Particles
  30596. for (index = 0; index < scene.particleSystems.length; index++) {
  30597. var system = scene.particleSystems[index];
  30598. if (system.emitter === source) {
  30599. system.clone(system.name, _this);
  30600. }
  30601. }
  30602. _this.refreshBoundingInfo();
  30603. _this.computeWorldMatrix(true);
  30604. }
  30605. // Parent
  30606. if (parent !== null) {
  30607. _this.parent = parent;
  30608. }
  30609. return _this;
  30610. }
  30611. Object.defineProperty(Mesh, "FRONTSIDE", {
  30612. /**
  30613. * Mesh side orientation : usually the external or front surface
  30614. */
  30615. get: function () {
  30616. return Mesh._FRONTSIDE;
  30617. },
  30618. enumerable: true,
  30619. configurable: true
  30620. });
  30621. Object.defineProperty(Mesh, "BACKSIDE", {
  30622. /**
  30623. * Mesh side orientation : usually the internal or back surface
  30624. */
  30625. get: function () {
  30626. return Mesh._BACKSIDE;
  30627. },
  30628. enumerable: true,
  30629. configurable: true
  30630. });
  30631. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30632. /**
  30633. * Mesh side orientation : both internal and external or front and back surfaces
  30634. */
  30635. get: function () {
  30636. return Mesh._DOUBLESIDE;
  30637. },
  30638. enumerable: true,
  30639. configurable: true
  30640. });
  30641. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30642. /**
  30643. * Mesh side orientation : by default, `FRONTSIDE`
  30644. */
  30645. get: function () {
  30646. return Mesh._DEFAULTSIDE;
  30647. },
  30648. enumerable: true,
  30649. configurable: true
  30650. });
  30651. Object.defineProperty(Mesh, "NO_CAP", {
  30652. /**
  30653. * Mesh cap setting : no cap
  30654. */
  30655. get: function () {
  30656. return Mesh._NO_CAP;
  30657. },
  30658. enumerable: true,
  30659. configurable: true
  30660. });
  30661. Object.defineProperty(Mesh, "CAP_START", {
  30662. /**
  30663. * Mesh cap setting : one cap at the beginning of the mesh
  30664. */
  30665. get: function () {
  30666. return Mesh._CAP_START;
  30667. },
  30668. enumerable: true,
  30669. configurable: true
  30670. });
  30671. Object.defineProperty(Mesh, "CAP_END", {
  30672. /**
  30673. * Mesh cap setting : one cap at the end of the mesh
  30674. */
  30675. get: function () {
  30676. return Mesh._CAP_END;
  30677. },
  30678. enumerable: true,
  30679. configurable: true
  30680. });
  30681. Object.defineProperty(Mesh, "CAP_ALL", {
  30682. /**
  30683. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30684. */
  30685. get: function () {
  30686. return Mesh._CAP_ALL;
  30687. },
  30688. enumerable: true,
  30689. configurable: true
  30690. });
  30691. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  30692. /**
  30693. * An event triggered before rendering the mesh
  30694. */
  30695. get: function () {
  30696. if (!this._onBeforeRenderObservable) {
  30697. this._onBeforeRenderObservable = new BABYLON.Observable();
  30698. }
  30699. return this._onBeforeRenderObservable;
  30700. },
  30701. enumerable: true,
  30702. configurable: true
  30703. });
  30704. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  30705. /**
  30706. * An event triggered after rendering the mesh
  30707. */
  30708. get: function () {
  30709. if (!this._onAfterRenderObservable) {
  30710. this._onAfterRenderObservable = new BABYLON.Observable();
  30711. }
  30712. return this._onAfterRenderObservable;
  30713. },
  30714. enumerable: true,
  30715. configurable: true
  30716. });
  30717. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  30718. /**
  30719. * An event triggered before drawing the mesh
  30720. */
  30721. get: function () {
  30722. if (!this._onBeforeDrawObservable) {
  30723. this._onBeforeDrawObservable = new BABYLON.Observable();
  30724. }
  30725. return this._onBeforeDrawObservable;
  30726. },
  30727. enumerable: true,
  30728. configurable: true
  30729. });
  30730. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30731. set: function (callback) {
  30732. if (this._onBeforeDrawObserver) {
  30733. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30734. }
  30735. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30736. },
  30737. enumerable: true,
  30738. configurable: true
  30739. });
  30740. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  30741. get: function () {
  30742. return this._morphTargetManager;
  30743. },
  30744. set: function (value) {
  30745. if (this._morphTargetManager === value) {
  30746. return;
  30747. }
  30748. this._morphTargetManager = value;
  30749. this._syncGeometryWithMorphTargetManager();
  30750. },
  30751. enumerable: true,
  30752. configurable: true
  30753. });
  30754. Object.defineProperty(Mesh.prototype, "source", {
  30755. get: function () {
  30756. return this._source;
  30757. },
  30758. enumerable: true,
  30759. configurable: true
  30760. });
  30761. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  30762. get: function () {
  30763. return this._unIndexed;
  30764. },
  30765. set: function (value) {
  30766. if (this._unIndexed !== value) {
  30767. this._unIndexed = value;
  30768. this._markSubMeshesAsAttributesDirty();
  30769. }
  30770. },
  30771. enumerable: true,
  30772. configurable: true
  30773. });
  30774. // Methods
  30775. /**
  30776. * Returns the string "Mesh".
  30777. */
  30778. Mesh.prototype.getClassName = function () {
  30779. return "Mesh";
  30780. };
  30781. /**
  30782. * Returns a string.
  30783. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30784. */
  30785. Mesh.prototype.toString = function (fullDetails) {
  30786. var ret = _super.prototype.toString.call(this, fullDetails);
  30787. ret += ", n vertices: " + this.getTotalVertices();
  30788. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  30789. if (this.animations) {
  30790. for (var i = 0; i < this.animations.length; i++) {
  30791. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  30792. }
  30793. }
  30794. if (fullDetails) {
  30795. if (this._geometry) {
  30796. var ib = this.getIndices();
  30797. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30798. if (vb && ib) {
  30799. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  30800. }
  30801. }
  30802. else {
  30803. ret += ", flat shading: UNKNOWN";
  30804. }
  30805. }
  30806. return ret;
  30807. };
  30808. /** @hidden */
  30809. Mesh.prototype._unBindEffect = function () {
  30810. _super.prototype._unBindEffect.call(this);
  30811. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  30812. var instance = _a[_i];
  30813. instance._unBindEffect();
  30814. }
  30815. };
  30816. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  30817. /**
  30818. * True if the mesh has some Levels Of Details (LOD).
  30819. * Returns a boolean.
  30820. */
  30821. get: function () {
  30822. return this._LODLevels.length > 0;
  30823. },
  30824. enumerable: true,
  30825. configurable: true
  30826. });
  30827. /**
  30828. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  30829. * @returns an array of {BABYLON.MeshLODLevel}
  30830. */
  30831. Mesh.prototype.getLODLevels = function () {
  30832. return this._LODLevels;
  30833. };
  30834. Mesh.prototype._sortLODLevels = function () {
  30835. this._LODLevels.sort(function (a, b) {
  30836. if (a.distance < b.distance) {
  30837. return 1;
  30838. }
  30839. if (a.distance > b.distance) {
  30840. return -1;
  30841. }
  30842. return 0;
  30843. });
  30844. };
  30845. /**
  30846. * Add a mesh as LOD level triggered at the given distance.
  30847. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30848. * @param distance The distance from the center of the object to show this level
  30849. * @param mesh The mesh to be added as LOD level (can be null)
  30850. * @return This mesh (for chaining)
  30851. */
  30852. Mesh.prototype.addLODLevel = function (distance, mesh) {
  30853. if (mesh && mesh._masterMesh) {
  30854. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  30855. return this;
  30856. }
  30857. var level = new BABYLON.MeshLODLevel(distance, mesh);
  30858. this._LODLevels.push(level);
  30859. if (mesh) {
  30860. mesh._masterMesh = this;
  30861. }
  30862. this._sortLODLevels();
  30863. return this;
  30864. };
  30865. /**
  30866. * Returns the LOD level mesh at the passed distance or null if not found.
  30867. * It is related to the method `addLODLevel(distance, mesh)`.
  30868. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30869. * Returns an object Mesh or `null`.
  30870. */
  30871. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  30872. for (var index = 0; index < this._LODLevels.length; index++) {
  30873. var level = this._LODLevels[index];
  30874. if (level.distance === distance) {
  30875. return level.mesh;
  30876. }
  30877. }
  30878. return null;
  30879. };
  30880. /**
  30881. * Remove a mesh from the LOD array
  30882. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30883. * @param {Mesh} mesh The mesh to be removed.
  30884. * @return {Mesh} This mesh (for chaining)
  30885. */
  30886. Mesh.prototype.removeLODLevel = function (mesh) {
  30887. for (var index = 0; index < this._LODLevels.length; index++) {
  30888. if (this._LODLevels[index].mesh === mesh) {
  30889. this._LODLevels.splice(index, 1);
  30890. if (mesh) {
  30891. mesh._masterMesh = null;
  30892. }
  30893. }
  30894. }
  30895. this._sortLODLevels();
  30896. return this;
  30897. };
  30898. /**
  30899. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  30900. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  30901. */
  30902. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  30903. if (!this._LODLevels || this._LODLevels.length === 0) {
  30904. return this;
  30905. }
  30906. var bSphere;
  30907. if (boundingSphere) {
  30908. bSphere = boundingSphere;
  30909. }
  30910. else {
  30911. var boundingInfo = this.getBoundingInfo();
  30912. bSphere = boundingInfo.boundingSphere;
  30913. }
  30914. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  30915. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  30916. if (this.onLODLevelSelection) {
  30917. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  30918. }
  30919. return this;
  30920. }
  30921. for (var index = 0; index < this._LODLevels.length; index++) {
  30922. var level = this._LODLevels[index];
  30923. if (level.distance < distanceToCamera) {
  30924. if (level.mesh) {
  30925. level.mesh._preActivate();
  30926. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  30927. }
  30928. if (this.onLODLevelSelection) {
  30929. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  30930. }
  30931. return level.mesh;
  30932. }
  30933. }
  30934. if (this.onLODLevelSelection) {
  30935. this.onLODLevelSelection(distanceToCamera, this, this);
  30936. }
  30937. return this;
  30938. };
  30939. Object.defineProperty(Mesh.prototype, "geometry", {
  30940. /**
  30941. * Returns the mesh internal Geometry object.
  30942. */
  30943. get: function () {
  30944. return this._geometry;
  30945. },
  30946. enumerable: true,
  30947. configurable: true
  30948. });
  30949. /**
  30950. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  30951. */
  30952. Mesh.prototype.getTotalVertices = function () {
  30953. if (this._geometry === null || this._geometry === undefined) {
  30954. return 0;
  30955. }
  30956. return this._geometry.getTotalVertices();
  30957. };
  30958. /**
  30959. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  30960. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  30961. * You can force the copy with forceCopy === true
  30962. * Returns null if the mesh has no geometry or no vertex buffer.
  30963. * Possible `kind` values :
  30964. * - BABYLON.VertexBuffer.PositionKind
  30965. * - BABYLON.VertexBuffer.UVKind
  30966. * - BABYLON.VertexBuffer.UV2Kind
  30967. * - BABYLON.VertexBuffer.UV3Kind
  30968. * - BABYLON.VertexBuffer.UV4Kind
  30969. * - BABYLON.VertexBuffer.UV5Kind
  30970. * - BABYLON.VertexBuffer.UV6Kind
  30971. * - BABYLON.VertexBuffer.ColorKind
  30972. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30973. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30974. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30975. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30976. */
  30977. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30978. if (!this._geometry) {
  30979. return null;
  30980. }
  30981. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  30982. };
  30983. /**
  30984. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  30985. * Returns `null` if the mesh has no geometry.
  30986. * Possible `kind` values :
  30987. * - BABYLON.VertexBuffer.PositionKind
  30988. * - BABYLON.VertexBuffer.UVKind
  30989. * - BABYLON.VertexBuffer.UV2Kind
  30990. * - BABYLON.VertexBuffer.UV3Kind
  30991. * - BABYLON.VertexBuffer.UV4Kind
  30992. * - BABYLON.VertexBuffer.UV5Kind
  30993. * - BABYLON.VertexBuffer.UV6Kind
  30994. * - BABYLON.VertexBuffer.ColorKind
  30995. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30996. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30997. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30998. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30999. */
  31000. Mesh.prototype.getVertexBuffer = function (kind) {
  31001. if (!this._geometry) {
  31002. return null;
  31003. }
  31004. return this._geometry.getVertexBuffer(kind);
  31005. };
  31006. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31007. if (!this._geometry) {
  31008. if (this._delayInfo) {
  31009. return this._delayInfo.indexOf(kind) !== -1;
  31010. }
  31011. return false;
  31012. }
  31013. return this._geometry.isVerticesDataPresent(kind);
  31014. };
  31015. /**
  31016. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31017. * Possible `kind` values :
  31018. * - BABYLON.VertexBuffer.PositionKind
  31019. * - BABYLON.VertexBuffer.UVKind
  31020. * - BABYLON.VertexBuffer.UV2Kind
  31021. * - BABYLON.VertexBuffer.UV3Kind
  31022. * - BABYLON.VertexBuffer.UV4Kind
  31023. * - BABYLON.VertexBuffer.UV5Kind
  31024. * - BABYLON.VertexBuffer.UV6Kind
  31025. * - BABYLON.VertexBuffer.ColorKind
  31026. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31027. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31028. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31029. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31030. */
  31031. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31032. if (!this._geometry) {
  31033. if (this._delayInfo) {
  31034. return this._delayInfo.indexOf(kind) !== -1;
  31035. }
  31036. return false;
  31037. }
  31038. return this._geometry.isVertexBufferUpdatable(kind);
  31039. };
  31040. /**
  31041. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31042. * Possible `kind` values :
  31043. * - BABYLON.VertexBuffer.PositionKind
  31044. * - BABYLON.VertexBuffer.UVKind
  31045. * - BABYLON.VertexBuffer.UV2Kind
  31046. * - BABYLON.VertexBuffer.UV3Kind
  31047. * - BABYLON.VertexBuffer.UV4Kind
  31048. * - BABYLON.VertexBuffer.UV5Kind
  31049. * - BABYLON.VertexBuffer.UV6Kind
  31050. * - BABYLON.VertexBuffer.ColorKind
  31051. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31052. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31053. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31054. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31055. */
  31056. Mesh.prototype.getVerticesDataKinds = function () {
  31057. if (!this._geometry) {
  31058. var result = new Array();
  31059. if (this._delayInfo) {
  31060. this._delayInfo.forEach(function (kind, index, array) {
  31061. result.push(kind);
  31062. });
  31063. }
  31064. return result;
  31065. }
  31066. return this._geometry.getVerticesDataKinds();
  31067. };
  31068. /**
  31069. * Returns a positive integer : the total number of indices in this mesh geometry.
  31070. * Returns zero if the mesh has no geometry.
  31071. */
  31072. Mesh.prototype.getTotalIndices = function () {
  31073. if (!this._geometry) {
  31074. return 0;
  31075. }
  31076. return this._geometry.getTotalIndices();
  31077. };
  31078. /**
  31079. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31080. * @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.
  31081. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31082. * @returns the indices array or an empty array if the mesh has no geometry
  31083. */
  31084. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31085. if (!this._geometry) {
  31086. return [];
  31087. }
  31088. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31089. };
  31090. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31091. get: function () {
  31092. return this._masterMesh !== null && this._masterMesh !== undefined;
  31093. },
  31094. enumerable: true,
  31095. configurable: true
  31096. });
  31097. /**
  31098. * Determine if the current mesh is ready to be rendered
  31099. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31100. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31101. * @returns true if all associated assets are ready (material, textures, shaders)
  31102. */
  31103. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31104. if (completeCheck === void 0) { completeCheck = false; }
  31105. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31106. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31107. return false;
  31108. }
  31109. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31110. return false;
  31111. }
  31112. if (!this.subMeshes || this.subMeshes.length === 0) {
  31113. return true;
  31114. }
  31115. if (!completeCheck) {
  31116. return true;
  31117. }
  31118. var engine = this.getEngine();
  31119. var scene = this.getScene();
  31120. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31121. this.computeWorldMatrix();
  31122. var mat = this.material || scene.defaultMaterial;
  31123. if (mat) {
  31124. if (mat.storeEffectOnSubMeshes) {
  31125. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31126. var subMesh = _a[_i];
  31127. var effectiveMaterial = subMesh.getMaterial();
  31128. if (effectiveMaterial) {
  31129. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31130. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31131. return false;
  31132. }
  31133. }
  31134. else {
  31135. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31136. return false;
  31137. }
  31138. }
  31139. }
  31140. }
  31141. }
  31142. else {
  31143. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31144. return false;
  31145. }
  31146. }
  31147. }
  31148. // Shadows
  31149. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31150. var light = _c[_b];
  31151. var generator = light.getShadowGenerator();
  31152. if (generator) {
  31153. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31154. var subMesh = _e[_d];
  31155. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31156. return false;
  31157. }
  31158. }
  31159. }
  31160. }
  31161. // LOD
  31162. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31163. var lod = _g[_f];
  31164. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31165. return false;
  31166. }
  31167. }
  31168. return true;
  31169. };
  31170. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31171. /**
  31172. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31173. * This property is pertinent only for updatable parametric shapes.
  31174. */
  31175. get: function () {
  31176. return this._areNormalsFrozen;
  31177. },
  31178. enumerable: true,
  31179. configurable: true
  31180. });
  31181. /**
  31182. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31183. * It has no effect at all on other shapes.
  31184. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31185. * Returns the Mesh.
  31186. */
  31187. Mesh.prototype.freezeNormals = function () {
  31188. this._areNormalsFrozen = true;
  31189. return this;
  31190. };
  31191. /**
  31192. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31193. * It has no effect at all on other shapes.
  31194. * It reactivates the mesh normals computation if it was previously frozen.
  31195. * Returns the Mesh.
  31196. */
  31197. Mesh.prototype.unfreezeNormals = function () {
  31198. this._areNormalsFrozen = false;
  31199. return this;
  31200. };
  31201. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31202. /**
  31203. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31204. */
  31205. set: function (count) {
  31206. this._overridenInstanceCount = count;
  31207. },
  31208. enumerable: true,
  31209. configurable: true
  31210. });
  31211. // Methods
  31212. /** @hidden */
  31213. Mesh.prototype._preActivate = function () {
  31214. var sceneRenderId = this.getScene().getRenderId();
  31215. if (this._preActivateId === sceneRenderId) {
  31216. return this;
  31217. }
  31218. this._preActivateId = sceneRenderId;
  31219. this._visibleInstances = null;
  31220. return this;
  31221. };
  31222. /** @hidden */
  31223. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31224. if (this._visibleInstances) {
  31225. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31226. }
  31227. return this;
  31228. };
  31229. /** @hidden */
  31230. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31231. if (!this._visibleInstances) {
  31232. this._visibleInstances = {};
  31233. this._visibleInstances.defaultRenderId = renderId;
  31234. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31235. }
  31236. if (!this._visibleInstances[renderId]) {
  31237. this._visibleInstances[renderId] = new Array();
  31238. }
  31239. this._visibleInstances[renderId].push(instance);
  31240. return this;
  31241. };
  31242. /**
  31243. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31244. * This means the mesh underlying bounding box and sphere are recomputed.
  31245. * Returns the Mesh.
  31246. */
  31247. Mesh.prototype.refreshBoundingInfo = function () {
  31248. return this._refreshBoundingInfo(false);
  31249. };
  31250. /** @hidden */
  31251. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31252. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31253. return this;
  31254. }
  31255. var data = this._getPositionData(applySkeleton);
  31256. if (data) {
  31257. var bias = this.geometry ? this.geometry.boundingBias : null;
  31258. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  31259. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31260. }
  31261. if (this.subMeshes) {
  31262. for (var index = 0; index < this.subMeshes.length; index++) {
  31263. this.subMeshes[index].refreshBoundingInfo();
  31264. }
  31265. }
  31266. this._updateBoundingInfo();
  31267. return this;
  31268. };
  31269. Mesh.prototype._getPositionData = function (applySkeleton) {
  31270. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31271. if (data && applySkeleton && this.skeleton) {
  31272. data = BABYLON.Tools.Slice(data);
  31273. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31274. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31275. if (matricesWeightsData && matricesIndicesData) {
  31276. var needExtras = this.numBoneInfluencers > 4;
  31277. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31278. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31279. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31280. var tempVector = BABYLON.Tmp.Vector3[0];
  31281. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31282. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31283. var matWeightIdx = 0;
  31284. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31285. finalMatrix.reset();
  31286. var inf;
  31287. var weight;
  31288. for (inf = 0; inf < 4; inf++) {
  31289. weight = matricesWeightsData[matWeightIdx + inf];
  31290. if (weight > 0) {
  31291. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31292. finalMatrix.addToSelf(tempMatrix);
  31293. }
  31294. }
  31295. if (needExtras) {
  31296. for (inf = 0; inf < 4; inf++) {
  31297. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31298. if (weight > 0) {
  31299. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31300. finalMatrix.addToSelf(tempMatrix);
  31301. }
  31302. }
  31303. }
  31304. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31305. tempVector.toArray(data, index);
  31306. }
  31307. }
  31308. }
  31309. return data;
  31310. };
  31311. /** @hidden */
  31312. Mesh.prototype._createGlobalSubMesh = function (force) {
  31313. var totalVertices = this.getTotalVertices();
  31314. if (!totalVertices || !this.getIndices()) {
  31315. return null;
  31316. }
  31317. // Check if we need to recreate the submeshes
  31318. if (this.subMeshes && this.subMeshes.length > 0) {
  31319. var ib = this.getIndices();
  31320. if (!ib) {
  31321. return null;
  31322. }
  31323. var totalIndices = ib.length;
  31324. var needToRecreate = false;
  31325. if (force) {
  31326. needToRecreate = true;
  31327. }
  31328. else {
  31329. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31330. var submesh = _a[_i];
  31331. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31332. needToRecreate = true;
  31333. break;
  31334. }
  31335. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31336. needToRecreate = true;
  31337. break;
  31338. }
  31339. }
  31340. }
  31341. if (!needToRecreate) {
  31342. return this.subMeshes[0];
  31343. }
  31344. }
  31345. this.releaseSubMeshes();
  31346. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31347. };
  31348. Mesh.prototype.subdivide = function (count) {
  31349. if (count < 1) {
  31350. return;
  31351. }
  31352. var totalIndices = this.getTotalIndices();
  31353. var subdivisionSize = (totalIndices / count) | 0;
  31354. var offset = 0;
  31355. // Ensure that subdivisionSize is a multiple of 3
  31356. while (subdivisionSize % 3 !== 0) {
  31357. subdivisionSize++;
  31358. }
  31359. this.releaseSubMeshes();
  31360. for (var index = 0; index < count; index++) {
  31361. if (offset >= totalIndices) {
  31362. break;
  31363. }
  31364. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31365. offset += subdivisionSize;
  31366. }
  31367. this.synchronizeInstances();
  31368. };
  31369. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31370. if (updatable === void 0) { updatable = false; }
  31371. if (!this._geometry) {
  31372. var vertexData = new BABYLON.VertexData();
  31373. vertexData.set(data, kind);
  31374. var scene = this.getScene();
  31375. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31376. }
  31377. else {
  31378. this._geometry.setVerticesData(kind, data, updatable, stride);
  31379. }
  31380. return this;
  31381. };
  31382. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31383. if (updatable === void 0) { updatable = true; }
  31384. var vb = this.getVertexBuffer(kind);
  31385. if (!vb || vb.isUpdatable() === updatable) {
  31386. return;
  31387. }
  31388. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31389. };
  31390. /**
  31391. * Sets the mesh VertexBuffer.
  31392. * Returns the Mesh.
  31393. */
  31394. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31395. if (!this._geometry) {
  31396. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31397. }
  31398. this._geometry.setVerticesBuffer(buffer);
  31399. return this;
  31400. };
  31401. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31402. if (!this._geometry) {
  31403. return this;
  31404. }
  31405. if (!makeItUnique) {
  31406. this._geometry.updateVerticesData(kind, data, updateExtends);
  31407. }
  31408. else {
  31409. this.makeGeometryUnique();
  31410. this.updateVerticesData(kind, data, updateExtends, false);
  31411. }
  31412. return this;
  31413. };
  31414. /**
  31415. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31416. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31417. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31418. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31419. * Returns the Mesh.
  31420. */
  31421. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31422. if (computeNormals === void 0) { computeNormals = true; }
  31423. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31424. if (!positions) {
  31425. return this;
  31426. }
  31427. positionFunction(positions);
  31428. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31429. if (computeNormals) {
  31430. var indices = this.getIndices();
  31431. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31432. if (!normals) {
  31433. return this;
  31434. }
  31435. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31436. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31437. }
  31438. return this;
  31439. };
  31440. /**
  31441. * Creates a un-shared specific occurence of the geometry for the mesh.
  31442. * Returns the Mesh.
  31443. */
  31444. Mesh.prototype.makeGeometryUnique = function () {
  31445. if (!this._geometry) {
  31446. return this;
  31447. }
  31448. var oldGeometry = this._geometry;
  31449. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31450. oldGeometry.releaseForMesh(this, true);
  31451. geometry.applyToMesh(this);
  31452. return this;
  31453. };
  31454. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31455. if (totalVertices === void 0) { totalVertices = null; }
  31456. if (updatable === void 0) { updatable = false; }
  31457. if (!this._geometry) {
  31458. var vertexData = new BABYLON.VertexData();
  31459. vertexData.indices = indices;
  31460. var scene = this.getScene();
  31461. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31462. }
  31463. else {
  31464. this._geometry.setIndices(indices, totalVertices, updatable);
  31465. }
  31466. return this;
  31467. };
  31468. /**
  31469. * Update the current index buffer
  31470. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31471. * Returns the Mesh.
  31472. */
  31473. Mesh.prototype.updateIndices = function (indices, offset) {
  31474. if (!this._geometry) {
  31475. return this;
  31476. }
  31477. this._geometry.updateIndices(indices, offset);
  31478. return this;
  31479. };
  31480. /**
  31481. * Invert the geometry to move from a right handed system to a left handed one.
  31482. * Returns the Mesh.
  31483. */
  31484. Mesh.prototype.toLeftHanded = function () {
  31485. if (!this._geometry) {
  31486. return this;
  31487. }
  31488. this._geometry.toLeftHanded();
  31489. return this;
  31490. };
  31491. /** @hidden */
  31492. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31493. if (!this._geometry) {
  31494. return this;
  31495. }
  31496. var engine = this.getScene().getEngine();
  31497. // Wireframe
  31498. var indexToBind;
  31499. if (this._unIndexed) {
  31500. indexToBind = null;
  31501. }
  31502. else {
  31503. switch (fillMode) {
  31504. case BABYLON.Material.PointFillMode:
  31505. indexToBind = null;
  31506. break;
  31507. case BABYLON.Material.WireFrameFillMode:
  31508. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31509. break;
  31510. default:
  31511. case BABYLON.Material.TriangleFillMode:
  31512. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31513. break;
  31514. }
  31515. }
  31516. // VBOs
  31517. this._geometry._bind(effect, indexToBind);
  31518. return this;
  31519. };
  31520. /** @hidden */
  31521. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31522. if (alternate === void 0) { alternate = false; }
  31523. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31524. return this;
  31525. }
  31526. if (this._onBeforeDrawObservable) {
  31527. this._onBeforeDrawObservable.notifyObservers(this);
  31528. }
  31529. var scene = this.getScene();
  31530. var engine = scene.getEngine();
  31531. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31532. // or triangles as points
  31533. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31534. }
  31535. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31536. // Triangles as wireframe
  31537. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31538. }
  31539. else {
  31540. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31541. }
  31542. if (scene._isAlternateRenderingEnabled && !alternate) {
  31543. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31544. if (!effect || !scene.activeCamera) {
  31545. return this;
  31546. }
  31547. scene._switchToAlternateCameraConfiguration(true);
  31548. this._effectiveMaterial.bindView(effect);
  31549. this._effectiveMaterial.bindViewProjection(effect);
  31550. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31551. this._draw(subMesh, fillMode, instancesCount, true);
  31552. engine.setViewport(scene.activeCamera.viewport);
  31553. scene._switchToAlternateCameraConfiguration(false);
  31554. this._effectiveMaterial.bindView(effect);
  31555. this._effectiveMaterial.bindViewProjection(effect);
  31556. }
  31557. return this;
  31558. };
  31559. /**
  31560. * Registers for this mesh a javascript function called just before the rendering process.
  31561. * This function is passed the current mesh.
  31562. * Return the Mesh.
  31563. */
  31564. Mesh.prototype.registerBeforeRender = function (func) {
  31565. this.onBeforeRenderObservable.add(func);
  31566. return this;
  31567. };
  31568. /**
  31569. * Disposes a previously registered javascript function called before the rendering.
  31570. * This function is passed the current mesh.
  31571. * Returns the Mesh.
  31572. */
  31573. Mesh.prototype.unregisterBeforeRender = function (func) {
  31574. this.onBeforeRenderObservable.removeCallback(func);
  31575. return this;
  31576. };
  31577. /**
  31578. * Registers for this mesh a javascript function called just after the rendering is complete.
  31579. * This function is passed the current mesh.
  31580. * Returns the Mesh.
  31581. */
  31582. Mesh.prototype.registerAfterRender = function (func) {
  31583. this.onAfterRenderObservable.add(func);
  31584. return this;
  31585. };
  31586. /**
  31587. * Disposes a previously registered javascript function called after the rendering.
  31588. * This function is passed the current mesh.
  31589. * Return the Mesh.
  31590. */
  31591. Mesh.prototype.unregisterAfterRender = function (func) {
  31592. this.onAfterRenderObservable.removeCallback(func);
  31593. return this;
  31594. };
  31595. /** @hidden */
  31596. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31597. var scene = this.getScene();
  31598. this._batchCache.mustReturn = false;
  31599. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31600. this._batchCache.visibleInstances[subMeshId] = null;
  31601. if (this._visibleInstances) {
  31602. var currentRenderId = scene.getRenderId();
  31603. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31604. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31605. var selfRenderId = this._renderId;
  31606. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31607. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31608. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31609. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31610. }
  31611. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31612. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31613. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31614. this._batchCache.mustReturn = true;
  31615. return this._batchCache;
  31616. }
  31617. if (currentRenderId !== selfRenderId) {
  31618. this._batchCache.renderSelf[subMeshId] = false;
  31619. }
  31620. }
  31621. this._renderIdForInstances[subMeshId] = currentRenderId;
  31622. }
  31623. return this._batchCache;
  31624. };
  31625. /** @hidden */
  31626. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31627. var visibleInstances = batch.visibleInstances[subMesh._id];
  31628. if (!visibleInstances) {
  31629. return this;
  31630. }
  31631. var matricesCount = visibleInstances.length + 1;
  31632. var bufferSize = matricesCount * 16 * 4;
  31633. var currentInstancesBufferSize = this._instancesBufferSize;
  31634. var instancesBuffer = this._instancesBuffer;
  31635. while (this._instancesBufferSize < bufferSize) {
  31636. this._instancesBufferSize *= 2;
  31637. }
  31638. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31639. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31640. }
  31641. var offset = 0;
  31642. var instancesCount = 0;
  31643. var world = this.getWorldMatrix();
  31644. if (batch.renderSelf[subMesh._id]) {
  31645. world.copyToArray(this._instancesData, offset);
  31646. offset += 16;
  31647. instancesCount++;
  31648. }
  31649. if (visibleInstances) {
  31650. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31651. var instance = visibleInstances[instanceIndex];
  31652. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31653. offset += 16;
  31654. instancesCount++;
  31655. }
  31656. }
  31657. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31658. if (instancesBuffer) {
  31659. instancesBuffer.dispose();
  31660. }
  31661. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31662. this._instancesBuffer = instancesBuffer;
  31663. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31664. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31665. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31666. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31667. }
  31668. else {
  31669. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31670. }
  31671. this._bind(subMesh, effect, fillMode);
  31672. this._draw(subMesh, fillMode, instancesCount);
  31673. engine.unbindInstanceAttributes();
  31674. return this;
  31675. };
  31676. /** @hidden */
  31677. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31678. var scene = this.getScene();
  31679. var engine = scene.getEngine();
  31680. if (hardwareInstancedRendering) {
  31681. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31682. }
  31683. else {
  31684. if (batch.renderSelf[subMesh._id]) {
  31685. // Draw
  31686. if (onBeforeDraw) {
  31687. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31688. }
  31689. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31690. }
  31691. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31692. if (visibleInstancesForSubMesh) {
  31693. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31694. var instance = visibleInstancesForSubMesh[instanceIndex];
  31695. // World
  31696. var world = instance.getWorldMatrix();
  31697. if (onBeforeDraw) {
  31698. onBeforeDraw(true, world, effectiveMaterial);
  31699. }
  31700. // Draw
  31701. this._draw(subMesh, fillMode);
  31702. }
  31703. }
  31704. }
  31705. return this;
  31706. };
  31707. /**
  31708. * 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
  31709. * @param subMesh defines the subMesh to render
  31710. * @param enableAlphaMode defines if alpha mode can be changed
  31711. * @returns the current mesh
  31712. */
  31713. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31714. this._checkOcclusionQuery();
  31715. if (this._isOccluded) {
  31716. return this;
  31717. }
  31718. var scene = this.getScene();
  31719. // Managing instances
  31720. var batch = this._getInstancesRenderList(subMesh._id);
  31721. if (batch.mustReturn) {
  31722. return this;
  31723. }
  31724. // Checking geometry state
  31725. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31726. return this;
  31727. }
  31728. if (this._onBeforeRenderObservable) {
  31729. this._onBeforeRenderObservable.notifyObservers(this);
  31730. }
  31731. var engine = scene.getEngine();
  31732. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31733. // Material
  31734. var material = subMesh.getMaterial();
  31735. if (!material) {
  31736. return this;
  31737. }
  31738. this._effectiveMaterial = material;
  31739. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31740. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31741. return this;
  31742. }
  31743. }
  31744. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31745. return this;
  31746. }
  31747. // Alpha mode
  31748. if (enableAlphaMode) {
  31749. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  31750. }
  31751. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  31752. var step = _a[_i];
  31753. step.action(this, subMesh, batch);
  31754. }
  31755. var effect;
  31756. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31757. effect = subMesh.effect;
  31758. }
  31759. else {
  31760. effect = this._effectiveMaterial.getEffect();
  31761. }
  31762. if (!effect) {
  31763. return this;
  31764. }
  31765. var sideOrientation = this.overrideMaterialSideOrientation;
  31766. if (sideOrientation == null) {
  31767. sideOrientation = this._effectiveMaterial.sideOrientation;
  31768. if (this._getWorldMatrixDeterminant() < 0) {
  31769. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  31770. }
  31771. }
  31772. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  31773. if (this._effectiveMaterial.forceDepthWrite) {
  31774. engine.setDepthWrite(true);
  31775. }
  31776. // Bind
  31777. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  31778. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  31779. this._bind(subMesh, effect, fillMode);
  31780. }
  31781. var world = this.getWorldMatrix();
  31782. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31783. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  31784. }
  31785. else {
  31786. this._effectiveMaterial.bind(world, this);
  31787. }
  31788. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  31789. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  31790. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31791. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  31792. }
  31793. // Draw
  31794. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31795. // Unbind
  31796. this._effectiveMaterial.unbind();
  31797. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  31798. var step = _c[_b];
  31799. step.action(this, subMesh, batch);
  31800. }
  31801. if (this._onAfterRenderObservable) {
  31802. this._onAfterRenderObservable.notifyObservers(this);
  31803. }
  31804. return this;
  31805. };
  31806. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  31807. if (isInstance && effectiveMaterial) {
  31808. effectiveMaterial.bindOnlyWorldMatrix(world);
  31809. }
  31810. };
  31811. /**
  31812. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  31813. */
  31814. Mesh.prototype.getEmittedParticleSystems = function () {
  31815. var results = new Array();
  31816. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31817. var particleSystem = this.getScene().particleSystems[index];
  31818. if (particleSystem.emitter === this) {
  31819. results.push(particleSystem);
  31820. }
  31821. }
  31822. return results;
  31823. };
  31824. /**
  31825. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  31826. */
  31827. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  31828. var results = new Array();
  31829. var descendants = this.getDescendants();
  31830. descendants.push(this);
  31831. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31832. var particleSystem = this.getScene().particleSystems[index];
  31833. var emitter = particleSystem.emitter;
  31834. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  31835. results.push(particleSystem);
  31836. }
  31837. }
  31838. return results;
  31839. };
  31840. /**
  31841. * Normalize matrix weights so that all vertices have a total weight set to 1
  31842. */
  31843. Mesh.prototype.cleanMatrixWeights = function () {
  31844. var epsilon = 1e-3;
  31845. var noInfluenceBoneIndex = 0.0;
  31846. if (this.skeleton) {
  31847. noInfluenceBoneIndex = this.skeleton.bones.length;
  31848. }
  31849. else {
  31850. return;
  31851. }
  31852. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31853. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31854. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31855. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  31856. var influencers = this.numBoneInfluencers;
  31857. var size = matricesWeights.length;
  31858. for (var i = 0; i < size; i += 4) {
  31859. var weight = 0.0;
  31860. var firstZeroWeight = -1;
  31861. for (var j = 0; j < 4; j++) {
  31862. var w = matricesWeights[i + j];
  31863. weight += w;
  31864. if (w < epsilon && firstZeroWeight < 0) {
  31865. firstZeroWeight = j;
  31866. }
  31867. }
  31868. if (matricesWeightsExtra) {
  31869. for (var j = 0; j < 4; j++) {
  31870. var w = matricesWeightsExtra[i + j];
  31871. weight += w;
  31872. if (w < epsilon && firstZeroWeight < 0) {
  31873. firstZeroWeight = j + 4;
  31874. }
  31875. }
  31876. }
  31877. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31878. firstZeroWeight = influencers - 1;
  31879. }
  31880. if (weight > epsilon) {
  31881. var mweight = 1.0 / weight;
  31882. for (var j = 0; j < 4; j++) {
  31883. matricesWeights[i + j] *= mweight;
  31884. }
  31885. if (matricesWeightsExtra) {
  31886. for (var j = 0; j < 4; j++) {
  31887. matricesWeightsExtra[i + j] *= mweight;
  31888. }
  31889. }
  31890. }
  31891. else {
  31892. if (firstZeroWeight >= 4) {
  31893. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31894. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31895. }
  31896. else {
  31897. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31898. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31899. }
  31900. }
  31901. }
  31902. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31903. if (matricesIndicesExtra) {
  31904. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31905. }
  31906. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  31907. if (matricesWeightsExtra) {
  31908. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  31909. }
  31910. };
  31911. /** @hidden */
  31912. Mesh.prototype._checkDelayState = function () {
  31913. var scene = this.getScene();
  31914. if (this._geometry) {
  31915. this._geometry.load(scene);
  31916. }
  31917. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31918. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31919. this._queueLoad(scene);
  31920. }
  31921. return this;
  31922. };
  31923. Mesh.prototype._queueLoad = function (scene) {
  31924. var _this = this;
  31925. scene._addPendingData(this);
  31926. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  31927. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31928. if (data instanceof ArrayBuffer) {
  31929. _this._delayLoadingFunction(data, _this);
  31930. }
  31931. else {
  31932. _this._delayLoadingFunction(JSON.parse(data), _this);
  31933. }
  31934. _this.instances.forEach(function (instance) {
  31935. instance._syncSubMeshes();
  31936. });
  31937. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31938. scene._removePendingData(_this);
  31939. }, function () { }, scene.database, getBinaryData);
  31940. return this;
  31941. };
  31942. /**
  31943. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  31944. * A mesh is in the frustum if its bounding box intersects the frustum
  31945. * @param frustumPlanes defines the frustum to test
  31946. * @returns true if the mesh is in the frustum planes
  31947. */
  31948. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  31949. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31950. return false;
  31951. }
  31952. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  31953. return false;
  31954. }
  31955. this._checkDelayState();
  31956. return true;
  31957. };
  31958. /**
  31959. * Sets the mesh material by the material or multiMaterial `id` property.
  31960. * The material `id` is a string identifying the material or the multiMaterial.
  31961. * This method returns the Mesh.
  31962. */
  31963. Mesh.prototype.setMaterialByID = function (id) {
  31964. var materials = this.getScene().materials;
  31965. var index;
  31966. for (index = materials.length - 1; index > -1; index--) {
  31967. if (materials[index].id === id) {
  31968. this.material = materials[index];
  31969. return this;
  31970. }
  31971. }
  31972. // Multi
  31973. var multiMaterials = this.getScene().multiMaterials;
  31974. for (index = multiMaterials.length - 1; index > -1; index--) {
  31975. if (multiMaterials[index].id === id) {
  31976. this.material = multiMaterials[index];
  31977. return this;
  31978. }
  31979. }
  31980. return this;
  31981. };
  31982. /**
  31983. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  31984. */
  31985. Mesh.prototype.getAnimatables = function () {
  31986. var results = new Array();
  31987. if (this.material) {
  31988. results.push(this.material);
  31989. }
  31990. if (this.skeleton) {
  31991. results.push(this.skeleton);
  31992. }
  31993. return results;
  31994. };
  31995. /**
  31996. * Modifies the mesh geometry according to the passed transformation matrix.
  31997. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  31998. * The mesh normals are modified using the same transformation.
  31999. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32000. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32001. * Returns the Mesh.
  32002. */
  32003. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32004. // Position
  32005. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32006. return this;
  32007. }
  32008. var submeshes = this.subMeshes.splice(0);
  32009. this._resetPointsArrayCache();
  32010. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32011. var temp = new Array();
  32012. var index;
  32013. for (index = 0; index < data.length; index += 3) {
  32014. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32015. }
  32016. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32017. // Normals
  32018. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32019. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32020. temp = [];
  32021. for (index = 0; index < data.length; index += 3) {
  32022. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32023. }
  32024. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32025. }
  32026. // flip faces?
  32027. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32028. this.flipFaces();
  32029. }
  32030. // Restore submeshes
  32031. this.releaseSubMeshes();
  32032. this.subMeshes = submeshes;
  32033. return this;
  32034. };
  32035. /**
  32036. * Modifies the mesh geometry according to its own current World Matrix.
  32037. * The mesh World Matrix is then reset.
  32038. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32039. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32040. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32041. * Returns the Mesh.
  32042. */
  32043. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32044. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32045. this.scaling.copyFromFloats(1, 1, 1);
  32046. this.position.copyFromFloats(0, 0, 0);
  32047. this.rotation.copyFromFloats(0, 0, 0);
  32048. //only if quaternion is already set
  32049. if (this.rotationQuaternion) {
  32050. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32051. }
  32052. this._worldMatrix = BABYLON.Matrix.Identity();
  32053. return this;
  32054. };
  32055. Object.defineProperty(Mesh.prototype, "_positions", {
  32056. // Cache
  32057. get: function () {
  32058. if (this._geometry) {
  32059. return this._geometry._positions;
  32060. }
  32061. return null;
  32062. },
  32063. enumerable: true,
  32064. configurable: true
  32065. });
  32066. /** @hidden */
  32067. Mesh.prototype._resetPointsArrayCache = function () {
  32068. if (this._geometry) {
  32069. this._geometry._resetPointsArrayCache();
  32070. }
  32071. return this;
  32072. };
  32073. /** @hidden */
  32074. Mesh.prototype._generatePointsArray = function () {
  32075. if (this._geometry) {
  32076. return this._geometry._generatePointsArray();
  32077. }
  32078. return false;
  32079. };
  32080. /**
  32081. * Returns a new Mesh object generated from the current mesh properties.
  32082. * This method must not get confused with createInstance().
  32083. * The parameter `name` is a string, the name given to the new mesh.
  32084. * The optional parameter `newParent` can be any Node object (default `null`).
  32085. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32086. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  32087. */
  32088. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32089. if (name === void 0) { name = ""; }
  32090. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32091. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32092. };
  32093. /**
  32094. * Releases resources associated with this mesh.
  32095. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32096. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32097. */
  32098. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32099. var _this = this;
  32100. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32101. this.morphTargetManager = null;
  32102. if (this._geometry) {
  32103. this._geometry.releaseForMesh(this, true);
  32104. }
  32105. if (this._onBeforeDrawObservable) {
  32106. this._onBeforeDrawObservable.clear();
  32107. }
  32108. if (this._onBeforeRenderObservable) {
  32109. this._onBeforeRenderObservable.clear();
  32110. }
  32111. if (this._onAfterRenderObservable) {
  32112. this._onAfterRenderObservable.clear();
  32113. }
  32114. // Sources
  32115. var meshes = this.getScene().meshes;
  32116. meshes.forEach(function (abstractMesh) {
  32117. var mesh = abstractMesh;
  32118. if (mesh._source && mesh._source === _this) {
  32119. mesh._source = null;
  32120. }
  32121. });
  32122. this._source = null;
  32123. // Instances
  32124. if (this._instancesBuffer) {
  32125. this._instancesBuffer.dispose();
  32126. this._instancesBuffer = null;
  32127. }
  32128. while (this.instances.length) {
  32129. this.instances[0].dispose();
  32130. }
  32131. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32132. };
  32133. /**
  32134. * Modifies the mesh geometry according to a displacement map.
  32135. * 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.
  32136. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32137. * This method returns nothing.
  32138. * @param url is a string, the URL from the image file is to be downloaded.
  32139. * @param minHeight is the lower limit of the displacement.
  32140. * @param maxHeight is the upper limit of the displacement.
  32141. * @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.
  32142. * @param uvOffset is an optional vector2 used to offset UV.
  32143. * @param uvScale is an optional vector2 used to scale UV.
  32144. * @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.
  32145. * @returns the Mesh.
  32146. */
  32147. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32148. var _this = this;
  32149. if (forceUpdate === void 0) { forceUpdate = false; }
  32150. var scene = this.getScene();
  32151. var onload = function (img) {
  32152. // Getting height map data
  32153. var canvas = document.createElement("canvas");
  32154. var context = canvas.getContext("2d");
  32155. var heightMapWidth = img.width;
  32156. var heightMapHeight = img.height;
  32157. canvas.width = heightMapWidth;
  32158. canvas.height = heightMapHeight;
  32159. context.drawImage(img, 0, 0);
  32160. // Create VertexData from map data
  32161. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32162. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32163. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32164. //execute success callback, if set
  32165. if (onSuccess) {
  32166. onSuccess(_this);
  32167. }
  32168. };
  32169. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32170. return this;
  32171. };
  32172. /**
  32173. * Modifies the mesh geometry according to a displacementMap buffer.
  32174. * 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.
  32175. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32176. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32177. * @param heightMapWidth is the width of the buffer image.
  32178. * @param heightMapHeight is the height of the buffer image.
  32179. * @param minHeight is the lower limit of the displacement.
  32180. * @param maxHeight is the upper limit of the displacement.
  32181. * @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.
  32182. * @param uvOffset is an optional vector2 used to offset UV.
  32183. * @param uvScale is an optional vector2 used to scale UV.
  32184. * @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.
  32185. * @returns the Mesh.
  32186. */
  32187. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32188. if (forceUpdate === void 0) { forceUpdate = false; }
  32189. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32190. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32191. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32192. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32193. return this;
  32194. }
  32195. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32196. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32197. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32198. var position = BABYLON.Vector3.Zero();
  32199. var normal = BABYLON.Vector3.Zero();
  32200. var uv = BABYLON.Vector2.Zero();
  32201. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32202. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32203. for (var index = 0; index < positions.length; index += 3) {
  32204. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32205. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32206. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32207. // Compute height
  32208. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32209. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32210. var pos = (u + v * heightMapWidth) * 4;
  32211. var r = buffer[pos] / 255.0;
  32212. var g = buffer[pos + 1] / 255.0;
  32213. var b = buffer[pos + 2] / 255.0;
  32214. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32215. normal.normalize();
  32216. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32217. position = position.add(normal);
  32218. position.toArray(positions, index);
  32219. }
  32220. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32221. if (forceUpdate) {
  32222. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32223. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32224. }
  32225. else {
  32226. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32227. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32228. }
  32229. return this;
  32230. };
  32231. /**
  32232. * Modify the mesh to get a flat shading rendering.
  32233. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32234. * This method returns the Mesh.
  32235. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32236. */
  32237. Mesh.prototype.convertToFlatShadedMesh = function () {
  32238. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32239. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32240. var kinds = this.getVerticesDataKinds();
  32241. var vbs = {};
  32242. var data = {};
  32243. var newdata = {};
  32244. var updatableNormals = false;
  32245. var kindIndex;
  32246. var kind;
  32247. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32248. kind = kinds[kindIndex];
  32249. var vertexBuffer = this.getVertexBuffer(kind);
  32250. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32251. updatableNormals = vertexBuffer.isUpdatable();
  32252. kinds.splice(kindIndex, 1);
  32253. kindIndex--;
  32254. continue;
  32255. }
  32256. vbs[kind] = vertexBuffer;
  32257. data[kind] = vbs[kind].getData();
  32258. newdata[kind] = [];
  32259. }
  32260. // Save previous submeshes
  32261. var previousSubmeshes = this.subMeshes.slice(0);
  32262. var indices = this.getIndices();
  32263. var totalIndices = this.getTotalIndices();
  32264. // Generating unique vertices per face
  32265. var index;
  32266. for (index = 0; index < totalIndices; index++) {
  32267. var vertexIndex = indices[index];
  32268. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32269. kind = kinds[kindIndex];
  32270. var stride = vbs[kind].getStrideSize();
  32271. for (var offset = 0; offset < stride; offset++) {
  32272. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32273. }
  32274. }
  32275. }
  32276. // Updating faces & normal
  32277. var normals = [];
  32278. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32279. for (index = 0; index < totalIndices; index += 3) {
  32280. indices[index] = index;
  32281. indices[index + 1] = index + 1;
  32282. indices[index + 2] = index + 2;
  32283. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32284. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32285. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32286. var p1p2 = p1.subtract(p2);
  32287. var p3p2 = p3.subtract(p2);
  32288. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32289. // Store same normals for every vertex
  32290. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32291. normals.push(normal.x);
  32292. normals.push(normal.y);
  32293. normals.push(normal.z);
  32294. }
  32295. }
  32296. this.setIndices(indices);
  32297. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32298. // Updating vertex buffers
  32299. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32300. kind = kinds[kindIndex];
  32301. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32302. }
  32303. // Updating submeshes
  32304. this.releaseSubMeshes();
  32305. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32306. var previousOne = previousSubmeshes[submeshIndex];
  32307. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32308. }
  32309. this.synchronizeInstances();
  32310. return this;
  32311. };
  32312. /**
  32313. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32314. * In other words, more vertices, no more indices and a single bigger VBO.
  32315. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32316. * Returns the Mesh.
  32317. */
  32318. Mesh.prototype.convertToUnIndexedMesh = function () {
  32319. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32320. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32321. var kinds = this.getVerticesDataKinds();
  32322. var vbs = {};
  32323. var data = {};
  32324. var newdata = {};
  32325. var kindIndex;
  32326. var kind;
  32327. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32328. kind = kinds[kindIndex];
  32329. var vertexBuffer = this.getVertexBuffer(kind);
  32330. vbs[kind] = vertexBuffer;
  32331. data[kind] = vbs[kind].getData();
  32332. newdata[kind] = [];
  32333. }
  32334. // Save previous submeshes
  32335. var previousSubmeshes = this.subMeshes.slice(0);
  32336. var indices = this.getIndices();
  32337. var totalIndices = this.getTotalIndices();
  32338. // Generating unique vertices per face
  32339. var index;
  32340. for (index = 0; index < totalIndices; index++) {
  32341. var vertexIndex = indices[index];
  32342. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32343. kind = kinds[kindIndex];
  32344. var stride = vbs[kind].getStrideSize();
  32345. for (var offset = 0; offset < stride; offset++) {
  32346. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32347. }
  32348. }
  32349. }
  32350. // Updating indices
  32351. for (index = 0; index < totalIndices; index += 3) {
  32352. indices[index] = index;
  32353. indices[index + 1] = index + 1;
  32354. indices[index + 2] = index + 2;
  32355. }
  32356. this.setIndices(indices);
  32357. // Updating vertex buffers
  32358. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32359. kind = kinds[kindIndex];
  32360. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32361. }
  32362. // Updating submeshes
  32363. this.releaseSubMeshes();
  32364. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32365. var previousOne = previousSubmeshes[submeshIndex];
  32366. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32367. }
  32368. this._unIndexed = true;
  32369. this.synchronizeInstances();
  32370. return this;
  32371. };
  32372. /**
  32373. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32374. * This method returns the Mesh.
  32375. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32376. */
  32377. Mesh.prototype.flipFaces = function (flipNormals) {
  32378. if (flipNormals === void 0) { flipNormals = false; }
  32379. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32380. var i;
  32381. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32382. for (i = 0; i < vertex_data.normals.length; i++) {
  32383. vertex_data.normals[i] *= -1;
  32384. }
  32385. }
  32386. if (vertex_data.indices) {
  32387. var temp;
  32388. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32389. // reassign indices
  32390. temp = vertex_data.indices[i + 1];
  32391. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32392. vertex_data.indices[i + 2] = temp;
  32393. }
  32394. }
  32395. vertex_data.applyToMesh(this);
  32396. return this;
  32397. };
  32398. // Instances
  32399. /**
  32400. * Creates a new InstancedMesh object from the mesh model.
  32401. * An instance shares the same properties and the same material than its model.
  32402. * Please make sure to call mesh.makeGeometryUnique() if you are calling createInstance on a previously cloned mesh.
  32403. * Only these properties of each instance can then be set individually :
  32404. * - position
  32405. * - rotation
  32406. * - rotationQuaternion
  32407. * - setPivotMatrix
  32408. * - scaling
  32409. *
  32410. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32411. * Warning : this method is not supported for Line mesh and LineSystem
  32412. */
  32413. Mesh.prototype.createInstance = function (name) {
  32414. return new BABYLON.InstancedMesh(name, this);
  32415. };
  32416. /**
  32417. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32418. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32419. * This method returns the Mesh.
  32420. */
  32421. Mesh.prototype.synchronizeInstances = function () {
  32422. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32423. var instance = this.instances[instanceIndex];
  32424. instance._syncSubMeshes();
  32425. }
  32426. return this;
  32427. };
  32428. /**
  32429. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32430. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32431. * This should be used together with the simplification to avoid disappearing triangles.
  32432. * Returns the Mesh.
  32433. * @param successCallback an optional success callback to be called after the optimization finished.
  32434. */
  32435. Mesh.prototype.optimizeIndices = function (successCallback) {
  32436. var _this = this;
  32437. var indices = this.getIndices();
  32438. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32439. if (!positions || !indices) {
  32440. return this;
  32441. }
  32442. var vectorPositions = new Array();
  32443. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32444. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32445. }
  32446. var dupes = new Array();
  32447. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32448. var realPos = vectorPositions.length - 1 - iteration;
  32449. var testedPosition = vectorPositions[realPos];
  32450. for (var j = 0; j < realPos; ++j) {
  32451. var againstPosition = vectorPositions[j];
  32452. if (testedPosition.equals(againstPosition)) {
  32453. dupes[realPos] = j;
  32454. break;
  32455. }
  32456. }
  32457. }, function () {
  32458. for (var i = 0; i < indices.length; ++i) {
  32459. indices[i] = dupes[indices[i]] || indices[i];
  32460. }
  32461. //indices are now reordered
  32462. var originalSubMeshes = _this.subMeshes.slice(0);
  32463. _this.setIndices(indices);
  32464. _this.subMeshes = originalSubMeshes;
  32465. if (successCallback) {
  32466. successCallback(_this);
  32467. }
  32468. });
  32469. return this;
  32470. };
  32471. Mesh.prototype.serialize = function (serializationObject) {
  32472. serializationObject.name = this.name;
  32473. serializationObject.id = this.id;
  32474. serializationObject.type = this.getClassName();
  32475. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32476. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32477. }
  32478. serializationObject.position = this.position.asArray();
  32479. if (this.rotationQuaternion) {
  32480. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32481. }
  32482. else if (this.rotation) {
  32483. serializationObject.rotation = this.rotation.asArray();
  32484. }
  32485. serializationObject.scaling = this.scaling.asArray();
  32486. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32487. serializationObject.isEnabled = this.isEnabled(false);
  32488. serializationObject.isVisible = this.isVisible;
  32489. serializationObject.infiniteDistance = this.infiniteDistance;
  32490. serializationObject.pickable = this.isPickable;
  32491. serializationObject.receiveShadows = this.receiveShadows;
  32492. serializationObject.billboardMode = this.billboardMode;
  32493. serializationObject.visibility = this.visibility;
  32494. serializationObject.checkCollisions = this.checkCollisions;
  32495. serializationObject.isBlocker = this.isBlocker;
  32496. // Parent
  32497. if (this.parent) {
  32498. serializationObject.parentId = this.parent.id;
  32499. }
  32500. // Geometry
  32501. serializationObject.isUnIndexed = this.isUnIndexed;
  32502. var geometry = this._geometry;
  32503. if (geometry) {
  32504. var geometryId = geometry.id;
  32505. serializationObject.geometryId = geometryId;
  32506. // SubMeshes
  32507. serializationObject.subMeshes = [];
  32508. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32509. var subMesh = this.subMeshes[subIndex];
  32510. serializationObject.subMeshes.push({
  32511. materialIndex: subMesh.materialIndex,
  32512. verticesStart: subMesh.verticesStart,
  32513. verticesCount: subMesh.verticesCount,
  32514. indexStart: subMesh.indexStart,
  32515. indexCount: subMesh.indexCount
  32516. });
  32517. }
  32518. }
  32519. // Material
  32520. if (this.material) {
  32521. serializationObject.materialId = this.material.id;
  32522. }
  32523. else {
  32524. this.material = null;
  32525. }
  32526. // Morph targets
  32527. if (this.morphTargetManager) {
  32528. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32529. }
  32530. // Skeleton
  32531. if (this.skeleton) {
  32532. serializationObject.skeletonId = this.skeleton.id;
  32533. }
  32534. // Physics
  32535. //TODO implement correct serialization for physics impostors.
  32536. var impostor = this.getPhysicsImpostor();
  32537. if (impostor) {
  32538. serializationObject.physicsMass = impostor.getParam("mass");
  32539. serializationObject.physicsFriction = impostor.getParam("friction");
  32540. serializationObject.physicsRestitution = impostor.getParam("mass");
  32541. serializationObject.physicsImpostor = impostor.type;
  32542. }
  32543. // Metadata
  32544. if (this.metadata) {
  32545. serializationObject.metadata = this.metadata;
  32546. }
  32547. // Instances
  32548. serializationObject.instances = [];
  32549. for (var index = 0; index < this.instances.length; index++) {
  32550. var instance = this.instances[index];
  32551. if (instance.doNotSerialize) {
  32552. continue;
  32553. }
  32554. var serializationInstance = {
  32555. name: instance.name,
  32556. id: instance.id,
  32557. position: instance.position.asArray(),
  32558. scaling: instance.scaling.asArray()
  32559. };
  32560. if (instance.parent) {
  32561. serializationInstance.parentId = instance.parent.id;
  32562. }
  32563. if (instance.rotationQuaternion) {
  32564. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32565. }
  32566. else if (instance.rotation) {
  32567. serializationInstance.rotation = instance.rotation.asArray();
  32568. }
  32569. serializationObject.instances.push(serializationInstance);
  32570. // Animations
  32571. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32572. serializationInstance.ranges = instance.serializeAnimationRanges();
  32573. }
  32574. //
  32575. // Animations
  32576. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32577. serializationObject.ranges = this.serializeAnimationRanges();
  32578. // Layer mask
  32579. serializationObject.layerMask = this.layerMask;
  32580. // Alpha
  32581. serializationObject.alphaIndex = this.alphaIndex;
  32582. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32583. // Overlay
  32584. serializationObject.overlayAlpha = this.overlayAlpha;
  32585. serializationObject.overlayColor = this.overlayColor.asArray();
  32586. serializationObject.renderOverlay = this.renderOverlay;
  32587. // Fog
  32588. serializationObject.applyFog = this.applyFog;
  32589. // Action Manager
  32590. if (this.actionManager) {
  32591. serializationObject.actions = this.actionManager.serialize(this.name);
  32592. }
  32593. };
  32594. /** @hidden */
  32595. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32596. if (!this.geometry) {
  32597. return;
  32598. }
  32599. this._markSubMeshesAsAttributesDirty();
  32600. var morphTargetManager = this._morphTargetManager;
  32601. if (morphTargetManager && morphTargetManager.vertexCount) {
  32602. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32603. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32604. this.morphTargetManager = null;
  32605. return;
  32606. }
  32607. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32608. var morphTarget = morphTargetManager.getActiveTarget(index);
  32609. var positions = morphTarget.getPositions();
  32610. if (!positions) {
  32611. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32612. return;
  32613. }
  32614. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32615. var normals = morphTarget.getNormals();
  32616. if (normals) {
  32617. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32618. }
  32619. var tangents = morphTarget.getTangents();
  32620. if (tangents) {
  32621. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32622. }
  32623. }
  32624. }
  32625. else {
  32626. var index = 0;
  32627. // Positions
  32628. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32629. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32630. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32631. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32632. }
  32633. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32634. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32635. }
  32636. index++;
  32637. }
  32638. }
  32639. };
  32640. // Statics
  32641. /**
  32642. * Returns a new Mesh object parsed from the source provided.
  32643. * The parameter `parsedMesh` is the source.
  32644. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32645. */
  32646. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32647. var mesh;
  32648. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32649. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32650. }
  32651. else {
  32652. mesh = new Mesh(parsedMesh.name, scene);
  32653. }
  32654. mesh.id = parsedMesh.id;
  32655. if (BABYLON.Tags) {
  32656. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32657. }
  32658. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32659. if (parsedMesh.metadata !== undefined) {
  32660. mesh.metadata = parsedMesh.metadata;
  32661. }
  32662. if (parsedMesh.rotationQuaternion) {
  32663. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32664. }
  32665. else if (parsedMesh.rotation) {
  32666. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32667. }
  32668. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32669. if (parsedMesh.localMatrix) {
  32670. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32671. }
  32672. else if (parsedMesh.pivotMatrix) {
  32673. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32674. }
  32675. mesh.setEnabled(parsedMesh.isEnabled);
  32676. mesh.isVisible = parsedMesh.isVisible;
  32677. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32678. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32679. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32680. if (parsedMesh.applyFog !== undefined) {
  32681. mesh.applyFog = parsedMesh.applyFog;
  32682. }
  32683. if (parsedMesh.pickable !== undefined) {
  32684. mesh.isPickable = parsedMesh.pickable;
  32685. }
  32686. if (parsedMesh.alphaIndex !== undefined) {
  32687. mesh.alphaIndex = parsedMesh.alphaIndex;
  32688. }
  32689. mesh.receiveShadows = parsedMesh.receiveShadows;
  32690. mesh.billboardMode = parsedMesh.billboardMode;
  32691. if (parsedMesh.visibility !== undefined) {
  32692. mesh.visibility = parsedMesh.visibility;
  32693. }
  32694. mesh.checkCollisions = parsedMesh.checkCollisions;
  32695. if (parsedMesh.isBlocker !== undefined) {
  32696. mesh.isBlocker = parsedMesh.isBlocker;
  32697. }
  32698. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32699. // freezeWorldMatrix
  32700. if (parsedMesh.freezeWorldMatrix) {
  32701. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32702. }
  32703. // Parent
  32704. if (parsedMesh.parentId) {
  32705. mesh._waitingParentId = parsedMesh.parentId;
  32706. }
  32707. // Actions
  32708. if (parsedMesh.actions !== undefined) {
  32709. mesh._waitingActions = parsedMesh.actions;
  32710. }
  32711. // Overlay
  32712. if (parsedMesh.overlayAlpha !== undefined) {
  32713. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32714. }
  32715. if (parsedMesh.overlayColor !== undefined) {
  32716. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32717. }
  32718. if (parsedMesh.renderOverlay !== undefined) {
  32719. mesh.renderOverlay = parsedMesh.renderOverlay;
  32720. }
  32721. // Geometry
  32722. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32723. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32724. if (parsedMesh.delayLoadingFile) {
  32725. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32726. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32727. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32728. if (parsedMesh._binaryInfo) {
  32729. mesh._binaryInfo = parsedMesh._binaryInfo;
  32730. }
  32731. mesh._delayInfo = [];
  32732. if (parsedMesh.hasUVs) {
  32733. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32734. }
  32735. if (parsedMesh.hasUVs2) {
  32736. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32737. }
  32738. if (parsedMesh.hasUVs3) {
  32739. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32740. }
  32741. if (parsedMesh.hasUVs4) {
  32742. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32743. }
  32744. if (parsedMesh.hasUVs5) {
  32745. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32746. }
  32747. if (parsedMesh.hasUVs6) {
  32748. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32749. }
  32750. if (parsedMesh.hasColors) {
  32751. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32752. }
  32753. if (parsedMesh.hasMatricesIndices) {
  32754. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32755. }
  32756. if (parsedMesh.hasMatricesWeights) {
  32757. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32758. }
  32759. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32760. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32761. mesh._checkDelayState();
  32762. }
  32763. }
  32764. else {
  32765. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32766. }
  32767. // Material
  32768. if (parsedMesh.materialId) {
  32769. mesh.setMaterialByID(parsedMesh.materialId);
  32770. }
  32771. else {
  32772. mesh.material = null;
  32773. }
  32774. // Morph targets
  32775. if (parsedMesh.morphTargetManagerId > -1) {
  32776. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32777. }
  32778. // Skeleton
  32779. if (parsedMesh.skeletonId > -1) {
  32780. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32781. if (parsedMesh.numBoneInfluencers) {
  32782. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  32783. }
  32784. }
  32785. // Animations
  32786. if (parsedMesh.animations) {
  32787. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32788. var parsedAnimation = parsedMesh.animations[animationIndex];
  32789. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32790. }
  32791. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  32792. }
  32793. if (parsedMesh.autoAnimate) {
  32794. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  32795. }
  32796. // Layer Mask
  32797. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  32798. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  32799. }
  32800. else {
  32801. mesh.layerMask = 0x0FFFFFFF;
  32802. }
  32803. // Physics
  32804. if (parsedMesh.physicsImpostor) {
  32805. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  32806. mass: parsedMesh.physicsMass,
  32807. friction: parsedMesh.physicsFriction,
  32808. restitution: parsedMesh.physicsRestitution
  32809. }, scene);
  32810. }
  32811. // Instances
  32812. if (parsedMesh.instances) {
  32813. for (var index = 0; index < parsedMesh.instances.length; index++) {
  32814. var parsedInstance = parsedMesh.instances[index];
  32815. var instance = mesh.createInstance(parsedInstance.name);
  32816. if (parsedInstance.id) {
  32817. instance.id = parsedInstance.id;
  32818. }
  32819. if (BABYLON.Tags) {
  32820. if (parsedInstance.tags) {
  32821. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  32822. }
  32823. else {
  32824. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  32825. }
  32826. }
  32827. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  32828. if (parsedInstance.parentId) {
  32829. instance._waitingParentId = parsedInstance.parentId;
  32830. }
  32831. if (parsedInstance.rotationQuaternion) {
  32832. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  32833. }
  32834. else if (parsedInstance.rotation) {
  32835. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  32836. }
  32837. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  32838. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  32839. instance.checkCollisions = parsedInstance.checkCollisions;
  32840. }
  32841. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  32842. instance.isPickable = parsedInstance.pickable;
  32843. }
  32844. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  32845. instance.showBoundingBox = parsedInstance.showBoundingBox;
  32846. }
  32847. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  32848. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  32849. }
  32850. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  32851. instance.alphaIndex = parsedInstance.alphaIndex;
  32852. }
  32853. // Physics
  32854. if (parsedInstance.physicsImpostor) {
  32855. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  32856. mass: parsedInstance.physicsMass,
  32857. friction: parsedInstance.physicsFriction,
  32858. restitution: parsedInstance.physicsRestitution
  32859. }, scene);
  32860. }
  32861. // Animation
  32862. if (parsedInstance.animations) {
  32863. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  32864. parsedAnimation = parsedInstance.animations[animationIndex];
  32865. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32866. }
  32867. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  32868. if (parsedInstance.autoAnimate) {
  32869. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  32870. }
  32871. }
  32872. }
  32873. }
  32874. return mesh;
  32875. };
  32876. /**
  32877. * Creates a ribbon mesh.
  32878. * Please consider using the same method from the MeshBuilder class instead.
  32879. * The ribbon is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  32880. *
  32881. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  32882. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  32883. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  32884. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  32885. * 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.
  32886. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  32887. * 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
  32888. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32889. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32890. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32891. */
  32892. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  32893. if (closeArray === void 0) { closeArray = false; }
  32894. if (updatable === void 0) { updatable = false; }
  32895. return BABYLON.MeshBuilder.CreateRibbon(name, {
  32896. pathArray: pathArray,
  32897. closeArray: closeArray,
  32898. closePath: closePath,
  32899. offset: offset,
  32900. updatable: updatable,
  32901. sideOrientation: sideOrientation,
  32902. instance: instance
  32903. }, scene);
  32904. };
  32905. /**
  32906. * Creates a plane polygonal mesh. By default, this is a disc.
  32907. * Please consider using the same method from the MeshBuilder class instead.
  32908. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  32909. * 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.
  32910. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32911. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32912. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32913. */
  32914. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  32915. if (scene === void 0) { scene = null; }
  32916. var options = {
  32917. radius: radius,
  32918. tessellation: tessellation,
  32919. sideOrientation: sideOrientation,
  32920. updatable: updatable
  32921. };
  32922. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  32923. };
  32924. /**
  32925. * Creates a box mesh.
  32926. * Please consider using the same method from the MeshBuilder class instead.
  32927. * The parameter `size` sets the size (float) of each box side (default 1).
  32928. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32929. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32930. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32931. */
  32932. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  32933. if (scene === void 0) { scene = null; }
  32934. var options = {
  32935. size: size,
  32936. sideOrientation: sideOrientation,
  32937. updatable: updatable
  32938. };
  32939. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  32940. };
  32941. /**
  32942. * Creates a sphere mesh.
  32943. * Please consider using the same method from the MeshBuilder class instead.
  32944. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  32945. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  32946. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32947. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32948. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32949. */
  32950. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  32951. var options = {
  32952. segments: segments,
  32953. diameterX: diameter,
  32954. diameterY: diameter,
  32955. diameterZ: diameter,
  32956. sideOrientation: sideOrientation,
  32957. updatable: updatable
  32958. };
  32959. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  32960. };
  32961. /**
  32962. * Creates a cylinder or a cone mesh.
  32963. * Please consider using the same method from the MeshBuilder class instead.
  32964. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  32965. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  32966. * 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.
  32967. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  32968. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  32969. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32970. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  32971. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32972. */
  32973. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  32974. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  32975. if (scene !== undefined) {
  32976. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  32977. updatable = scene;
  32978. }
  32979. scene = subdivisions;
  32980. subdivisions = 1;
  32981. }
  32982. var options = {
  32983. height: height,
  32984. diameterTop: diameterTop,
  32985. diameterBottom: diameterBottom,
  32986. tessellation: tessellation,
  32987. subdivisions: subdivisions,
  32988. sideOrientation: sideOrientation,
  32989. updatable: updatable
  32990. };
  32991. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  32992. };
  32993. // Torus (Code from SharpDX.org)
  32994. /**
  32995. * Creates a torus mesh.
  32996. * Please consider using the same method from the MeshBuilder class instead.
  32997. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  32998. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  32999. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33000. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33001. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33002. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33003. */
  33004. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33005. var options = {
  33006. diameter: diameter,
  33007. thickness: thickness,
  33008. tessellation: tessellation,
  33009. sideOrientation: sideOrientation,
  33010. updatable: updatable
  33011. };
  33012. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33013. };
  33014. /**
  33015. * Creates a torus knot mesh.
  33016. * Please consider using the same method from the MeshBuilder class instead.
  33017. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33018. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33019. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33020. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33021. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33022. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33023. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33024. */
  33025. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33026. var options = {
  33027. radius: radius,
  33028. tube: tube,
  33029. radialSegments: radialSegments,
  33030. tubularSegments: tubularSegments,
  33031. p: p,
  33032. q: q,
  33033. sideOrientation: sideOrientation,
  33034. updatable: updatable
  33035. };
  33036. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33037. };
  33038. /**
  33039. * Creates a line mesh.
  33040. * Please consider using the same method from the MeshBuilder class instead.
  33041. * 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.
  33042. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33043. * The parameter `points` is an array successive Vector3.
  33044. * 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
  33045. * When updating an instance, remember that only point positions can change, not the number of points.
  33046. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33047. */
  33048. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33049. if (scene === void 0) { scene = null; }
  33050. if (updatable === void 0) { updatable = false; }
  33051. if (instance === void 0) { instance = null; }
  33052. var options = {
  33053. points: points,
  33054. updatable: updatable,
  33055. instance: instance
  33056. };
  33057. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33058. };
  33059. /**
  33060. * Creates a dashed line mesh.
  33061. * Please consider using the same method from the MeshBuilder class instead.
  33062. * 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.
  33063. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33064. * The parameter `points` is an array successive Vector3.
  33065. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33066. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33067. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33068. * 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
  33069. * When updating an instance, remember that only point positions can change, not the number of points.
  33070. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33071. */
  33072. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33073. if (scene === void 0) { scene = null; }
  33074. var options = {
  33075. points: points,
  33076. dashSize: dashSize,
  33077. gapSize: gapSize,
  33078. dashNb: dashNb,
  33079. updatable: updatable,
  33080. instance: instance
  33081. };
  33082. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33083. };
  33084. /**
  33085. * Creates a polygon mesh.
  33086. * Please consider using the same method from the MeshBuilder class instead.
  33087. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33088. * 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.
  33089. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33090. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33091. * Remember you can only change the shape positions, not their number when updating a polygon.
  33092. */
  33093. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33094. var options = {
  33095. shape: shape,
  33096. holes: holes,
  33097. updatable: updatable,
  33098. sideOrientation: sideOrientation
  33099. };
  33100. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33101. };
  33102. /**
  33103. * Creates an extruded polygon mesh, with depth in the Y direction.
  33104. * Please consider using the same method from the MeshBuilder class instead.
  33105. */
  33106. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33107. var options = {
  33108. shape: shape,
  33109. holes: holes,
  33110. depth: depth,
  33111. updatable: updatable,
  33112. sideOrientation: sideOrientation
  33113. };
  33114. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33115. };
  33116. /**
  33117. * Creates an extruded shape mesh.
  33118. * The extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33119. * Please consider using the same method from the MeshBuilder class instead.
  33120. *
  33121. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33122. * 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
  33123. * extruded along the Z axis.
  33124. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33125. * 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.
  33126. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33127. * 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
  33128. * 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
  33129. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33130. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33131. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33132. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33133. */
  33134. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33135. if (scene === void 0) { scene = null; }
  33136. var options = {
  33137. shape: shape,
  33138. path: path,
  33139. scale: scale,
  33140. rotation: rotation,
  33141. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33142. sideOrientation: sideOrientation,
  33143. instance: instance,
  33144. updatable: updatable
  33145. };
  33146. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33147. };
  33148. /**
  33149. * Creates an custom extruded shape mesh.
  33150. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33151. * Please consider using the same method from the MeshBuilder class instead.
  33152. *
  33153. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33154. * 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
  33155. * extruded along the Z axis.
  33156. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33157. * 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
  33158. * and the distance of this point from the begining of the path :
  33159. * ```javascript
  33160. * var rotationFunction = function(i, distance) {
  33161. * // do things
  33162. * return rotationValue; }
  33163. * ```
  33164. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33165. * 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
  33166. * and the distance of this point from the begining of the path :
  33167. * ```javascript
  33168. * var scaleFunction = function(i, distance) {
  33169. * // do things
  33170. * return scaleValue;}
  33171. * ```
  33172. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33173. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33174. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33175. * 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
  33176. * 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
  33177. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33178. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33179. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33180. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33181. */
  33182. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33183. var options = {
  33184. shape: shape,
  33185. path: path,
  33186. scaleFunction: scaleFunction,
  33187. rotationFunction: rotationFunction,
  33188. ribbonCloseArray: ribbonCloseArray,
  33189. ribbonClosePath: ribbonClosePath,
  33190. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33191. sideOrientation: sideOrientation,
  33192. instance: instance,
  33193. updatable: updatable
  33194. };
  33195. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33196. };
  33197. /**
  33198. * Creates lathe mesh.
  33199. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33200. * Please consider using the same method from the MeshBuilder class instead.
  33201. * 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
  33202. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33203. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33204. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33205. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33206. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33207. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33208. */
  33209. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33210. var options = {
  33211. shape: shape,
  33212. radius: radius,
  33213. tessellation: tessellation,
  33214. sideOrientation: sideOrientation,
  33215. updatable: updatable
  33216. };
  33217. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33218. };
  33219. /**
  33220. * Creates a plane mesh.
  33221. * Please consider using the same method from the MeshBuilder class instead.
  33222. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33223. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33224. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33225. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33226. */
  33227. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33228. var options = {
  33229. size: size,
  33230. width: size,
  33231. height: size,
  33232. sideOrientation: sideOrientation,
  33233. updatable: updatable
  33234. };
  33235. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33236. };
  33237. /**
  33238. * Creates a ground mesh.
  33239. * Please consider using the same method from the MeshBuilder class instead.
  33240. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33241. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33242. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33243. */
  33244. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33245. var options = {
  33246. width: width,
  33247. height: height,
  33248. subdivisions: subdivisions,
  33249. updatable: updatable
  33250. };
  33251. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33252. };
  33253. /**
  33254. * Creates a tiled ground mesh.
  33255. * Please consider using the same method from the MeshBuilder class instead.
  33256. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33257. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33258. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33259. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33260. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33261. * numbers of subdivisions on the ground width and height of each tile.
  33262. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33263. */
  33264. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33265. var options = {
  33266. xmin: xmin,
  33267. zmin: zmin,
  33268. xmax: xmax,
  33269. zmax: zmax,
  33270. subdivisions: subdivisions,
  33271. precision: precision,
  33272. updatable: updatable
  33273. };
  33274. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33275. };
  33276. /**
  33277. * Creates a ground mesh from a height map.
  33278. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33279. * Please consider using the same method from the MeshBuilder class instead.
  33280. * @param url sets the URL of the height map image resource.
  33281. * @param width (positive float, default 10) set the ground width size.
  33282. * @param height (positive float, default 10) set the ground height size.
  33283. * @param subdivisions (positive integer, default 1) sets the number of subdivision per side.
  33284. * @param minHeight (float, default 0) is the minimum altitude on the ground.
  33285. * @param maxHeight (float, default 1) is the maximum altitude on the ground.
  33286. * @param onReady is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  33287. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible).
  33288. * This function is passed the newly built mesh :
  33289. * ```javascript
  33290. * function(mesh) { // do things
  33291. * return; }
  33292. * ```
  33293. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33294. */
  33295. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  33296. var options = {
  33297. width: width,
  33298. height: height,
  33299. subdivisions: subdivisions,
  33300. minHeight: minHeight,
  33301. maxHeight: maxHeight,
  33302. updatable: updatable,
  33303. onReady: onReady,
  33304. alphaFilter: alphaFilter
  33305. };
  33306. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33307. };
  33308. /**
  33309. * Creates a tube mesh.
  33310. * The tube is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33311. * Please consider using the same method from the MeshBuilder class instead.
  33312. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33313. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33314. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33315. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33316. * 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.
  33317. * It must return a radius value (positive float) :
  33318. * ```javascript
  33319. * var radiusFunction = function(i, distance) {
  33320. * // do things
  33321. * return radius; }
  33322. * ```
  33323. * 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
  33324. * 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
  33325. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33326. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33327. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33328. */
  33329. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33330. var options = {
  33331. path: path,
  33332. radius: radius,
  33333. tessellation: tessellation,
  33334. radiusFunction: radiusFunction,
  33335. arc: 1,
  33336. cap: cap,
  33337. updatable: updatable,
  33338. sideOrientation: sideOrientation,
  33339. instance: instance
  33340. };
  33341. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33342. };
  33343. /**
  33344. * Creates a polyhedron mesh.
  33345. * Please consider using the same method from the MeshBuilder class instead.
  33346. * 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
  33347. * to choose the wanted type.
  33348. * The parameter `size` (positive float, default 1) sets the polygon size.
  33349. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33350. * 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`.
  33351. * 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
  33352. * 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)`).
  33353. * 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
  33354. * 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.
  33355. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33356. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33357. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33358. */
  33359. Mesh.CreatePolyhedron = function (name, options, scene) {
  33360. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33361. };
  33362. /**
  33363. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33364. * Please consider using the same method from the MeshBuilder class instead.
  33365. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33366. * 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`).
  33367. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33368. * 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.
  33369. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33370. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33371. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33372. */
  33373. Mesh.CreateIcoSphere = function (name, options, scene) {
  33374. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33375. };
  33376. /**
  33377. * Creates a decal mesh.
  33378. * Please consider using the same method from the MeshBuilder class instead.
  33379. * 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.
  33380. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33381. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33382. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33383. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33384. */
  33385. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33386. var options = {
  33387. position: position,
  33388. normal: normal,
  33389. size: size,
  33390. angle: angle
  33391. };
  33392. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33393. };
  33394. // Skeletons
  33395. /**
  33396. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33397. */
  33398. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33399. if (!this._sourcePositions) {
  33400. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33401. if (!source) {
  33402. return this._sourcePositions;
  33403. }
  33404. this._sourcePositions = new Float32Array(source);
  33405. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33406. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33407. }
  33408. }
  33409. return this._sourcePositions;
  33410. };
  33411. /**
  33412. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33413. */
  33414. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33415. if (!this._sourceNormals) {
  33416. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33417. if (!source) {
  33418. return this._sourceNormals;
  33419. }
  33420. this._sourceNormals = new Float32Array(source);
  33421. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33422. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33423. }
  33424. }
  33425. return this._sourceNormals;
  33426. };
  33427. /**
  33428. * Updates the vertex buffer by applying transformation from the bones.
  33429. * Returns the Mesh.
  33430. *
  33431. * @param {skeleton} skeleton to apply
  33432. */
  33433. Mesh.prototype.applySkeleton = function (skeleton) {
  33434. if (!this.geometry) {
  33435. return this;
  33436. }
  33437. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  33438. return this;
  33439. }
  33440. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  33441. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33442. return this;
  33443. }
  33444. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33445. return this;
  33446. }
  33447. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33448. return this;
  33449. }
  33450. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33451. return this;
  33452. }
  33453. if (!this._sourcePositions) {
  33454. var submeshes = this.subMeshes.slice();
  33455. this.setPositionsForCPUSkinning();
  33456. this.subMeshes = submeshes;
  33457. }
  33458. if (!this._sourceNormals) {
  33459. this.setNormalsForCPUSkinning();
  33460. }
  33461. // positionsData checks for not being Float32Array will only pass at most once
  33462. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33463. if (!positionsData) {
  33464. return this;
  33465. }
  33466. if (!(positionsData instanceof Float32Array)) {
  33467. positionsData = new Float32Array(positionsData);
  33468. }
  33469. // normalsData checks for not being Float32Array will only pass at most once
  33470. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33471. if (!normalsData) {
  33472. return this;
  33473. }
  33474. if (!(normalsData instanceof Float32Array)) {
  33475. normalsData = new Float32Array(normalsData);
  33476. }
  33477. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33478. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33479. if (!matricesWeightsData || !matricesIndicesData) {
  33480. return this;
  33481. }
  33482. var needExtras = this.numBoneInfluencers > 4;
  33483. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33484. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33485. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33486. var tempVector3 = BABYLON.Vector3.Zero();
  33487. var finalMatrix = new BABYLON.Matrix();
  33488. var tempMatrix = new BABYLON.Matrix();
  33489. var matWeightIdx = 0;
  33490. var inf;
  33491. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33492. var weight;
  33493. for (inf = 0; inf < 4; inf++) {
  33494. weight = matricesWeightsData[matWeightIdx + inf];
  33495. if (weight > 0) {
  33496. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33497. finalMatrix.addToSelf(tempMatrix);
  33498. }
  33499. }
  33500. if (needExtras) {
  33501. for (inf = 0; inf < 4; inf++) {
  33502. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33503. if (weight > 0) {
  33504. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33505. finalMatrix.addToSelf(tempMatrix);
  33506. }
  33507. }
  33508. }
  33509. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33510. tempVector3.toArray(positionsData, index);
  33511. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33512. tempVector3.toArray(normalsData, index);
  33513. finalMatrix.reset();
  33514. }
  33515. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33516. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33517. return this;
  33518. };
  33519. // Tools
  33520. /**
  33521. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33522. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33523. */
  33524. Mesh.MinMax = function (meshes) {
  33525. var minVector = null;
  33526. var maxVector = null;
  33527. meshes.forEach(function (mesh, index, array) {
  33528. var boundingInfo = mesh.getBoundingInfo();
  33529. var boundingBox = boundingInfo.boundingBox;
  33530. if (!minVector || !maxVector) {
  33531. minVector = boundingBox.minimumWorld;
  33532. maxVector = boundingBox.maximumWorld;
  33533. }
  33534. else {
  33535. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33536. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33537. }
  33538. });
  33539. if (!minVector || !maxVector) {
  33540. return {
  33541. min: BABYLON.Vector3.Zero(),
  33542. max: BABYLON.Vector3.Zero()
  33543. };
  33544. }
  33545. return {
  33546. min: minVector,
  33547. max: maxVector
  33548. };
  33549. };
  33550. /**
  33551. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33552. */
  33553. Mesh.Center = function (meshesOrMinMaxVector) {
  33554. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33555. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33556. };
  33557. /**
  33558. * Merge the array of meshes into a single mesh for performance reasons.
  33559. * @param meshes - The vertices source. They should all be of the same material. Entries can empty
  33560. * @param disposeSource - When true (default), dispose of the vertices from the source meshes
  33561. * @param allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33562. * @param meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33563. * @param subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33564. */
  33565. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33566. if (disposeSource === void 0) { disposeSource = true; }
  33567. var index;
  33568. if (!allow32BitsIndices) {
  33569. var totalVertices = 0;
  33570. // Counting vertices
  33571. for (index = 0; index < meshes.length; index++) {
  33572. if (meshes[index]) {
  33573. totalVertices += meshes[index].getTotalVertices();
  33574. if (totalVertices > 65536) {
  33575. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33576. return null;
  33577. }
  33578. }
  33579. }
  33580. }
  33581. // Merge
  33582. var vertexData = null;
  33583. var otherVertexData;
  33584. var indiceArray = new Array();
  33585. var source = null;
  33586. for (index = 0; index < meshes.length; index++) {
  33587. if (meshes[index]) {
  33588. var wm = meshes[index].computeWorldMatrix(true);
  33589. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33590. otherVertexData.transform(wm);
  33591. if (vertexData) {
  33592. vertexData.merge(otherVertexData, allow32BitsIndices);
  33593. }
  33594. else {
  33595. vertexData = otherVertexData;
  33596. source = meshes[index];
  33597. }
  33598. if (subdivideWithSubMeshes) {
  33599. indiceArray.push(meshes[index].getTotalIndices());
  33600. }
  33601. }
  33602. }
  33603. source = source;
  33604. if (!meshSubclass) {
  33605. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33606. }
  33607. vertexData.applyToMesh(meshSubclass);
  33608. // Setting properties
  33609. meshSubclass.material = source.material;
  33610. meshSubclass.checkCollisions = source.checkCollisions;
  33611. // Cleaning
  33612. if (disposeSource) {
  33613. for (index = 0; index < meshes.length; index++) {
  33614. if (meshes[index]) {
  33615. meshes[index].dispose();
  33616. }
  33617. }
  33618. }
  33619. // Subdivide
  33620. if (subdivideWithSubMeshes) {
  33621. //-- removal of global submesh
  33622. meshSubclass.releaseSubMeshes();
  33623. index = 0;
  33624. var offset = 0;
  33625. //-- apply subdivision according to index table
  33626. while (index < indiceArray.length) {
  33627. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33628. offset += indiceArray[index];
  33629. index++;
  33630. }
  33631. }
  33632. return meshSubclass;
  33633. };
  33634. // Consts
  33635. Mesh._FRONTSIDE = 0;
  33636. Mesh._BACKSIDE = 1;
  33637. Mesh._DOUBLESIDE = 2;
  33638. Mesh._DEFAULTSIDE = 0;
  33639. Mesh._NO_CAP = 0;
  33640. Mesh._CAP_START = 1;
  33641. Mesh._CAP_END = 2;
  33642. Mesh._CAP_ALL = 3;
  33643. return Mesh;
  33644. }(BABYLON.AbstractMesh));
  33645. BABYLON.Mesh = Mesh;
  33646. })(BABYLON || (BABYLON = {}));
  33647. //# sourceMappingURL=babylon.mesh.js.map
  33648. var BABYLON;
  33649. (function (BABYLON) {
  33650. var BaseSubMesh = /** @class */ (function () {
  33651. function BaseSubMesh() {
  33652. }
  33653. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33654. get: function () {
  33655. return this._materialEffect;
  33656. },
  33657. enumerable: true,
  33658. configurable: true
  33659. });
  33660. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33661. if (defines === void 0) { defines = null; }
  33662. if (this._materialEffect === effect) {
  33663. if (!effect) {
  33664. this._materialDefines = null;
  33665. }
  33666. return;
  33667. }
  33668. this._materialDefines = defines;
  33669. this._materialEffect = effect;
  33670. };
  33671. return BaseSubMesh;
  33672. }());
  33673. BABYLON.BaseSubMesh = BaseSubMesh;
  33674. var SubMesh = /** @class */ (function (_super) {
  33675. __extends(SubMesh, _super);
  33676. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33677. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33678. var _this = _super.call(this) || this;
  33679. _this.materialIndex = materialIndex;
  33680. _this.verticesStart = verticesStart;
  33681. _this.verticesCount = verticesCount;
  33682. _this.indexStart = indexStart;
  33683. _this.indexCount = indexCount;
  33684. /** @hidden */
  33685. _this._renderId = 0;
  33686. _this._mesh = mesh;
  33687. _this._renderingMesh = renderingMesh || mesh;
  33688. mesh.subMeshes.push(_this);
  33689. _this._trianglePlanes = [];
  33690. _this._id = mesh.subMeshes.length - 1;
  33691. if (createBoundingBox) {
  33692. _this.refreshBoundingInfo();
  33693. mesh.computeWorldMatrix(true);
  33694. }
  33695. return _this;
  33696. }
  33697. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33698. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33699. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33700. };
  33701. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33702. get: function () {
  33703. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  33704. },
  33705. enumerable: true,
  33706. configurable: true
  33707. });
  33708. /**
  33709. * Returns the submesh BoudingInfo object.
  33710. */
  33711. SubMesh.prototype.getBoundingInfo = function () {
  33712. if (this.IsGlobal) {
  33713. return this._mesh.getBoundingInfo();
  33714. }
  33715. return this._boundingInfo;
  33716. };
  33717. /**
  33718. * Sets the submesh BoundingInfo.
  33719. * Return the SubMesh.
  33720. */
  33721. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33722. this._boundingInfo = boundingInfo;
  33723. return this;
  33724. };
  33725. /**
  33726. * Returns the mesh of the current submesh.
  33727. */
  33728. SubMesh.prototype.getMesh = function () {
  33729. return this._mesh;
  33730. };
  33731. /**
  33732. * Returns the rendering mesh of the submesh.
  33733. */
  33734. SubMesh.prototype.getRenderingMesh = function () {
  33735. return this._renderingMesh;
  33736. };
  33737. /**
  33738. * Returns the submesh material.
  33739. */
  33740. SubMesh.prototype.getMaterial = function () {
  33741. var rootMaterial = this._renderingMesh.material;
  33742. if (rootMaterial === null || rootMaterial === undefined) {
  33743. return this._mesh.getScene().defaultMaterial;
  33744. }
  33745. else if (rootMaterial.getSubMaterial) {
  33746. var multiMaterial = rootMaterial;
  33747. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33748. if (this._currentMaterial !== effectiveMaterial) {
  33749. this._currentMaterial = effectiveMaterial;
  33750. this._materialDefines = null;
  33751. }
  33752. return effectiveMaterial;
  33753. }
  33754. return rootMaterial;
  33755. };
  33756. // Methods
  33757. /**
  33758. * Sets a new updated BoundingInfo object to the submesh.
  33759. * Returns the SubMesh.
  33760. */
  33761. SubMesh.prototype.refreshBoundingInfo = function () {
  33762. this._lastColliderWorldVertices = null;
  33763. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33764. return this;
  33765. }
  33766. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33767. if (!data) {
  33768. this._boundingInfo = this._mesh.getBoundingInfo();
  33769. return this;
  33770. }
  33771. var indices = this._renderingMesh.getIndices();
  33772. var extend;
  33773. //is this the only submesh?
  33774. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33775. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33776. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33777. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33778. }
  33779. else {
  33780. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33781. }
  33782. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33783. return this;
  33784. };
  33785. /** @hidden */
  33786. SubMesh.prototype._checkCollision = function (collider) {
  33787. var boundingInfo = this.getBoundingInfo();
  33788. return boundingInfo._checkCollision(collider);
  33789. };
  33790. /**
  33791. * Updates the submesh BoundingInfo.
  33792. * Returns the Submesh.
  33793. */
  33794. SubMesh.prototype.updateBoundingInfo = function (world) {
  33795. var boundingInfo = this.getBoundingInfo();
  33796. if (!boundingInfo) {
  33797. this.refreshBoundingInfo();
  33798. boundingInfo = this.getBoundingInfo();
  33799. }
  33800. boundingInfo.update(world);
  33801. return this;
  33802. };
  33803. /**
  33804. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33805. * Boolean returned.
  33806. */
  33807. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33808. var boundingInfo = this.getBoundingInfo();
  33809. if (!boundingInfo) {
  33810. return false;
  33811. }
  33812. return boundingInfo.isInFrustum(frustumPlanes);
  33813. };
  33814. /**
  33815. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  33816. * Boolean returned.
  33817. */
  33818. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  33819. var boundingInfo = this.getBoundingInfo();
  33820. if (!boundingInfo) {
  33821. return false;
  33822. }
  33823. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  33824. };
  33825. /**
  33826. * Renders the submesh.
  33827. * Returns it.
  33828. */
  33829. SubMesh.prototype.render = function (enableAlphaMode) {
  33830. this._renderingMesh.render(this, enableAlphaMode);
  33831. return this;
  33832. };
  33833. /**
  33834. * Returns a new Index Buffer.
  33835. * Type returned : WebGLBuffer.
  33836. */
  33837. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  33838. if (!this._linesIndexBuffer) {
  33839. var linesIndices = [];
  33840. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33841. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  33842. }
  33843. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  33844. this.linesIndexCount = linesIndices.length;
  33845. }
  33846. return this._linesIndexBuffer;
  33847. };
  33848. /**
  33849. * True is the passed Ray intersects the submesh bounding box.
  33850. * Boolean returned.
  33851. */
  33852. SubMesh.prototype.canIntersects = function (ray) {
  33853. var boundingInfo = this.getBoundingInfo();
  33854. if (!boundingInfo) {
  33855. return false;
  33856. }
  33857. return ray.intersectsBox(boundingInfo.boundingBox);
  33858. };
  33859. /**
  33860. * Returns an object IntersectionInfo.
  33861. */
  33862. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  33863. var intersectInfo = null;
  33864. var material = this.getMaterial();
  33865. if (!material) {
  33866. return null;
  33867. }
  33868. switch (material.fillMode) {
  33869. case BABYLON.Material.PointListDrawMode:
  33870. case BABYLON.Material.LineListDrawMode:
  33871. case BABYLON.Material.LineLoopDrawMode:
  33872. case BABYLON.Material.LineStripDrawMode:
  33873. case BABYLON.Material.TriangleFanDrawMode:
  33874. case BABYLON.Material.TriangleStripDrawMode:
  33875. return null;
  33876. }
  33877. // LineMesh first as it's also a Mesh...
  33878. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  33879. var lineMesh = this._mesh;
  33880. // Line test
  33881. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  33882. var p0 = positions[indices[index]];
  33883. var p1 = positions[indices[index + 1]];
  33884. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  33885. if (length < 0) {
  33886. continue;
  33887. }
  33888. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  33889. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  33890. if (fastCheck) {
  33891. break;
  33892. }
  33893. }
  33894. }
  33895. }
  33896. else {
  33897. // Triangles test
  33898. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33899. var p0 = positions[indices[index]];
  33900. var p1 = positions[indices[index + 1]];
  33901. var p2 = positions[indices[index + 2]];
  33902. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  33903. if (currentIntersectInfo) {
  33904. if (currentIntersectInfo.distance < 0) {
  33905. continue;
  33906. }
  33907. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  33908. intersectInfo = currentIntersectInfo;
  33909. intersectInfo.faceId = index / 3;
  33910. if (fastCheck) {
  33911. break;
  33912. }
  33913. }
  33914. }
  33915. }
  33916. }
  33917. return intersectInfo;
  33918. };
  33919. /** @hidden */
  33920. SubMesh.prototype._rebuild = function () {
  33921. if (this._linesIndexBuffer) {
  33922. this._linesIndexBuffer = null;
  33923. }
  33924. };
  33925. // Clone
  33926. /**
  33927. * Creates a new Submesh from the passed Mesh.
  33928. */
  33929. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  33930. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  33931. if (!this.IsGlobal) {
  33932. var boundingInfo = this.getBoundingInfo();
  33933. if (!boundingInfo) {
  33934. return result;
  33935. }
  33936. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  33937. }
  33938. return result;
  33939. };
  33940. // Dispose
  33941. /**
  33942. * Disposes the Submesh.
  33943. * Returns nothing.
  33944. */
  33945. SubMesh.prototype.dispose = function () {
  33946. if (this._linesIndexBuffer) {
  33947. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  33948. this._linesIndexBuffer = null;
  33949. }
  33950. // Remove from mesh
  33951. var index = this._mesh.subMeshes.indexOf(this);
  33952. this._mesh.subMeshes.splice(index, 1);
  33953. };
  33954. // Statics
  33955. /**
  33956. * Creates a new Submesh from the passed parameters :
  33957. * - materialIndex (integer) : the index of the main mesh material.
  33958. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  33959. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  33960. * - mesh (Mesh) : the main mesh to create the submesh from.
  33961. * - renderingMesh (optional Mesh) : rendering mesh.
  33962. */
  33963. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  33964. var minVertexIndex = Number.MAX_VALUE;
  33965. var maxVertexIndex = -Number.MAX_VALUE;
  33966. renderingMesh = (renderingMesh || mesh);
  33967. var indices = renderingMesh.getIndices();
  33968. for (var index = startIndex; index < startIndex + indexCount; index++) {
  33969. var vertexIndex = indices[index];
  33970. if (vertexIndex < minVertexIndex)
  33971. minVertexIndex = vertexIndex;
  33972. if (vertexIndex > maxVertexIndex)
  33973. maxVertexIndex = vertexIndex;
  33974. }
  33975. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  33976. };
  33977. return SubMesh;
  33978. }(BaseSubMesh));
  33979. BABYLON.SubMesh = SubMesh;
  33980. })(BABYLON || (BABYLON = {}));
  33981. //# sourceMappingURL=babylon.subMesh.js.map
  33982. var __assign = (this && this.__assign) || function () {
  33983. __assign = Object.assign || function(t) {
  33984. for (var s, i = 1, n = arguments.length; i < n; i++) {
  33985. s = arguments[i];
  33986. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  33987. t[p] = s[p];
  33988. }
  33989. return t;
  33990. };
  33991. return __assign.apply(this, arguments);
  33992. };
  33993. var BABYLON;
  33994. (function (BABYLON) {
  33995. /**
  33996. * Manages the defines for the Material
  33997. */
  33998. var MaterialDefines = /** @class */ (function () {
  33999. function MaterialDefines() {
  34000. this._isDirty = true;
  34001. /** @hidden */
  34002. this._areLightsDirty = true;
  34003. /** @hidden */
  34004. this._areAttributesDirty = true;
  34005. /** @hidden */
  34006. this._areTexturesDirty = true;
  34007. /** @hidden */
  34008. this._areFresnelDirty = true;
  34009. /** @hidden */
  34010. this._areMiscDirty = true;
  34011. /** @hidden */
  34012. this._areImageProcessingDirty = true;
  34013. /** @hidden */
  34014. this._normals = false;
  34015. /** @hidden */
  34016. this._uvs = false;
  34017. /** @hidden */
  34018. this._needNormals = false;
  34019. /** @hidden */
  34020. this._needUVs = false;
  34021. }
  34022. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34023. /**
  34024. * Specifies if the material needs to be re-calculated
  34025. */
  34026. get: function () {
  34027. return this._isDirty;
  34028. },
  34029. enumerable: true,
  34030. configurable: true
  34031. });
  34032. /**
  34033. * Marks the material to indicate that it has been re-calculated
  34034. */
  34035. MaterialDefines.prototype.markAsProcessed = function () {
  34036. this._isDirty = false;
  34037. this._areAttributesDirty = false;
  34038. this._areTexturesDirty = false;
  34039. this._areFresnelDirty = false;
  34040. this._areLightsDirty = false;
  34041. this._areMiscDirty = false;
  34042. this._areImageProcessingDirty = false;
  34043. };
  34044. /**
  34045. * Marks the material to indicate that it needs to be re-calculated
  34046. */
  34047. MaterialDefines.prototype.markAsUnprocessed = function () {
  34048. this._isDirty = true;
  34049. };
  34050. /**
  34051. * Marks the material to indicate all of its defines need to be re-calculated
  34052. */
  34053. MaterialDefines.prototype.markAllAsDirty = function () {
  34054. this._areTexturesDirty = true;
  34055. this._areAttributesDirty = true;
  34056. this._areLightsDirty = true;
  34057. this._areFresnelDirty = true;
  34058. this._areMiscDirty = true;
  34059. this._areImageProcessingDirty = true;
  34060. this._isDirty = true;
  34061. };
  34062. /**
  34063. * Marks the material to indicate that image processing needs to be re-calculated
  34064. */
  34065. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34066. this._areImageProcessingDirty = true;
  34067. this._isDirty = true;
  34068. };
  34069. /**
  34070. * Marks the material to indicate the lights need to be re-calculated
  34071. */
  34072. MaterialDefines.prototype.markAsLightDirty = function () {
  34073. this._areLightsDirty = true;
  34074. this._isDirty = true;
  34075. };
  34076. /**
  34077. * Marks the attribute state as changed
  34078. */
  34079. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34080. this._areAttributesDirty = true;
  34081. this._isDirty = true;
  34082. };
  34083. /**
  34084. * Marks the texture state as changed
  34085. */
  34086. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34087. this._areTexturesDirty = true;
  34088. this._isDirty = true;
  34089. };
  34090. /**
  34091. * Marks the fresnel state as changed
  34092. */
  34093. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34094. this._areFresnelDirty = true;
  34095. this._isDirty = true;
  34096. };
  34097. /**
  34098. * Marks the misc state as changed
  34099. */
  34100. MaterialDefines.prototype.markAsMiscDirty = function () {
  34101. this._areMiscDirty = true;
  34102. this._isDirty = true;
  34103. };
  34104. /**
  34105. * Rebuilds the material defines
  34106. */
  34107. MaterialDefines.prototype.rebuild = function () {
  34108. if (this._keys) {
  34109. delete this._keys;
  34110. }
  34111. this._keys = [];
  34112. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34113. var key = _a[_i];
  34114. if (key[0] === "_") {
  34115. continue;
  34116. }
  34117. this._keys.push(key);
  34118. }
  34119. };
  34120. /**
  34121. * Specifies if two material defines are equal
  34122. * @param other - A material define instance to compare to
  34123. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34124. */
  34125. MaterialDefines.prototype.isEqual = function (other) {
  34126. if (this._keys.length !== other._keys.length) {
  34127. return false;
  34128. }
  34129. for (var index = 0; index < this._keys.length; index++) {
  34130. var prop = this._keys[index];
  34131. if (this[prop] !== other[prop]) {
  34132. return false;
  34133. }
  34134. }
  34135. return true;
  34136. };
  34137. /**
  34138. * Clones this instance's defines to another instance
  34139. * @param other - material defines to clone values to
  34140. */
  34141. MaterialDefines.prototype.cloneTo = function (other) {
  34142. if (this._keys.length !== other._keys.length) {
  34143. other._keys = this._keys.slice(0);
  34144. }
  34145. for (var index = 0; index < this._keys.length; index++) {
  34146. var prop = this._keys[index];
  34147. other[prop] = this[prop];
  34148. }
  34149. };
  34150. /**
  34151. * Resets the material define values
  34152. */
  34153. MaterialDefines.prototype.reset = function () {
  34154. for (var index = 0; index < this._keys.length; index++) {
  34155. var prop = this._keys[index];
  34156. var type = typeof this[prop];
  34157. switch (type) {
  34158. case "number":
  34159. this[prop] = 0;
  34160. break;
  34161. case "string":
  34162. this[prop] = "";
  34163. break;
  34164. default:
  34165. this[prop] = false;
  34166. break;
  34167. }
  34168. }
  34169. };
  34170. /**
  34171. * Converts the material define values to a string
  34172. * @returns - String of material define information
  34173. */
  34174. MaterialDefines.prototype.toString = function () {
  34175. var result = "";
  34176. for (var index = 0; index < this._keys.length; index++) {
  34177. var prop = this._keys[index];
  34178. var value = this[prop];
  34179. var type = typeof value;
  34180. switch (type) {
  34181. case "number":
  34182. case "string":
  34183. result += "#define " + prop + " " + value + "\n";
  34184. break;
  34185. default:
  34186. if (value) {
  34187. result += "#define " + prop + "\n";
  34188. }
  34189. break;
  34190. }
  34191. }
  34192. return result;
  34193. };
  34194. return MaterialDefines;
  34195. }());
  34196. BABYLON.MaterialDefines = MaterialDefines;
  34197. /**
  34198. * Base class for the main features of a material in Babylon.js
  34199. */
  34200. var Material = /** @class */ (function () {
  34201. /**
  34202. * Creates a material instance
  34203. * @param name defines the name of the material
  34204. * @param scene defines the scene to reference
  34205. * @param doNotAdd specifies if the material should be added to the scene
  34206. */
  34207. function Material(name, scene, doNotAdd) {
  34208. /**
  34209. * Specifies if the ready state should be checked on each call
  34210. */
  34211. this.checkReadyOnEveryCall = false;
  34212. /**
  34213. * Specifies if the ready state should be checked once
  34214. */
  34215. this.checkReadyOnlyOnce = false;
  34216. /**
  34217. * The state of the material
  34218. */
  34219. this.state = "";
  34220. /**
  34221. * The alpha value of the material
  34222. */
  34223. this._alpha = 1.0;
  34224. /**
  34225. * Specifies if back face culling is enabled
  34226. */
  34227. this._backFaceCulling = true;
  34228. /**
  34229. * Gets a boolean indicating that current material needs to register RTT
  34230. */
  34231. this.hasRenderTargetTextures = false;
  34232. /**
  34233. * Specifies if the material should be serialized
  34234. */
  34235. this.doNotSerialize = false;
  34236. /**
  34237. * Specifies if the effect should be stored on sub meshes
  34238. */
  34239. this.storeEffectOnSubMeshes = false;
  34240. /**
  34241. * An event triggered when the material is disposed
  34242. */
  34243. this.onDisposeObservable = new BABYLON.Observable();
  34244. /**
  34245. * Stores the value of the alpha mode
  34246. */
  34247. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34248. /**
  34249. * Stores the state of the need depth pre-pass value
  34250. */
  34251. this._needDepthPrePass = false;
  34252. /**
  34253. * Specifies if depth writing should be disabled
  34254. */
  34255. this.disableDepthWrite = false;
  34256. /**
  34257. * Specifies if depth writing should be forced
  34258. */
  34259. this.forceDepthWrite = false;
  34260. /**
  34261. * Specifies if there should be a separate pass for culling
  34262. */
  34263. this.separateCullingPass = false;
  34264. /**
  34265. * Stores the state specifing if fog should be enabled
  34266. */
  34267. this._fogEnabled = true;
  34268. /**
  34269. * Stores the size of points
  34270. */
  34271. this.pointSize = 1.0;
  34272. /**
  34273. * Stores the z offset value
  34274. */
  34275. this.zOffset = 0;
  34276. /**
  34277. * @hidden
  34278. * Specifies if the material was previously ready
  34279. */
  34280. this._wasPreviouslyReady = false;
  34281. /**
  34282. * Stores the fill mode state
  34283. */
  34284. this._fillMode = Material.TriangleFillMode;
  34285. this.name = name;
  34286. this.id = name || BABYLON.Tools.RandomId();
  34287. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34288. this.uniqueId = this._scene.getUniqueId();
  34289. if (this._scene.useRightHandedSystem) {
  34290. this.sideOrientation = Material.ClockWiseSideOrientation;
  34291. }
  34292. else {
  34293. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34294. }
  34295. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34296. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34297. if (!doNotAdd) {
  34298. this._scene.materials.push(this);
  34299. }
  34300. }
  34301. Object.defineProperty(Material, "TriangleFillMode", {
  34302. /**
  34303. * Returns the triangle fill mode
  34304. */
  34305. get: function () {
  34306. return Material._TriangleFillMode;
  34307. },
  34308. enumerable: true,
  34309. configurable: true
  34310. });
  34311. Object.defineProperty(Material, "WireFrameFillMode", {
  34312. /**
  34313. * Returns the wireframe mode
  34314. */
  34315. get: function () {
  34316. return Material._WireFrameFillMode;
  34317. },
  34318. enumerable: true,
  34319. configurable: true
  34320. });
  34321. Object.defineProperty(Material, "PointFillMode", {
  34322. /**
  34323. * Returns the point fill mode
  34324. */
  34325. get: function () {
  34326. return Material._PointFillMode;
  34327. },
  34328. enumerable: true,
  34329. configurable: true
  34330. });
  34331. Object.defineProperty(Material, "PointListDrawMode", {
  34332. /**
  34333. * Returns the point list draw mode
  34334. */
  34335. get: function () {
  34336. return Material._PointListDrawMode;
  34337. },
  34338. enumerable: true,
  34339. configurable: true
  34340. });
  34341. Object.defineProperty(Material, "LineListDrawMode", {
  34342. /**
  34343. * Returns the line list draw mode
  34344. */
  34345. get: function () {
  34346. return Material._LineListDrawMode;
  34347. },
  34348. enumerable: true,
  34349. configurable: true
  34350. });
  34351. Object.defineProperty(Material, "LineLoopDrawMode", {
  34352. /**
  34353. * Returns the line loop draw mode
  34354. */
  34355. get: function () {
  34356. return Material._LineLoopDrawMode;
  34357. },
  34358. enumerable: true,
  34359. configurable: true
  34360. });
  34361. Object.defineProperty(Material, "LineStripDrawMode", {
  34362. /**
  34363. * Returns the line strip draw mode
  34364. */
  34365. get: function () {
  34366. return Material._LineStripDrawMode;
  34367. },
  34368. enumerable: true,
  34369. configurable: true
  34370. });
  34371. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34372. /**
  34373. * Returns the triangle strip draw mode
  34374. */
  34375. get: function () {
  34376. return Material._TriangleStripDrawMode;
  34377. },
  34378. enumerable: true,
  34379. configurable: true
  34380. });
  34381. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34382. /**
  34383. * Returns the triangle fan draw mode
  34384. */
  34385. get: function () {
  34386. return Material._TriangleFanDrawMode;
  34387. },
  34388. enumerable: true,
  34389. configurable: true
  34390. });
  34391. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34392. /**
  34393. * Returns the clock-wise side orientation
  34394. */
  34395. get: function () {
  34396. return Material._ClockWiseSideOrientation;
  34397. },
  34398. enumerable: true,
  34399. configurable: true
  34400. });
  34401. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34402. /**
  34403. * Returns the counter clock-wise side orientation
  34404. */
  34405. get: function () {
  34406. return Material._CounterClockWiseSideOrientation;
  34407. },
  34408. enumerable: true,
  34409. configurable: true
  34410. });
  34411. Object.defineProperty(Material, "TextureDirtyFlag", {
  34412. /**
  34413. * Returns the dirty texture flag value
  34414. */
  34415. get: function () {
  34416. return Material._TextureDirtyFlag;
  34417. },
  34418. enumerable: true,
  34419. configurable: true
  34420. });
  34421. Object.defineProperty(Material, "LightDirtyFlag", {
  34422. /**
  34423. * Returns the dirty light flag value
  34424. */
  34425. get: function () {
  34426. return Material._LightDirtyFlag;
  34427. },
  34428. enumerable: true,
  34429. configurable: true
  34430. });
  34431. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34432. /**
  34433. * Returns the dirty fresnel flag value
  34434. */
  34435. get: function () {
  34436. return Material._FresnelDirtyFlag;
  34437. },
  34438. enumerable: true,
  34439. configurable: true
  34440. });
  34441. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34442. /**
  34443. * Returns the dirty attributes flag value
  34444. */
  34445. get: function () {
  34446. return Material._AttributesDirtyFlag;
  34447. },
  34448. enumerable: true,
  34449. configurable: true
  34450. });
  34451. Object.defineProperty(Material, "MiscDirtyFlag", {
  34452. /**
  34453. * Returns the dirty misc flag value
  34454. */
  34455. get: function () {
  34456. return Material._MiscDirtyFlag;
  34457. },
  34458. enumerable: true,
  34459. configurable: true
  34460. });
  34461. Object.defineProperty(Material.prototype, "alpha", {
  34462. /**
  34463. * Gets the alpha value of the material
  34464. */
  34465. get: function () {
  34466. return this._alpha;
  34467. },
  34468. /**
  34469. * Sets the alpha value of the material
  34470. */
  34471. set: function (value) {
  34472. if (this._alpha === value) {
  34473. return;
  34474. }
  34475. this._alpha = value;
  34476. this.markAsDirty(Material.MiscDirtyFlag);
  34477. },
  34478. enumerable: true,
  34479. configurable: true
  34480. });
  34481. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34482. /**
  34483. * Gets the back-face culling state
  34484. */
  34485. get: function () {
  34486. return this._backFaceCulling;
  34487. },
  34488. /**
  34489. * Sets the back-face culling state
  34490. */
  34491. set: function (value) {
  34492. if (this._backFaceCulling === value) {
  34493. return;
  34494. }
  34495. this._backFaceCulling = value;
  34496. this.markAsDirty(Material.TextureDirtyFlag);
  34497. },
  34498. enumerable: true,
  34499. configurable: true
  34500. });
  34501. Object.defineProperty(Material.prototype, "onDispose", {
  34502. /**
  34503. * Called during a dispose event
  34504. */
  34505. set: function (callback) {
  34506. if (this._onDisposeObserver) {
  34507. this.onDisposeObservable.remove(this._onDisposeObserver);
  34508. }
  34509. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34510. },
  34511. enumerable: true,
  34512. configurable: true
  34513. });
  34514. Object.defineProperty(Material.prototype, "onBindObservable", {
  34515. /**
  34516. * An event triggered when the material is bound
  34517. */
  34518. get: function () {
  34519. if (!this._onBindObservable) {
  34520. this._onBindObservable = new BABYLON.Observable();
  34521. }
  34522. return this._onBindObservable;
  34523. },
  34524. enumerable: true,
  34525. configurable: true
  34526. });
  34527. Object.defineProperty(Material.prototype, "onBind", {
  34528. /**
  34529. * Called during a bind event
  34530. */
  34531. set: function (callback) {
  34532. if (this._onBindObserver) {
  34533. this.onBindObservable.remove(this._onBindObserver);
  34534. }
  34535. this._onBindObserver = this.onBindObservable.add(callback);
  34536. },
  34537. enumerable: true,
  34538. configurable: true
  34539. });
  34540. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  34541. /**
  34542. * An event triggered when the material is unbound
  34543. */
  34544. get: function () {
  34545. if (!this._onUnBindObservable) {
  34546. this._onUnBindObservable = new BABYLON.Observable();
  34547. }
  34548. return this._onUnBindObservable;
  34549. },
  34550. enumerable: true,
  34551. configurable: true
  34552. });
  34553. Object.defineProperty(Material.prototype, "alphaMode", {
  34554. /**
  34555. * Gets the value of the alpha mode
  34556. */
  34557. get: function () {
  34558. return this._alphaMode;
  34559. },
  34560. /**
  34561. * Sets the value of the alpha mode.
  34562. *
  34563. * | Value | Type | Description |
  34564. * | --- | --- | --- |
  34565. * | 0 | ALPHA_DISABLE | |
  34566. * | 1 | ALPHA_ADD | |
  34567. * | 2 | ALPHA_COMBINE | |
  34568. * | 3 | ALPHA_SUBTRACT | |
  34569. * | 4 | ALPHA_MULTIPLY | |
  34570. * | 5 | ALPHA_MAXIMIZED | |
  34571. * | 6 | ALPHA_ONEONE | |
  34572. * | 7 | ALPHA_PREMULTIPLIED | |
  34573. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34574. * | 9 | ALPHA_INTERPOLATE | |
  34575. * | 10 | ALPHA_SCREENMODE | |
  34576. *
  34577. */
  34578. set: function (value) {
  34579. if (this._alphaMode === value) {
  34580. return;
  34581. }
  34582. this._alphaMode = value;
  34583. this.markAsDirty(Material.TextureDirtyFlag);
  34584. },
  34585. enumerable: true,
  34586. configurable: true
  34587. });
  34588. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34589. /**
  34590. * Gets the depth pre-pass value
  34591. */
  34592. get: function () {
  34593. return this._needDepthPrePass;
  34594. },
  34595. /**
  34596. * Sets the need depth pre-pass value
  34597. */
  34598. set: function (value) {
  34599. if (this._needDepthPrePass === value) {
  34600. return;
  34601. }
  34602. this._needDepthPrePass = value;
  34603. if (this._needDepthPrePass) {
  34604. this.checkReadyOnEveryCall = true;
  34605. }
  34606. },
  34607. enumerable: true,
  34608. configurable: true
  34609. });
  34610. Object.defineProperty(Material.prototype, "fogEnabled", {
  34611. /**
  34612. * Gets the value of the fog enabled state
  34613. */
  34614. get: function () {
  34615. return this._fogEnabled;
  34616. },
  34617. /**
  34618. * Sets the state for enabling fog
  34619. */
  34620. set: function (value) {
  34621. if (this._fogEnabled === value) {
  34622. return;
  34623. }
  34624. this._fogEnabled = value;
  34625. this.markAsDirty(Material.MiscDirtyFlag);
  34626. },
  34627. enumerable: true,
  34628. configurable: true
  34629. });
  34630. Object.defineProperty(Material.prototype, "wireframe", {
  34631. /**
  34632. * Gets a value specifying if wireframe mode is enabled
  34633. */
  34634. get: function () {
  34635. switch (this._fillMode) {
  34636. case Material.WireFrameFillMode:
  34637. case Material.LineListDrawMode:
  34638. case Material.LineLoopDrawMode:
  34639. case Material.LineStripDrawMode:
  34640. return true;
  34641. }
  34642. return this._scene.forceWireframe;
  34643. },
  34644. /**
  34645. * Sets the state of wireframe mode
  34646. */
  34647. set: function (value) {
  34648. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34649. },
  34650. enumerable: true,
  34651. configurable: true
  34652. });
  34653. Object.defineProperty(Material.prototype, "pointsCloud", {
  34654. /**
  34655. * Gets the value specifying if point clouds are enabled
  34656. */
  34657. get: function () {
  34658. switch (this._fillMode) {
  34659. case Material.PointFillMode:
  34660. case Material.PointListDrawMode:
  34661. return true;
  34662. }
  34663. return this._scene.forcePointsCloud;
  34664. },
  34665. /**
  34666. * Sets the state of point cloud mode
  34667. */
  34668. set: function (value) {
  34669. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34670. },
  34671. enumerable: true,
  34672. configurable: true
  34673. });
  34674. Object.defineProperty(Material.prototype, "fillMode", {
  34675. /**
  34676. * Gets the material fill mode
  34677. */
  34678. get: function () {
  34679. return this._fillMode;
  34680. },
  34681. /**
  34682. * Sets the material fill mode
  34683. */
  34684. set: function (value) {
  34685. if (this._fillMode === value) {
  34686. return;
  34687. }
  34688. this._fillMode = value;
  34689. this.markAsDirty(Material.MiscDirtyFlag);
  34690. },
  34691. enumerable: true,
  34692. configurable: true
  34693. });
  34694. /**
  34695. * Returns a string representation of the current material
  34696. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34697. * @returns a string with material information
  34698. */
  34699. Material.prototype.toString = function (fullDetails) {
  34700. var ret = "Name: " + this.name;
  34701. if (fullDetails) {
  34702. }
  34703. return ret;
  34704. };
  34705. /**
  34706. * Gets the class name of the material
  34707. * @returns a string with the class name of the material
  34708. */
  34709. Material.prototype.getClassName = function () {
  34710. return "Material";
  34711. };
  34712. Object.defineProperty(Material.prototype, "isFrozen", {
  34713. /**
  34714. * Specifies if updates for the material been locked
  34715. */
  34716. get: function () {
  34717. return this.checkReadyOnlyOnce;
  34718. },
  34719. enumerable: true,
  34720. configurable: true
  34721. });
  34722. /**
  34723. * Locks updates for the material
  34724. */
  34725. Material.prototype.freeze = function () {
  34726. this.checkReadyOnlyOnce = true;
  34727. };
  34728. /**
  34729. * Unlocks updates for the material
  34730. */
  34731. Material.prototype.unfreeze = function () {
  34732. this.checkReadyOnlyOnce = false;
  34733. };
  34734. /**
  34735. * Specifies if the material is ready to be used
  34736. * @param mesh defines the mesh to check
  34737. * @param useInstances specifies if instances should be used
  34738. * @returns a boolean indicating if the material is ready to be used
  34739. */
  34740. Material.prototype.isReady = function (mesh, useInstances) {
  34741. return true;
  34742. };
  34743. /**
  34744. * Specifies that the submesh is ready to be used
  34745. * @param mesh defines the mesh to check
  34746. * @param subMesh defines which submesh to check
  34747. * @param useInstances specifies that instances should be used
  34748. * @returns a boolean indicating that the submesh is ready or not
  34749. */
  34750. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34751. return false;
  34752. };
  34753. /**
  34754. * Returns the material effect
  34755. * @returns the effect associated with the material
  34756. */
  34757. Material.prototype.getEffect = function () {
  34758. return this._effect;
  34759. };
  34760. /**
  34761. * Returns the current scene
  34762. * @returns a Scene
  34763. */
  34764. Material.prototype.getScene = function () {
  34765. return this._scene;
  34766. };
  34767. /**
  34768. * Specifies if the material will require alpha blending
  34769. * @returns a boolean specifying if alpha blending is needed
  34770. */
  34771. Material.prototype.needAlphaBlending = function () {
  34772. return (this.alpha < 1.0);
  34773. };
  34774. /**
  34775. * Specifies if the mesh will require alpha blending
  34776. * @param mesh defines the mesh to check
  34777. * @returns a boolean specifying if alpha blending is needed for the mesh
  34778. */
  34779. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34780. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34781. };
  34782. /**
  34783. * Specifies if this material should be rendered in alpha test mode
  34784. * @returns a boolean specifying if an alpha test is needed.
  34785. */
  34786. Material.prototype.needAlphaTesting = function () {
  34787. return false;
  34788. };
  34789. /**
  34790. * Gets the texture used for the alpha test
  34791. * @returns the texture to use for alpha testing
  34792. */
  34793. Material.prototype.getAlphaTestTexture = function () {
  34794. return null;
  34795. };
  34796. /**
  34797. * Marks the material to indicate that it needs to be re-calculated
  34798. */
  34799. Material.prototype.markDirty = function () {
  34800. this._wasPreviouslyReady = false;
  34801. };
  34802. /** @hidden */
  34803. Material.prototype._preBind = function (effect, overrideOrientation) {
  34804. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34805. var engine = this._scene.getEngine();
  34806. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34807. var reverse = orientation === Material.ClockWiseSideOrientation;
  34808. engine.enableEffect(effect ? effect : this._effect);
  34809. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34810. return reverse;
  34811. };
  34812. /**
  34813. * Binds the material to the mesh
  34814. * @param world defines the world transformation matrix
  34815. * @param mesh defines the mesh to bind the material to
  34816. */
  34817. Material.prototype.bind = function (world, mesh) {
  34818. };
  34819. /**
  34820. * Binds the submesh to the material
  34821. * @param world defines the world transformation matrix
  34822. * @param mesh defines the mesh containing the submesh
  34823. * @param subMesh defines the submesh to bind the material to
  34824. */
  34825. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34826. };
  34827. /**
  34828. * Binds the world matrix to the material
  34829. * @param world defines the world transformation matrix
  34830. */
  34831. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34832. };
  34833. /**
  34834. * Binds the scene's uniform buffer to the effect.
  34835. * @param effect defines the effect to bind to the scene uniform buffer
  34836. * @param sceneUbo defines the uniform buffer storing scene data
  34837. */
  34838. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34839. sceneUbo.bindToEffect(effect, "Scene");
  34840. };
  34841. /**
  34842. * Binds the view matrix to the effect
  34843. * @param effect defines the effect to bind the view matrix to
  34844. */
  34845. Material.prototype.bindView = function (effect) {
  34846. if (!this._useUBO) {
  34847. effect.setMatrix("view", this.getScene().getViewMatrix());
  34848. }
  34849. else {
  34850. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34851. }
  34852. };
  34853. /**
  34854. * Binds the view projection matrix to the effect
  34855. * @param effect defines the effect to bind the view projection matrix to
  34856. */
  34857. Material.prototype.bindViewProjection = function (effect) {
  34858. if (!this._useUBO) {
  34859. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34860. }
  34861. else {
  34862. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34863. }
  34864. };
  34865. /**
  34866. * Specifies if material alpha testing should be turned on for the mesh
  34867. * @param mesh defines the mesh to check
  34868. */
  34869. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  34870. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  34871. };
  34872. /**
  34873. * Processes to execute after binding the material to a mesh
  34874. * @param mesh defines the rendered mesh
  34875. */
  34876. Material.prototype._afterBind = function (mesh) {
  34877. this._scene._cachedMaterial = this;
  34878. if (mesh) {
  34879. this._scene._cachedVisibility = mesh.visibility;
  34880. }
  34881. else {
  34882. this._scene._cachedVisibility = 1;
  34883. }
  34884. if (this._onBindObservable && mesh) {
  34885. this._onBindObservable.notifyObservers(mesh);
  34886. }
  34887. if (this.disableDepthWrite) {
  34888. var engine = this._scene.getEngine();
  34889. this._cachedDepthWriteState = engine.getDepthWrite();
  34890. engine.setDepthWrite(false);
  34891. }
  34892. };
  34893. /**
  34894. * Unbinds the material from the mesh
  34895. */
  34896. Material.prototype.unbind = function () {
  34897. if (this._onUnBindObservable) {
  34898. this._onUnBindObservable.notifyObservers(this);
  34899. }
  34900. if (this.disableDepthWrite) {
  34901. var engine = this._scene.getEngine();
  34902. engine.setDepthWrite(this._cachedDepthWriteState);
  34903. }
  34904. };
  34905. /**
  34906. * Gets the active textures from the material
  34907. * @returns an array of textures
  34908. */
  34909. Material.prototype.getActiveTextures = function () {
  34910. return [];
  34911. };
  34912. /**
  34913. * Specifies if the material uses a texture
  34914. * @param texture defines the texture to check against the material
  34915. * @returns a boolean specifying if the material uses the texture
  34916. */
  34917. Material.prototype.hasTexture = function (texture) {
  34918. return false;
  34919. };
  34920. /**
  34921. * Makes a duplicate of the material, and gives it a new name
  34922. * @param name defines the new name for the duplicated material
  34923. * @returns the cloned material
  34924. */
  34925. Material.prototype.clone = function (name) {
  34926. return null;
  34927. };
  34928. /**
  34929. * Gets the meshes bound to the material
  34930. * @returns an array of meshes bound to the material
  34931. */
  34932. Material.prototype.getBindedMeshes = function () {
  34933. var result = new Array();
  34934. for (var index = 0; index < this._scene.meshes.length; index++) {
  34935. var mesh = this._scene.meshes[index];
  34936. if (mesh.material === this) {
  34937. result.push(mesh);
  34938. }
  34939. }
  34940. return result;
  34941. };
  34942. /**
  34943. * Force shader compilation
  34944. * @param mesh defines the mesh associated with this material
  34945. * @param onCompiled defines a function to execute once the material is compiled
  34946. * @param options defines the options to configure the compilation
  34947. */
  34948. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  34949. var _this = this;
  34950. var localOptions = __assign({ clipPlane: false }, options);
  34951. var subMesh = new BABYLON.BaseSubMesh();
  34952. var scene = this.getScene();
  34953. var checkReady = function () {
  34954. if (!_this._scene || !_this._scene.getEngine()) {
  34955. return;
  34956. }
  34957. if (subMesh._materialDefines) {
  34958. subMesh._materialDefines._renderId = -1;
  34959. }
  34960. var clipPlaneState = scene.clipPlane;
  34961. if (localOptions.clipPlane) {
  34962. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  34963. }
  34964. if (_this.storeEffectOnSubMeshes) {
  34965. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  34966. if (onCompiled) {
  34967. onCompiled(_this);
  34968. }
  34969. }
  34970. else {
  34971. setTimeout(checkReady, 16);
  34972. }
  34973. }
  34974. else {
  34975. if (_this.isReady(mesh)) {
  34976. if (onCompiled) {
  34977. onCompiled(_this);
  34978. }
  34979. }
  34980. else {
  34981. setTimeout(checkReady, 16);
  34982. }
  34983. }
  34984. if (localOptions.clipPlane) {
  34985. scene.clipPlane = clipPlaneState;
  34986. }
  34987. };
  34988. checkReady();
  34989. };
  34990. /**
  34991. * Force shader compilation
  34992. * @param mesh defines the mesh that will use this material
  34993. * @param options defines additional options for compiling the shaders
  34994. * @returns a promise that resolves when the compilation completes
  34995. */
  34996. Material.prototype.forceCompilationAsync = function (mesh, options) {
  34997. var _this = this;
  34998. return new Promise(function (resolve) {
  34999. _this.forceCompilation(mesh, function () {
  35000. resolve();
  35001. }, options);
  35002. });
  35003. };
  35004. /**
  35005. * Marks a define in the material to indicate that it needs to be re-computed
  35006. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35007. */
  35008. Material.prototype.markAsDirty = function (flag) {
  35009. if (flag & Material.TextureDirtyFlag) {
  35010. this._markAllSubMeshesAsTexturesDirty();
  35011. }
  35012. if (flag & Material.LightDirtyFlag) {
  35013. this._markAllSubMeshesAsLightsDirty();
  35014. }
  35015. if (flag & Material.FresnelDirtyFlag) {
  35016. this._markAllSubMeshesAsFresnelDirty();
  35017. }
  35018. if (flag & Material.AttributesDirtyFlag) {
  35019. this._markAllSubMeshesAsAttributesDirty();
  35020. }
  35021. if (flag & Material.MiscDirtyFlag) {
  35022. this._markAllSubMeshesAsMiscDirty();
  35023. }
  35024. this.getScene().resetCachedMaterial();
  35025. };
  35026. /**
  35027. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35028. * @param func defines a function which checks material defines against the submeshes
  35029. */
  35030. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35031. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35032. var mesh = _a[_i];
  35033. if (!mesh.subMeshes) {
  35034. continue;
  35035. }
  35036. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35037. var subMesh = _c[_b];
  35038. if (subMesh.getMaterial() !== this) {
  35039. continue;
  35040. }
  35041. if (!subMesh._materialDefines) {
  35042. continue;
  35043. }
  35044. func(subMesh._materialDefines);
  35045. }
  35046. }
  35047. };
  35048. /**
  35049. * Indicates that image processing needs to be re-calculated for all submeshes
  35050. */
  35051. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35052. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35053. };
  35054. /**
  35055. * Indicates that textures need to be re-calculated for all submeshes
  35056. */
  35057. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35058. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35059. };
  35060. /**
  35061. * Indicates that fresnel needs to be re-calculated for all submeshes
  35062. */
  35063. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35064. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35065. };
  35066. /**
  35067. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35068. */
  35069. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35070. this._markAllSubMeshesAsDirty(function (defines) {
  35071. defines.markAsFresnelDirty();
  35072. defines.markAsMiscDirty();
  35073. });
  35074. };
  35075. /**
  35076. * Indicates that lights need to be re-calculated for all submeshes
  35077. */
  35078. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35079. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35080. };
  35081. /**
  35082. * Indicates that attributes need to be re-calculated for all submeshes
  35083. */
  35084. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35085. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35086. };
  35087. /**
  35088. * Indicates that misc needs to be re-calculated for all submeshes
  35089. */
  35090. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35091. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35092. };
  35093. /**
  35094. * Indicates that textures and misc need to be re-calculated for all submeshes
  35095. */
  35096. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35097. this._markAllSubMeshesAsDirty(function (defines) {
  35098. defines.markAsTexturesDirty();
  35099. defines.markAsMiscDirty();
  35100. });
  35101. };
  35102. /**
  35103. * Disposes the material
  35104. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35105. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35106. */
  35107. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35108. // Animations
  35109. this.getScene().stopAnimation(this);
  35110. this.getScene().freeProcessedMaterials();
  35111. // Remove from scene
  35112. var index = this._scene.materials.indexOf(this);
  35113. if (index >= 0) {
  35114. this._scene.materials.splice(index, 1);
  35115. }
  35116. // Remove from meshes
  35117. for (index = 0; index < this._scene.meshes.length; index++) {
  35118. var mesh = this._scene.meshes[index];
  35119. if (mesh.material === this) {
  35120. mesh.material = null;
  35121. if (mesh.geometry) {
  35122. var geometry = (mesh.geometry);
  35123. if (this.storeEffectOnSubMeshes) {
  35124. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35125. var subMesh = _a[_i];
  35126. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35127. if (forceDisposeEffect && subMesh._materialEffect) {
  35128. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35129. }
  35130. }
  35131. }
  35132. else {
  35133. geometry._releaseVertexArrayObject(this._effect);
  35134. }
  35135. }
  35136. }
  35137. }
  35138. this._uniformBuffer.dispose();
  35139. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35140. if (forceDisposeEffect && this._effect) {
  35141. if (!this.storeEffectOnSubMeshes) {
  35142. this._scene.getEngine()._releaseEffect(this._effect);
  35143. }
  35144. this._effect = null;
  35145. }
  35146. // Callback
  35147. this.onDisposeObservable.notifyObservers(this);
  35148. this.onDisposeObservable.clear();
  35149. if (this._onBindObservable) {
  35150. this._onBindObservable.clear();
  35151. }
  35152. if (this._onUnBindObservable) {
  35153. this._onUnBindObservable.clear();
  35154. }
  35155. };
  35156. /**
  35157. * Serializes this material
  35158. * @returns the serialized material object
  35159. */
  35160. Material.prototype.serialize = function () {
  35161. return BABYLON.SerializationHelper.Serialize(this);
  35162. };
  35163. /**
  35164. * Creates a MultiMaterial from parsed MultiMaterial data.
  35165. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35166. * @param scene defines the hosting scene
  35167. * @returns a new MultiMaterial
  35168. */
  35169. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35170. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35171. multiMaterial.id = parsedMultiMaterial.id;
  35172. if (BABYLON.Tags) {
  35173. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35174. }
  35175. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35176. var subMatId = parsedMultiMaterial.materials[matIndex];
  35177. if (subMatId) {
  35178. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35179. }
  35180. else {
  35181. multiMaterial.subMaterials.push(null);
  35182. }
  35183. }
  35184. return multiMaterial;
  35185. };
  35186. /**
  35187. * Creates a material from parsed material data
  35188. * @param parsedMaterial defines parsed material data
  35189. * @param scene defines the hosting scene
  35190. * @param rootUrl defines the root URL to use to load textures
  35191. * @returns a new material
  35192. */
  35193. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35194. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35195. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35196. }
  35197. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35198. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35199. if (!BABYLON.LegacyPBRMaterial) {
  35200. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35201. return;
  35202. }
  35203. }
  35204. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35205. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35206. };
  35207. // Triangle views
  35208. Material._TriangleFillMode = 0;
  35209. Material._WireFrameFillMode = 1;
  35210. Material._PointFillMode = 2;
  35211. // Draw modes
  35212. Material._PointListDrawMode = 3;
  35213. Material._LineListDrawMode = 4;
  35214. Material._LineLoopDrawMode = 5;
  35215. Material._LineStripDrawMode = 6;
  35216. Material._TriangleStripDrawMode = 7;
  35217. Material._TriangleFanDrawMode = 8;
  35218. /**
  35219. * Stores the clock-wise side orientation
  35220. */
  35221. Material._ClockWiseSideOrientation = 0;
  35222. /**
  35223. * Stores the counter clock-wise side orientation
  35224. */
  35225. Material._CounterClockWiseSideOrientation = 1;
  35226. /**
  35227. * The dirty texture flag value
  35228. */
  35229. Material._TextureDirtyFlag = 1;
  35230. /**
  35231. * The dirty light flag value
  35232. */
  35233. Material._LightDirtyFlag = 2;
  35234. /**
  35235. * The dirty fresnel flag value
  35236. */
  35237. Material._FresnelDirtyFlag = 4;
  35238. /**
  35239. * The dirty attribute flag value
  35240. */
  35241. Material._AttributesDirtyFlag = 8;
  35242. /**
  35243. * The dirty misc flag value
  35244. */
  35245. Material._MiscDirtyFlag = 16;
  35246. __decorate([
  35247. BABYLON.serialize()
  35248. ], Material.prototype, "id", void 0);
  35249. __decorate([
  35250. BABYLON.serialize()
  35251. ], Material.prototype, "uniqueId", void 0);
  35252. __decorate([
  35253. BABYLON.serialize()
  35254. ], Material.prototype, "name", void 0);
  35255. __decorate([
  35256. BABYLON.serialize()
  35257. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35258. __decorate([
  35259. BABYLON.serialize()
  35260. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35261. __decorate([
  35262. BABYLON.serialize()
  35263. ], Material.prototype, "state", void 0);
  35264. __decorate([
  35265. BABYLON.serialize("alpha")
  35266. ], Material.prototype, "_alpha", void 0);
  35267. __decorate([
  35268. BABYLON.serialize("backFaceCulling")
  35269. ], Material.prototype, "_backFaceCulling", void 0);
  35270. __decorate([
  35271. BABYLON.serialize()
  35272. ], Material.prototype, "sideOrientation", void 0);
  35273. __decorate([
  35274. BABYLON.serialize("alphaMode")
  35275. ], Material.prototype, "_alphaMode", void 0);
  35276. __decorate([
  35277. BABYLON.serialize()
  35278. ], Material.prototype, "_needDepthPrePass", void 0);
  35279. __decorate([
  35280. BABYLON.serialize()
  35281. ], Material.prototype, "disableDepthWrite", void 0);
  35282. __decorate([
  35283. BABYLON.serialize()
  35284. ], Material.prototype, "forceDepthWrite", void 0);
  35285. __decorate([
  35286. BABYLON.serialize()
  35287. ], Material.prototype, "separateCullingPass", void 0);
  35288. __decorate([
  35289. BABYLON.serialize("fogEnabled")
  35290. ], Material.prototype, "_fogEnabled", void 0);
  35291. __decorate([
  35292. BABYLON.serialize()
  35293. ], Material.prototype, "pointSize", void 0);
  35294. __decorate([
  35295. BABYLON.serialize()
  35296. ], Material.prototype, "zOffset", void 0);
  35297. __decorate([
  35298. BABYLON.serialize()
  35299. ], Material.prototype, "wireframe", null);
  35300. __decorate([
  35301. BABYLON.serialize()
  35302. ], Material.prototype, "pointsCloud", null);
  35303. __decorate([
  35304. BABYLON.serialize()
  35305. ], Material.prototype, "fillMode", null);
  35306. return Material;
  35307. }());
  35308. BABYLON.Material = Material;
  35309. })(BABYLON || (BABYLON = {}));
  35310. //# sourceMappingURL=babylon.material.js.map
  35311. var BABYLON;
  35312. (function (BABYLON) {
  35313. var UniformBuffer = /** @class */ (function () {
  35314. /**
  35315. * Uniform buffer objects.
  35316. *
  35317. * Handles blocks of uniform on the GPU.
  35318. *
  35319. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35320. *
  35321. * For more information, please refer to :
  35322. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35323. */
  35324. function UniformBuffer(engine, data, dynamic) {
  35325. this._engine = engine;
  35326. this._noUBO = !engine.supportsUniformBuffers;
  35327. this._dynamic = dynamic;
  35328. this._data = data || [];
  35329. this._uniformLocations = {};
  35330. this._uniformSizes = {};
  35331. this._uniformLocationPointer = 0;
  35332. this._needSync = false;
  35333. if (this._noUBO) {
  35334. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35335. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35336. this.updateFloat = this._updateFloatForEffect;
  35337. this.updateFloat2 = this._updateFloat2ForEffect;
  35338. this.updateFloat3 = this._updateFloat3ForEffect;
  35339. this.updateFloat4 = this._updateFloat4ForEffect;
  35340. this.updateMatrix = this._updateMatrixForEffect;
  35341. this.updateVector3 = this._updateVector3ForEffect;
  35342. this.updateVector4 = this._updateVector4ForEffect;
  35343. this.updateColor3 = this._updateColor3ForEffect;
  35344. this.updateColor4 = this._updateColor4ForEffect;
  35345. }
  35346. else {
  35347. this._engine._uniformBuffers.push(this);
  35348. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35349. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35350. this.updateFloat = this._updateFloatForUniform;
  35351. this.updateFloat2 = this._updateFloat2ForUniform;
  35352. this.updateFloat3 = this._updateFloat3ForUniform;
  35353. this.updateFloat4 = this._updateFloat4ForUniform;
  35354. this.updateMatrix = this._updateMatrixForUniform;
  35355. this.updateVector3 = this._updateVector3ForUniform;
  35356. this.updateVector4 = this._updateVector4ForUniform;
  35357. this.updateColor3 = this._updateColor3ForUniform;
  35358. this.updateColor4 = this._updateColor4ForUniform;
  35359. }
  35360. }
  35361. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35362. // Properties
  35363. /**
  35364. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35365. * or just falling back on setUniformXXX calls.
  35366. */
  35367. get: function () {
  35368. return !this._noUBO;
  35369. },
  35370. enumerable: true,
  35371. configurable: true
  35372. });
  35373. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35374. /**
  35375. * Indicates if the WebGL underlying uniform buffer is in sync
  35376. * with the javascript cache data.
  35377. */
  35378. get: function () {
  35379. return !this._needSync;
  35380. },
  35381. enumerable: true,
  35382. configurable: true
  35383. });
  35384. /**
  35385. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35386. * Also, a dynamic UniformBuffer will disable cache verification and always
  35387. * update the underlying WebGL uniform buffer to the GPU.
  35388. */
  35389. UniformBuffer.prototype.isDynamic = function () {
  35390. return this._dynamic !== undefined;
  35391. };
  35392. /**
  35393. * The data cache on JS side.
  35394. */
  35395. UniformBuffer.prototype.getData = function () {
  35396. return this._bufferData;
  35397. };
  35398. /**
  35399. * The underlying WebGL Uniform buffer.
  35400. */
  35401. UniformBuffer.prototype.getBuffer = function () {
  35402. return this._buffer;
  35403. };
  35404. /**
  35405. * std140 layout specifies how to align data within an UBO structure.
  35406. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35407. * for specs.
  35408. */
  35409. UniformBuffer.prototype._fillAlignment = function (size) {
  35410. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35411. // and 4x4 matrices
  35412. // TODO : change if other types are used
  35413. var alignment;
  35414. if (size <= 2) {
  35415. alignment = size;
  35416. }
  35417. else {
  35418. alignment = 4;
  35419. }
  35420. if ((this._uniformLocationPointer % alignment) !== 0) {
  35421. var oldPointer = this._uniformLocationPointer;
  35422. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35423. var diff = this._uniformLocationPointer - oldPointer;
  35424. for (var i = 0; i < diff; i++) {
  35425. this._data.push(0);
  35426. }
  35427. }
  35428. };
  35429. /**
  35430. * Adds an uniform in the buffer.
  35431. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35432. * for the layout to be correct !
  35433. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35434. * @param {number|number[]} size Data size, or data directly.
  35435. */
  35436. UniformBuffer.prototype.addUniform = function (name, size) {
  35437. if (this._noUBO) {
  35438. return;
  35439. }
  35440. if (this._uniformLocations[name] !== undefined) {
  35441. // Already existing uniform
  35442. return;
  35443. }
  35444. // This function must be called in the order of the shader layout !
  35445. // size can be the size of the uniform, or data directly
  35446. var data;
  35447. if (size instanceof Array) {
  35448. data = size;
  35449. size = data.length;
  35450. }
  35451. else {
  35452. size = size;
  35453. data = [];
  35454. // Fill with zeros
  35455. for (var i = 0; i < size; i++) {
  35456. data.push(0);
  35457. }
  35458. }
  35459. this._fillAlignment(size);
  35460. this._uniformSizes[name] = size;
  35461. this._uniformLocations[name] = this._uniformLocationPointer;
  35462. this._uniformLocationPointer += size;
  35463. for (var i = 0; i < size; i++) {
  35464. this._data.push(data[i]);
  35465. }
  35466. this._needSync = true;
  35467. };
  35468. /**
  35469. * Wrapper for addUniform.
  35470. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35471. * @param {Matrix} mat A 4x4 matrix.
  35472. */
  35473. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35474. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35475. };
  35476. /**
  35477. * Wrapper for addUniform.
  35478. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35479. * @param {number} x
  35480. * @param {number} y
  35481. */
  35482. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35483. var temp = [x, y];
  35484. this.addUniform(name, temp);
  35485. };
  35486. /**
  35487. * Wrapper for addUniform.
  35488. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35489. * @param {number} x
  35490. * @param {number} y
  35491. * @param {number} z
  35492. */
  35493. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35494. var temp = [x, y, z];
  35495. this.addUniform(name, temp);
  35496. };
  35497. /**
  35498. * Wrapper for addUniform.
  35499. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35500. * @param {Color3} color
  35501. */
  35502. UniformBuffer.prototype.addColor3 = function (name, color) {
  35503. var temp = new Array();
  35504. color.toArray(temp);
  35505. this.addUniform(name, temp);
  35506. };
  35507. /**
  35508. * Wrapper for addUniform.
  35509. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35510. * @param {Color3} color
  35511. * @param {number} alpha
  35512. */
  35513. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35514. var temp = new Array();
  35515. color.toArray(temp);
  35516. temp.push(alpha);
  35517. this.addUniform(name, temp);
  35518. };
  35519. /**
  35520. * Wrapper for addUniform.
  35521. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35522. * @param {Vector3} vector
  35523. */
  35524. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35525. var temp = new Array();
  35526. vector.toArray(temp);
  35527. this.addUniform(name, temp);
  35528. };
  35529. /**
  35530. * Wrapper for addUniform.
  35531. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35532. */
  35533. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35534. this.addUniform(name, 12);
  35535. };
  35536. /**
  35537. * Wrapper for addUniform.
  35538. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35539. */
  35540. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35541. this.addUniform(name, 8);
  35542. };
  35543. /**
  35544. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35545. */
  35546. UniformBuffer.prototype.create = function () {
  35547. if (this._noUBO) {
  35548. return;
  35549. }
  35550. if (this._buffer) {
  35551. return; // nothing to do
  35552. }
  35553. // See spec, alignment must be filled as a vec4
  35554. this._fillAlignment(4);
  35555. this._bufferData = new Float32Array(this._data);
  35556. this._rebuild();
  35557. this._needSync = true;
  35558. };
  35559. /** @hidden */
  35560. UniformBuffer.prototype._rebuild = function () {
  35561. if (this._noUBO) {
  35562. return;
  35563. }
  35564. if (this._dynamic) {
  35565. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35566. }
  35567. else {
  35568. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35569. }
  35570. };
  35571. /**
  35572. * Updates the WebGL Uniform Buffer on the GPU.
  35573. * If the `dynamic` flag is set to true, no cache comparison is done.
  35574. * Otherwise, the buffer will be updated only if the cache differs.
  35575. */
  35576. UniformBuffer.prototype.update = function () {
  35577. if (!this._buffer) {
  35578. this.create();
  35579. return;
  35580. }
  35581. if (!this._dynamic && !this._needSync) {
  35582. return;
  35583. }
  35584. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35585. this._needSync = false;
  35586. };
  35587. /**
  35588. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35589. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35590. * @param {number[]|Float32Array} data Flattened data
  35591. * @param {number} size Size of the data.
  35592. */
  35593. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35594. var location = this._uniformLocations[uniformName];
  35595. if (location === undefined) {
  35596. if (this._buffer) {
  35597. // Cannot add an uniform if the buffer is already created
  35598. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35599. return;
  35600. }
  35601. this.addUniform(uniformName, size);
  35602. location = this._uniformLocations[uniformName];
  35603. }
  35604. if (!this._buffer) {
  35605. this.create();
  35606. }
  35607. if (!this._dynamic) {
  35608. // Cache for static uniform buffers
  35609. var changed = false;
  35610. for (var i = 0; i < size; i++) {
  35611. if (this._bufferData[location + i] !== data[i]) {
  35612. changed = true;
  35613. this._bufferData[location + i] = data[i];
  35614. }
  35615. }
  35616. this._needSync = this._needSync || changed;
  35617. }
  35618. else {
  35619. // No cache for dynamic
  35620. for (var i = 0; i < size; i++) {
  35621. this._bufferData[location + i] = data[i];
  35622. }
  35623. }
  35624. };
  35625. // Update methods
  35626. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35627. // To match std140, matrix must be realigned
  35628. for (var i = 0; i < 3; i++) {
  35629. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35630. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35631. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35632. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35633. }
  35634. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35635. };
  35636. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35637. this._currentEffect.setMatrix3x3(name, matrix);
  35638. };
  35639. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35640. this._currentEffect.setMatrix2x2(name, matrix);
  35641. };
  35642. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35643. // To match std140, matrix must be realigned
  35644. for (var i = 0; i < 2; i++) {
  35645. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35646. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35647. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35648. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35649. }
  35650. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35651. };
  35652. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35653. this._currentEffect.setFloat(name, x);
  35654. };
  35655. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35656. UniformBuffer._tempBuffer[0] = x;
  35657. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35658. };
  35659. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35660. if (suffix === void 0) { suffix = ""; }
  35661. this._currentEffect.setFloat2(name + suffix, x, y);
  35662. };
  35663. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35664. if (suffix === void 0) { suffix = ""; }
  35665. UniformBuffer._tempBuffer[0] = x;
  35666. UniformBuffer._tempBuffer[1] = y;
  35667. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35668. };
  35669. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35670. if (suffix === void 0) { suffix = ""; }
  35671. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35672. };
  35673. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35674. if (suffix === void 0) { suffix = ""; }
  35675. UniformBuffer._tempBuffer[0] = x;
  35676. UniformBuffer._tempBuffer[1] = y;
  35677. UniformBuffer._tempBuffer[2] = z;
  35678. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35679. };
  35680. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35681. if (suffix === void 0) { suffix = ""; }
  35682. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35683. };
  35684. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35685. if (suffix === void 0) { suffix = ""; }
  35686. UniformBuffer._tempBuffer[0] = x;
  35687. UniformBuffer._tempBuffer[1] = y;
  35688. UniformBuffer._tempBuffer[2] = z;
  35689. UniformBuffer._tempBuffer[3] = w;
  35690. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35691. };
  35692. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35693. this._currentEffect.setMatrix(name, mat);
  35694. };
  35695. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35696. this.updateUniform(name, mat.toArray(), 16);
  35697. };
  35698. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35699. this._currentEffect.setVector3(name, vector);
  35700. };
  35701. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35702. vector.toArray(UniformBuffer._tempBuffer);
  35703. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35704. };
  35705. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35706. this._currentEffect.setVector4(name, vector);
  35707. };
  35708. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35709. vector.toArray(UniformBuffer._tempBuffer);
  35710. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35711. };
  35712. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35713. if (suffix === void 0) { suffix = ""; }
  35714. this._currentEffect.setColor3(name + suffix, color);
  35715. };
  35716. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35717. if (suffix === void 0) { suffix = ""; }
  35718. color.toArray(UniformBuffer._tempBuffer);
  35719. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35720. };
  35721. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35722. if (suffix === void 0) { suffix = ""; }
  35723. this._currentEffect.setColor4(name + suffix, color, alpha);
  35724. };
  35725. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35726. if (suffix === void 0) { suffix = ""; }
  35727. color.toArray(UniformBuffer._tempBuffer);
  35728. UniformBuffer._tempBuffer[3] = alpha;
  35729. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35730. };
  35731. /**
  35732. * Sets a sampler uniform on the effect.
  35733. * @param {string} name Name of the sampler.
  35734. * @param {Texture} texture
  35735. */
  35736. UniformBuffer.prototype.setTexture = function (name, texture) {
  35737. this._currentEffect.setTexture(name, texture);
  35738. };
  35739. /**
  35740. * Directly updates the value of the uniform in the cache AND on the GPU.
  35741. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35742. * @param {number[]|Float32Array} data Flattened data
  35743. */
  35744. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35745. this.updateUniform(uniformName, data, data.length);
  35746. this.update();
  35747. };
  35748. /**
  35749. * Binds this uniform buffer to an effect.
  35750. * @param {Effect} effect
  35751. * @param {string} name Name of the uniform block in the shader.
  35752. */
  35753. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35754. this._currentEffect = effect;
  35755. if (this._noUBO || !this._buffer) {
  35756. return;
  35757. }
  35758. effect.bindUniformBuffer(this._buffer, name);
  35759. };
  35760. /**
  35761. * Disposes the uniform buffer.
  35762. */
  35763. UniformBuffer.prototype.dispose = function () {
  35764. if (this._noUBO) {
  35765. return;
  35766. }
  35767. var index = this._engine._uniformBuffers.indexOf(this);
  35768. if (index !== -1) {
  35769. this._engine._uniformBuffers.splice(index, 1);
  35770. }
  35771. if (!this._buffer) {
  35772. return;
  35773. }
  35774. if (this._engine._releaseBuffer(this._buffer)) {
  35775. this._buffer = null;
  35776. }
  35777. };
  35778. // Pool for avoiding memory leaks
  35779. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35780. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35781. return UniformBuffer;
  35782. }());
  35783. BABYLON.UniformBuffer = UniformBuffer;
  35784. })(BABYLON || (BABYLON = {}));
  35785. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35786. var BABYLON;
  35787. (function (BABYLON) {
  35788. /**
  35789. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35790. */
  35791. var VertexData = /** @class */ (function () {
  35792. function VertexData() {
  35793. }
  35794. /**
  35795. * Uses the passed data array to set the set the values for the specified kind of data
  35796. * @param data a linear array of floating numbers
  35797. * @param kind the type of data that is being set, eg positions, colors etc
  35798. */
  35799. VertexData.prototype.set = function (data, kind) {
  35800. switch (kind) {
  35801. case BABYLON.VertexBuffer.PositionKind:
  35802. this.positions = data;
  35803. break;
  35804. case BABYLON.VertexBuffer.NormalKind:
  35805. this.normals = data;
  35806. break;
  35807. case BABYLON.VertexBuffer.TangentKind:
  35808. this.tangents = data;
  35809. break;
  35810. case BABYLON.VertexBuffer.UVKind:
  35811. this.uvs = data;
  35812. break;
  35813. case BABYLON.VertexBuffer.UV2Kind:
  35814. this.uvs2 = data;
  35815. break;
  35816. case BABYLON.VertexBuffer.UV3Kind:
  35817. this.uvs3 = data;
  35818. break;
  35819. case BABYLON.VertexBuffer.UV4Kind:
  35820. this.uvs4 = data;
  35821. break;
  35822. case BABYLON.VertexBuffer.UV5Kind:
  35823. this.uvs5 = data;
  35824. break;
  35825. case BABYLON.VertexBuffer.UV6Kind:
  35826. this.uvs6 = data;
  35827. break;
  35828. case BABYLON.VertexBuffer.ColorKind:
  35829. this.colors = data;
  35830. break;
  35831. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35832. this.matricesIndices = data;
  35833. break;
  35834. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35835. this.matricesWeights = data;
  35836. break;
  35837. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35838. this.matricesIndicesExtra = data;
  35839. break;
  35840. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35841. this.matricesWeightsExtra = data;
  35842. break;
  35843. }
  35844. };
  35845. /**
  35846. * Associates the vertexData to the passed Mesh.
  35847. * Sets it as updatable or not (default `false`)
  35848. * @param mesh the mesh the vertexData is applied to
  35849. * @param updatable when used and having the value true allows new data to update the vertexData
  35850. * @returns the VertexData
  35851. */
  35852. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35853. this._applyTo(mesh, updatable);
  35854. return this;
  35855. };
  35856. /**
  35857. * Associates the vertexData to the passed Geometry.
  35858. * Sets it as updatable or not (default `false`)
  35859. * @param geometry the geometry the vertexData is applied to
  35860. * @param updatable when used and having the value true allows new data to update the vertexData
  35861. * @returns VertexData
  35862. */
  35863. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35864. this._applyTo(geometry, updatable);
  35865. return this;
  35866. };
  35867. /**
  35868. * Updates the associated mesh
  35869. * @param mesh the mesh to be updated
  35870. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35871. * @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
  35872. * @returns VertexData
  35873. */
  35874. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35875. this._update(mesh);
  35876. return this;
  35877. };
  35878. /**
  35879. * Updates the associated geometry
  35880. * @param geometry the geometry to be updated
  35881. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35882. * @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
  35883. * @returns VertexData.
  35884. */
  35885. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35886. this._update(geometry);
  35887. return this;
  35888. };
  35889. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  35890. if (updatable === void 0) { updatable = false; }
  35891. if (this.positions) {
  35892. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  35893. }
  35894. if (this.normals) {
  35895. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  35896. }
  35897. if (this.tangents) {
  35898. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  35899. }
  35900. if (this.uvs) {
  35901. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  35902. }
  35903. if (this.uvs2) {
  35904. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  35905. }
  35906. if (this.uvs3) {
  35907. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  35908. }
  35909. if (this.uvs4) {
  35910. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  35911. }
  35912. if (this.uvs5) {
  35913. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  35914. }
  35915. if (this.uvs6) {
  35916. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  35917. }
  35918. if (this.colors) {
  35919. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  35920. }
  35921. if (this.matricesIndices) {
  35922. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  35923. }
  35924. if (this.matricesWeights) {
  35925. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  35926. }
  35927. if (this.matricesIndicesExtra) {
  35928. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  35929. }
  35930. if (this.matricesWeightsExtra) {
  35931. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  35932. }
  35933. if (this.indices) {
  35934. meshOrGeometry.setIndices(this.indices, null, updatable);
  35935. }
  35936. else {
  35937. meshOrGeometry.setIndices([], null);
  35938. }
  35939. return this;
  35940. };
  35941. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  35942. if (this.positions) {
  35943. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  35944. }
  35945. if (this.normals) {
  35946. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  35947. }
  35948. if (this.tangents) {
  35949. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  35950. }
  35951. if (this.uvs) {
  35952. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  35953. }
  35954. if (this.uvs2) {
  35955. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  35956. }
  35957. if (this.uvs3) {
  35958. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  35959. }
  35960. if (this.uvs4) {
  35961. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  35962. }
  35963. if (this.uvs5) {
  35964. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  35965. }
  35966. if (this.uvs6) {
  35967. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  35968. }
  35969. if (this.colors) {
  35970. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  35971. }
  35972. if (this.matricesIndices) {
  35973. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  35974. }
  35975. if (this.matricesWeights) {
  35976. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  35977. }
  35978. if (this.matricesIndicesExtra) {
  35979. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  35980. }
  35981. if (this.matricesWeightsExtra) {
  35982. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  35983. }
  35984. if (this.indices) {
  35985. meshOrGeometry.setIndices(this.indices, null);
  35986. }
  35987. return this;
  35988. };
  35989. /**
  35990. * Transforms each position and each normal of the vertexData according to the passed Matrix
  35991. * @param matrix the transforming matrix
  35992. * @returns the VertexData
  35993. */
  35994. VertexData.prototype.transform = function (matrix) {
  35995. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  35996. var transformed = BABYLON.Vector3.Zero();
  35997. var index;
  35998. if (this.positions) {
  35999. var position = BABYLON.Vector3.Zero();
  36000. for (index = 0; index < this.positions.length; index += 3) {
  36001. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36002. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36003. this.positions[index] = transformed.x;
  36004. this.positions[index + 1] = transformed.y;
  36005. this.positions[index + 2] = transformed.z;
  36006. }
  36007. }
  36008. if (this.normals) {
  36009. var normal = BABYLON.Vector3.Zero();
  36010. for (index = 0; index < this.normals.length; index += 3) {
  36011. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36012. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36013. this.normals[index] = transformed.x;
  36014. this.normals[index + 1] = transformed.y;
  36015. this.normals[index + 2] = transformed.z;
  36016. }
  36017. }
  36018. if (this.tangents) {
  36019. var tangent = BABYLON.Vector4.Zero();
  36020. var tangentTransformed = BABYLON.Vector4.Zero();
  36021. for (index = 0; index < this.tangents.length; index += 4) {
  36022. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36023. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36024. this.tangents[index] = tangentTransformed.x;
  36025. this.tangents[index + 1] = tangentTransformed.y;
  36026. this.tangents[index + 2] = tangentTransformed.z;
  36027. this.tangents[index + 3] = tangentTransformed.w;
  36028. }
  36029. }
  36030. if (flip && this.indices) {
  36031. for (index = 0; index < this.indices.length; index += 3) {
  36032. var tmp = this.indices[index + 1];
  36033. this.indices[index + 1] = this.indices[index + 2];
  36034. this.indices[index + 2] = tmp;
  36035. }
  36036. }
  36037. return this;
  36038. };
  36039. /**
  36040. * Merges the passed VertexData into the current one
  36041. * @param other the VertexData to be merged into the current one
  36042. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36043. * @returns the modified VertexData
  36044. */
  36045. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36046. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36047. this._validate();
  36048. other._validate();
  36049. if (!this.normals !== !other.normals ||
  36050. !this.tangents !== !other.tangents ||
  36051. !this.uvs !== !other.uvs ||
  36052. !this.uvs2 !== !other.uvs2 ||
  36053. !this.uvs3 !== !other.uvs3 ||
  36054. !this.uvs4 !== !other.uvs4 ||
  36055. !this.uvs5 !== !other.uvs5 ||
  36056. !this.uvs6 !== !other.uvs6 ||
  36057. !this.colors !== !other.colors ||
  36058. !this.matricesIndices !== !other.matricesIndices ||
  36059. !this.matricesWeights !== !other.matricesWeights ||
  36060. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36061. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36062. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36063. }
  36064. if (other.indices) {
  36065. if (!this.indices) {
  36066. this.indices = [];
  36067. }
  36068. var offset = this.positions ? this.positions.length / 3 : 0;
  36069. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36070. if (isSrcTypedArray) {
  36071. var len = this.indices.length + other.indices.length;
  36072. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36073. temp.set(this.indices);
  36074. var decal = this.indices.length;
  36075. for (var index = 0; index < other.indices.length; index++) {
  36076. temp[decal + index] = other.indices[index] + offset;
  36077. }
  36078. this.indices = temp;
  36079. }
  36080. else {
  36081. for (var index = 0; index < other.indices.length; index++) {
  36082. this.indices.push(other.indices[index] + offset);
  36083. }
  36084. }
  36085. }
  36086. this.positions = this._mergeElement(this.positions, other.positions);
  36087. this.normals = this._mergeElement(this.normals, other.normals);
  36088. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36089. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36090. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36091. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36092. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36093. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36094. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36095. this.colors = this._mergeElement(this.colors, other.colors);
  36096. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36097. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36098. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36099. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36100. return this;
  36101. };
  36102. VertexData.prototype._mergeElement = function (source, other) {
  36103. if (!source) {
  36104. return other;
  36105. }
  36106. if (!other) {
  36107. return source;
  36108. }
  36109. var len = other.length + source.length;
  36110. var isSrcTypedArray = source instanceof Float32Array;
  36111. var isOthTypedArray = other instanceof Float32Array;
  36112. // use non-loop method when the source is Float32Array
  36113. if (isSrcTypedArray) {
  36114. var ret32 = new Float32Array(len);
  36115. ret32.set(source);
  36116. ret32.set(other, source.length);
  36117. return ret32;
  36118. // source is number[], when other is also use concat
  36119. }
  36120. else if (!isOthTypedArray) {
  36121. return source.concat(other);
  36122. // source is a number[], but other is a Float32Array, loop required
  36123. }
  36124. else {
  36125. var ret = source.slice(0); // copy source to a separate array
  36126. for (var i = 0, len = other.length; i < len; i++) {
  36127. ret.push(other[i]);
  36128. }
  36129. return ret;
  36130. }
  36131. };
  36132. VertexData.prototype._validate = function () {
  36133. if (!this.positions) {
  36134. throw new Error("Positions are required");
  36135. }
  36136. var getElementCount = function (kind, values) {
  36137. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36138. if ((values.length % stride) !== 0) {
  36139. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36140. }
  36141. return values.length / stride;
  36142. };
  36143. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36144. var validateElementCount = function (kind, values) {
  36145. var elementCount = getElementCount(kind, values);
  36146. if (elementCount !== positionsElementCount) {
  36147. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36148. }
  36149. };
  36150. if (this.normals)
  36151. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36152. if (this.tangents)
  36153. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36154. if (this.uvs)
  36155. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36156. if (this.uvs2)
  36157. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36158. if (this.uvs3)
  36159. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36160. if (this.uvs4)
  36161. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36162. if (this.uvs5)
  36163. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36164. if (this.uvs6)
  36165. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36166. if (this.colors)
  36167. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36168. if (this.matricesIndices)
  36169. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36170. if (this.matricesWeights)
  36171. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36172. if (this.matricesIndicesExtra)
  36173. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36174. if (this.matricesWeightsExtra)
  36175. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36176. };
  36177. /**
  36178. * Serializes the VertexData
  36179. * @returns a serialized object
  36180. */
  36181. VertexData.prototype.serialize = function () {
  36182. var serializationObject = this.serialize();
  36183. if (this.positions) {
  36184. serializationObject.positions = this.positions;
  36185. }
  36186. if (this.normals) {
  36187. serializationObject.normals = this.normals;
  36188. }
  36189. if (this.tangents) {
  36190. serializationObject.tangents = this.tangents;
  36191. }
  36192. if (this.uvs) {
  36193. serializationObject.uvs = this.uvs;
  36194. }
  36195. if (this.uvs2) {
  36196. serializationObject.uvs2 = this.uvs2;
  36197. }
  36198. if (this.uvs3) {
  36199. serializationObject.uvs3 = this.uvs3;
  36200. }
  36201. if (this.uvs4) {
  36202. serializationObject.uvs4 = this.uvs4;
  36203. }
  36204. if (this.uvs5) {
  36205. serializationObject.uvs5 = this.uvs5;
  36206. }
  36207. if (this.uvs6) {
  36208. serializationObject.uvs6 = this.uvs6;
  36209. }
  36210. if (this.colors) {
  36211. serializationObject.colors = this.colors;
  36212. }
  36213. if (this.matricesIndices) {
  36214. serializationObject.matricesIndices = this.matricesIndices;
  36215. serializationObject.matricesIndices._isExpanded = true;
  36216. }
  36217. if (this.matricesWeights) {
  36218. serializationObject.matricesWeights = this.matricesWeights;
  36219. }
  36220. if (this.matricesIndicesExtra) {
  36221. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36222. serializationObject.matricesIndicesExtra._isExpanded = true;
  36223. }
  36224. if (this.matricesWeightsExtra) {
  36225. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36226. }
  36227. serializationObject.indices = this.indices;
  36228. return serializationObject;
  36229. };
  36230. // Statics
  36231. /**
  36232. * Extracts the vertexData from a mesh
  36233. * @param mesh the mesh from which to extract the VertexData
  36234. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36235. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36236. * @returns the object VertexData associated to the passed mesh
  36237. */
  36238. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36239. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36240. };
  36241. /**
  36242. * Extracts the vertexData from the geometry
  36243. * @param geometry the geometry from which to extract the VertexData
  36244. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36245. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36246. * @returns the object VertexData associated to the passed mesh
  36247. */
  36248. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36249. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36250. };
  36251. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36252. var result = new VertexData();
  36253. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36254. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36255. }
  36256. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36257. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36258. }
  36259. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36260. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36261. }
  36262. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36263. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36264. }
  36265. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36266. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36267. }
  36268. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36269. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36270. }
  36271. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36272. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36273. }
  36274. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36275. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36276. }
  36277. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36278. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36279. }
  36280. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36281. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36282. }
  36283. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36284. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36285. }
  36286. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36287. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36288. }
  36289. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36290. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36291. }
  36292. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36293. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36294. }
  36295. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36296. return result;
  36297. };
  36298. /**
  36299. * Creates the VertexData for a Ribbon
  36300. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36301. * * pathArray array of paths, each of which an array of successive Vector3
  36302. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36303. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36304. * * 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
  36305. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36306. * * 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)
  36307. * * 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)
  36308. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36309. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36310. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36311. * @returns the VertexData of the ribbon
  36312. */
  36313. VertexData.CreateRibbon = function (options) {
  36314. var pathArray = options.pathArray;
  36315. var closeArray = options.closeArray || false;
  36316. var closePath = options.closePath || false;
  36317. var invertUV = options.invertUV || false;
  36318. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36319. var offset = options.offset || defaultOffset;
  36320. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36321. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36322. var customUV = options.uvs;
  36323. var customColors = options.colors;
  36324. var positions = [];
  36325. var indices = [];
  36326. var normals = [];
  36327. var uvs = [];
  36328. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36329. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36330. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36331. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36332. var minlg; // minimal length among all paths from pathArray
  36333. var lg = []; // array of path lengths : nb of vertex per path
  36334. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36335. var p; // path iterator
  36336. var i; // point iterator
  36337. var j; // point iterator
  36338. // if single path in pathArray
  36339. if (pathArray.length < 2) {
  36340. var ar1 = [];
  36341. var ar2 = [];
  36342. for (i = 0; i < pathArray[0].length - offset; i++) {
  36343. ar1.push(pathArray[0][i]);
  36344. ar2.push(pathArray[0][i + offset]);
  36345. }
  36346. pathArray = [ar1, ar2];
  36347. }
  36348. // positions and horizontal distances (u)
  36349. var idc = 0;
  36350. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36351. var path;
  36352. var l;
  36353. minlg = pathArray[0].length;
  36354. var vectlg;
  36355. var dist;
  36356. for (p = 0; p < pathArray.length; p++) {
  36357. uTotalDistance[p] = 0;
  36358. us[p] = [0];
  36359. path = pathArray[p];
  36360. l = path.length;
  36361. minlg = (minlg < l) ? minlg : l;
  36362. j = 0;
  36363. while (j < l) {
  36364. positions.push(path[j].x, path[j].y, path[j].z);
  36365. if (j > 0) {
  36366. vectlg = path[j].subtract(path[j - 1]).length();
  36367. dist = vectlg + uTotalDistance[p];
  36368. us[p].push(dist);
  36369. uTotalDistance[p] = dist;
  36370. }
  36371. j++;
  36372. }
  36373. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36374. j--;
  36375. positions.push(path[0].x, path[0].y, path[0].z);
  36376. vectlg = path[j].subtract(path[0]).length();
  36377. dist = vectlg + uTotalDistance[p];
  36378. us[p].push(dist);
  36379. uTotalDistance[p] = dist;
  36380. }
  36381. lg[p] = l + closePathCorr;
  36382. idx[p] = idc;
  36383. idc += (l + closePathCorr);
  36384. }
  36385. // vertical distances (v)
  36386. var path1;
  36387. var path2;
  36388. var vertex1 = null;
  36389. var vertex2 = null;
  36390. for (i = 0; i < minlg + closePathCorr; i++) {
  36391. vTotalDistance[i] = 0;
  36392. vs[i] = [0];
  36393. for (p = 0; p < pathArray.length - 1; p++) {
  36394. path1 = pathArray[p];
  36395. path2 = pathArray[p + 1];
  36396. if (i === minlg) { // closePath
  36397. vertex1 = path1[0];
  36398. vertex2 = path2[0];
  36399. }
  36400. else {
  36401. vertex1 = path1[i];
  36402. vertex2 = path2[i];
  36403. }
  36404. vectlg = vertex2.subtract(vertex1).length();
  36405. dist = vectlg + vTotalDistance[i];
  36406. vs[i].push(dist);
  36407. vTotalDistance[i] = dist;
  36408. }
  36409. if (closeArray && vertex2 && vertex1) {
  36410. path1 = pathArray[p];
  36411. path2 = pathArray[0];
  36412. if (i === minlg) { // closePath
  36413. vertex2 = path2[0];
  36414. }
  36415. vectlg = vertex2.subtract(vertex1).length();
  36416. dist = vectlg + vTotalDistance[i];
  36417. vTotalDistance[i] = dist;
  36418. }
  36419. }
  36420. // uvs
  36421. var u;
  36422. var v;
  36423. if (customUV) {
  36424. for (p = 0; p < customUV.length; p++) {
  36425. uvs.push(customUV[p].x, customUV[p].y);
  36426. }
  36427. }
  36428. else {
  36429. for (p = 0; p < pathArray.length; p++) {
  36430. for (i = 0; i < minlg + closePathCorr; i++) {
  36431. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36432. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36433. if (invertUV) {
  36434. uvs.push(v, u);
  36435. }
  36436. else {
  36437. uvs.push(u, v);
  36438. }
  36439. }
  36440. }
  36441. }
  36442. // indices
  36443. p = 0; // path index
  36444. var pi = 0; // positions array index
  36445. var l1 = lg[p] - 1; // path1 length
  36446. var l2 = lg[p + 1] - 1; // path2 length
  36447. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36448. var shft = idx[1] - idx[0]; // shift
  36449. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36450. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36451. // 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
  36452. indices.push(pi, pi + shft, pi + 1);
  36453. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36454. pi += 1;
  36455. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36456. p++;
  36457. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36458. shft = idx[0] - idx[p];
  36459. l1 = lg[p] - 1;
  36460. l2 = lg[0] - 1;
  36461. }
  36462. else {
  36463. shft = idx[p + 1] - idx[p];
  36464. l1 = lg[p] - 1;
  36465. l2 = lg[p + 1] - 1;
  36466. }
  36467. pi = idx[p];
  36468. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36469. }
  36470. }
  36471. // normals
  36472. VertexData.ComputeNormals(positions, indices, normals);
  36473. if (closePath) { // update both the first and last vertex normals to their average value
  36474. var indexFirst = 0;
  36475. var indexLast = 0;
  36476. for (p = 0; p < pathArray.length; p++) {
  36477. indexFirst = idx[p] * 3;
  36478. if (p + 1 < pathArray.length) {
  36479. indexLast = (idx[p + 1] - 1) * 3;
  36480. }
  36481. else {
  36482. indexLast = normals.length - 3;
  36483. }
  36484. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36485. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36486. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36487. normals[indexLast] = normals[indexFirst];
  36488. normals[indexLast + 1] = normals[indexFirst + 1];
  36489. normals[indexLast + 2] = normals[indexFirst + 2];
  36490. }
  36491. }
  36492. // sides
  36493. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36494. // Colors
  36495. var colors = null;
  36496. if (customColors) {
  36497. colors = new Float32Array(customColors.length * 4);
  36498. for (var c = 0; c < customColors.length; c++) {
  36499. colors[c * 4] = customColors[c].r;
  36500. colors[c * 4 + 1] = customColors[c].g;
  36501. colors[c * 4 + 2] = customColors[c].b;
  36502. colors[c * 4 + 3] = customColors[c].a;
  36503. }
  36504. }
  36505. // Result
  36506. var vertexData = new VertexData();
  36507. var positions32 = new Float32Array(positions);
  36508. var normals32 = new Float32Array(normals);
  36509. var uvs32 = new Float32Array(uvs);
  36510. vertexData.indices = indices;
  36511. vertexData.positions = positions32;
  36512. vertexData.normals = normals32;
  36513. vertexData.uvs = uvs32;
  36514. if (colors) {
  36515. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36516. }
  36517. if (closePath) {
  36518. vertexData._idx = idx;
  36519. }
  36520. return vertexData;
  36521. };
  36522. /**
  36523. * Creates the VertexData for a box
  36524. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36525. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36526. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36527. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36528. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36529. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36530. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36531. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36532. * * 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)
  36533. * * 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)
  36534. * @returns the VertexData of the box
  36535. */
  36536. VertexData.CreateBox = function (options) {
  36537. var normalsSource = [
  36538. new BABYLON.Vector3(0, 0, 1),
  36539. new BABYLON.Vector3(0, 0, -1),
  36540. new BABYLON.Vector3(1, 0, 0),
  36541. new BABYLON.Vector3(-1, 0, 0),
  36542. new BABYLON.Vector3(0, 1, 0),
  36543. new BABYLON.Vector3(0, -1, 0)
  36544. ];
  36545. var indices = [];
  36546. var positions = [];
  36547. var normals = [];
  36548. var uvs = [];
  36549. var width = options.width || options.size || 1;
  36550. var height = options.height || options.size || 1;
  36551. var depth = options.depth || options.size || 1;
  36552. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36553. var faceUV = options.faceUV || new Array(6);
  36554. var faceColors = options.faceColors;
  36555. var colors = [];
  36556. // default face colors and UV if undefined
  36557. for (var f = 0; f < 6; f++) {
  36558. if (faceUV[f] === undefined) {
  36559. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36560. }
  36561. if (faceColors && faceColors[f] === undefined) {
  36562. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36563. }
  36564. }
  36565. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36566. // Create each face in turn.
  36567. for (var index = 0; index < normalsSource.length; index++) {
  36568. var normal = normalsSource[index];
  36569. // Get two vectors perpendicular to the face normal and to each other.
  36570. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36571. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36572. // Six indices (two triangles) per face.
  36573. var verticesLength = positions.length / 3;
  36574. indices.push(verticesLength);
  36575. indices.push(verticesLength + 1);
  36576. indices.push(verticesLength + 2);
  36577. indices.push(verticesLength);
  36578. indices.push(verticesLength + 2);
  36579. indices.push(verticesLength + 3);
  36580. // Four vertices per face.
  36581. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36582. positions.push(vertex.x, vertex.y, vertex.z);
  36583. normals.push(normal.x, normal.y, normal.z);
  36584. uvs.push(faceUV[index].z, faceUV[index].w);
  36585. if (faceColors) {
  36586. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36587. }
  36588. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36589. positions.push(vertex.x, vertex.y, vertex.z);
  36590. normals.push(normal.x, normal.y, normal.z);
  36591. uvs.push(faceUV[index].x, faceUV[index].w);
  36592. if (faceColors) {
  36593. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36594. }
  36595. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36596. positions.push(vertex.x, vertex.y, vertex.z);
  36597. normals.push(normal.x, normal.y, normal.z);
  36598. uvs.push(faceUV[index].x, faceUV[index].y);
  36599. if (faceColors) {
  36600. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36601. }
  36602. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36603. positions.push(vertex.x, vertex.y, vertex.z);
  36604. normals.push(normal.x, normal.y, normal.z);
  36605. uvs.push(faceUV[index].z, faceUV[index].y);
  36606. if (faceColors) {
  36607. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36608. }
  36609. }
  36610. // sides
  36611. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36612. // Result
  36613. var vertexData = new VertexData();
  36614. vertexData.indices = indices;
  36615. vertexData.positions = positions;
  36616. vertexData.normals = normals;
  36617. vertexData.uvs = uvs;
  36618. if (faceColors) {
  36619. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36620. vertexData.colors = totalColors;
  36621. }
  36622. return vertexData;
  36623. };
  36624. /**
  36625. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36626. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36627. * * segments sets the number of horizontal strips optional, default 32
  36628. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36629. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36630. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36631. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36632. * * 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
  36633. * * 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
  36634. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36635. * * 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)
  36636. * * 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)
  36637. * @returns the VertexData of the ellipsoid
  36638. */
  36639. VertexData.CreateSphere = function (options) {
  36640. var segments = options.segments || 32;
  36641. var diameterX = options.diameterX || options.diameter || 1;
  36642. var diameterY = options.diameterY || options.diameter || 1;
  36643. var diameterZ = options.diameterZ || options.diameter || 1;
  36644. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36645. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36646. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36647. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36648. var totalZRotationSteps = 2 + segments;
  36649. var totalYRotationSteps = 2 * totalZRotationSteps;
  36650. var indices = [];
  36651. var positions = [];
  36652. var normals = [];
  36653. var uvs = [];
  36654. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36655. var normalizedZ = zRotationStep / totalZRotationSteps;
  36656. var angleZ = normalizedZ * Math.PI * slice;
  36657. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36658. var normalizedY = yRotationStep / totalYRotationSteps;
  36659. var angleY = normalizedY * Math.PI * 2 * arc;
  36660. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36661. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36662. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36663. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36664. var vertex = complete.multiply(radius);
  36665. var normal = complete.divide(radius).normalize();
  36666. positions.push(vertex.x, vertex.y, vertex.z);
  36667. normals.push(normal.x, normal.y, normal.z);
  36668. uvs.push(normalizedY, normalizedZ);
  36669. }
  36670. if (zRotationStep > 0) {
  36671. var verticesCount = positions.length / 3;
  36672. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36673. indices.push((firstIndex));
  36674. indices.push((firstIndex + 1));
  36675. indices.push(firstIndex + totalYRotationSteps + 1);
  36676. indices.push((firstIndex + totalYRotationSteps + 1));
  36677. indices.push((firstIndex + 1));
  36678. indices.push((firstIndex + totalYRotationSteps + 2));
  36679. }
  36680. }
  36681. }
  36682. // Sides
  36683. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36684. // Result
  36685. var vertexData = new VertexData();
  36686. vertexData.indices = indices;
  36687. vertexData.positions = positions;
  36688. vertexData.normals = normals;
  36689. vertexData.uvs = uvs;
  36690. return vertexData;
  36691. };
  36692. /**
  36693. * Creates the VertexData for a cylinder, cone or prism
  36694. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36695. * * height sets the height (y direction) of the cylinder, optional, default 2
  36696. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36697. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36698. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36699. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36700. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36701. * * 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
  36702. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36703. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36704. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36705. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36706. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36707. * * 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)
  36708. * * 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)
  36709. * @returns the VertexData of the cylinder, cone or prism
  36710. */
  36711. VertexData.CreateCylinder = function (options) {
  36712. var height = options.height || 2;
  36713. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36714. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36715. var tessellation = options.tessellation || 24;
  36716. var subdivisions = options.subdivisions || 1;
  36717. var hasRings = options.hasRings ? true : false;
  36718. var enclose = options.enclose ? true : false;
  36719. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36720. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36721. var faceUV = options.faceUV || new Array(3);
  36722. var faceColors = options.faceColors;
  36723. // default face colors and UV if undefined
  36724. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36725. var ringNb = (hasRings) ? subdivisions : 1;
  36726. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36727. var f;
  36728. for (f = 0; f < surfaceNb; f++) {
  36729. if (faceColors && faceColors[f] === undefined) {
  36730. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36731. }
  36732. }
  36733. for (f = 0; f < surfaceNb; f++) {
  36734. if (faceUV && faceUV[f] === undefined) {
  36735. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36736. }
  36737. }
  36738. var indices = new Array();
  36739. var positions = new Array();
  36740. var normals = new Array();
  36741. var uvs = new Array();
  36742. var colors = new Array();
  36743. var angle_step = Math.PI * 2 * arc / tessellation;
  36744. var angle;
  36745. var h;
  36746. var radius;
  36747. var tan = (diameterBottom - diameterTop) / 2 / height;
  36748. var ringVertex = BABYLON.Vector3.Zero();
  36749. var ringNormal = BABYLON.Vector3.Zero();
  36750. var ringFirstVertex = BABYLON.Vector3.Zero();
  36751. var ringFirstNormal = BABYLON.Vector3.Zero();
  36752. var quadNormal = BABYLON.Vector3.Zero();
  36753. var Y = BABYLON.Axis.Y;
  36754. // positions, normals, uvs
  36755. var i;
  36756. var j;
  36757. var r;
  36758. var ringIdx = 1;
  36759. var s = 1; // surface index
  36760. var cs = 0;
  36761. var v = 0;
  36762. for (i = 0; i <= subdivisions; i++) {
  36763. h = i / subdivisions;
  36764. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36765. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36766. for (r = 0; r < ringIdx; r++) {
  36767. if (hasRings) {
  36768. s += r;
  36769. }
  36770. if (enclose) {
  36771. s += 2 * r;
  36772. }
  36773. for (j = 0; j <= tessellation; j++) {
  36774. angle = j * angle_step;
  36775. // position
  36776. ringVertex.x = Math.cos(-angle) * radius;
  36777. ringVertex.y = -height / 2 + h * height;
  36778. ringVertex.z = Math.sin(-angle) * radius;
  36779. // normal
  36780. if (diameterTop === 0 && i === subdivisions) {
  36781. // if no top cap, reuse former normals
  36782. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36783. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36784. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36785. }
  36786. else {
  36787. ringNormal.x = ringVertex.x;
  36788. ringNormal.z = ringVertex.z;
  36789. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36790. ringNormal.normalize();
  36791. }
  36792. // keep first ring vertex values for enclose
  36793. if (j === 0) {
  36794. ringFirstVertex.copyFrom(ringVertex);
  36795. ringFirstNormal.copyFrom(ringNormal);
  36796. }
  36797. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36798. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36799. if (hasRings) {
  36800. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36801. }
  36802. else {
  36803. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36804. }
  36805. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36806. if (faceColors) {
  36807. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36808. }
  36809. }
  36810. // if enclose, add four vertices and their dedicated normals
  36811. if (arc !== 1 && enclose) {
  36812. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36813. positions.push(0, ringVertex.y, 0);
  36814. positions.push(0, ringVertex.y, 0);
  36815. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36816. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36817. quadNormal.normalize();
  36818. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36819. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36820. quadNormal.normalize();
  36821. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36822. if (hasRings) {
  36823. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36824. }
  36825. else {
  36826. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36827. }
  36828. uvs.push(faceUV[s + 1].x, v);
  36829. uvs.push(faceUV[s + 1].z, v);
  36830. if (hasRings) {
  36831. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36832. }
  36833. else {
  36834. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36835. }
  36836. uvs.push(faceUV[s + 2].x, v);
  36837. uvs.push(faceUV[s + 2].z, v);
  36838. if (faceColors) {
  36839. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36840. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36841. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36842. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36843. }
  36844. }
  36845. if (cs !== s) {
  36846. cs = s;
  36847. }
  36848. }
  36849. }
  36850. // indices
  36851. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36852. var s;
  36853. i = 0;
  36854. for (s = 0; s < subdivisions; s++) {
  36855. var i0 = 0;
  36856. var i1 = 0;
  36857. var i2 = 0;
  36858. var i3 = 0;
  36859. for (j = 0; j < tessellation; j++) {
  36860. i0 = i * (e + 1) + j;
  36861. i1 = (i + 1) * (e + 1) + j;
  36862. i2 = i * (e + 1) + (j + 1);
  36863. i3 = (i + 1) * (e + 1) + (j + 1);
  36864. indices.push(i0, i1, i2);
  36865. indices.push(i3, i2, i1);
  36866. }
  36867. if (arc !== 1 && enclose) { // if enclose, add two quads
  36868. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36869. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36870. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36871. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36872. }
  36873. i = (hasRings) ? (i + 2) : (i + 1);
  36874. }
  36875. // Caps
  36876. var createCylinderCap = function (isTop) {
  36877. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36878. if (radius === 0) {
  36879. return;
  36880. }
  36881. // Cap positions, normals & uvs
  36882. var angle;
  36883. var circleVector;
  36884. var i;
  36885. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36886. var c = null;
  36887. if (faceColors) {
  36888. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36889. }
  36890. // cap center
  36891. var vbase = positions.length / 3;
  36892. var offset = isTop ? height / 2 : -height / 2;
  36893. var center = new BABYLON.Vector3(0, offset, 0);
  36894. positions.push(center.x, center.y, center.z);
  36895. normals.push(0, isTop ? 1 : -1, 0);
  36896. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36897. if (c) {
  36898. colors.push(c.r, c.g, c.b, c.a);
  36899. }
  36900. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36901. for (i = 0; i <= tessellation; i++) {
  36902. angle = Math.PI * 2 * i * arc / tessellation;
  36903. var cos = Math.cos(-angle);
  36904. var sin = Math.sin(-angle);
  36905. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36906. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36907. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36908. normals.push(0, isTop ? 1 : -1, 0);
  36909. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36910. if (c) {
  36911. colors.push(c.r, c.g, c.b, c.a);
  36912. }
  36913. }
  36914. // Cap indices
  36915. for (i = 0; i < tessellation; i++) {
  36916. if (!isTop) {
  36917. indices.push(vbase);
  36918. indices.push(vbase + (i + 1));
  36919. indices.push(vbase + (i + 2));
  36920. }
  36921. else {
  36922. indices.push(vbase);
  36923. indices.push(vbase + (i + 2));
  36924. indices.push(vbase + (i + 1));
  36925. }
  36926. }
  36927. };
  36928. // add caps to geometry
  36929. createCylinderCap(false);
  36930. createCylinderCap(true);
  36931. // Sides
  36932. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36933. var vertexData = new VertexData();
  36934. vertexData.indices = indices;
  36935. vertexData.positions = positions;
  36936. vertexData.normals = normals;
  36937. vertexData.uvs = uvs;
  36938. if (faceColors) {
  36939. vertexData.colors = colors;
  36940. }
  36941. return vertexData;
  36942. };
  36943. /**
  36944. * Creates the VertexData for a torus
  36945. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36946. * * diameter the diameter of the torus, optional default 1
  36947. * * thickness the diameter of the tube forming the torus, optional default 0.5
  36948. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36949. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36950. * * 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)
  36951. * * 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)
  36952. * @returns the VertexData of the torus
  36953. */
  36954. VertexData.CreateTorus = function (options) {
  36955. var indices = [];
  36956. var positions = [];
  36957. var normals = [];
  36958. var uvs = [];
  36959. var diameter = options.diameter || 1;
  36960. var thickness = options.thickness || 0.5;
  36961. var tessellation = options.tessellation || 16;
  36962. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36963. var stride = tessellation + 1;
  36964. for (var i = 0; i <= tessellation; i++) {
  36965. var u = i / tessellation;
  36966. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  36967. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  36968. for (var j = 0; j <= tessellation; j++) {
  36969. var v = 1 - j / tessellation;
  36970. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  36971. var dx = Math.cos(innerAngle);
  36972. var dy = Math.sin(innerAngle);
  36973. // Create a vertex.
  36974. var normal = new BABYLON.Vector3(dx, dy, 0);
  36975. var position = normal.scale(thickness / 2);
  36976. var textureCoordinate = new BABYLON.Vector2(u, v);
  36977. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  36978. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  36979. positions.push(position.x, position.y, position.z);
  36980. normals.push(normal.x, normal.y, normal.z);
  36981. uvs.push(textureCoordinate.x, textureCoordinate.y);
  36982. // And create indices for two triangles.
  36983. var nextI = (i + 1) % stride;
  36984. var nextJ = (j + 1) % stride;
  36985. indices.push(i * stride + j);
  36986. indices.push(i * stride + nextJ);
  36987. indices.push(nextI * stride + j);
  36988. indices.push(i * stride + nextJ);
  36989. indices.push(nextI * stride + nextJ);
  36990. indices.push(nextI * stride + j);
  36991. }
  36992. }
  36993. // Sides
  36994. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36995. // Result
  36996. var vertexData = new VertexData();
  36997. vertexData.indices = indices;
  36998. vertexData.positions = positions;
  36999. vertexData.normals = normals;
  37000. vertexData.uvs = uvs;
  37001. return vertexData;
  37002. };
  37003. /**
  37004. * Creates the VertexData of the LineSystem
  37005. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37006. * - lines an array of lines, each line being an array of successive Vector3
  37007. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37008. * @returns the VertexData of the LineSystem
  37009. */
  37010. VertexData.CreateLineSystem = function (options) {
  37011. var indices = [];
  37012. var positions = [];
  37013. var lines = options.lines;
  37014. var colors = options.colors;
  37015. var vertexColors = [];
  37016. var idx = 0;
  37017. for (var l = 0; l < lines.length; l++) {
  37018. var points = lines[l];
  37019. for (var index = 0; index < points.length; index++) {
  37020. positions.push(points[index].x, points[index].y, points[index].z);
  37021. if (colors) {
  37022. var color = colors[l];
  37023. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37024. }
  37025. if (index > 0) {
  37026. indices.push(idx - 1);
  37027. indices.push(idx);
  37028. }
  37029. idx++;
  37030. }
  37031. }
  37032. var vertexData = new VertexData();
  37033. vertexData.indices = indices;
  37034. vertexData.positions = positions;
  37035. if (colors) {
  37036. vertexData.colors = vertexColors;
  37037. }
  37038. return vertexData;
  37039. };
  37040. /**
  37041. * Create the VertexData for a DashedLines
  37042. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37043. * - points an array successive Vector3
  37044. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37045. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37046. * - dashNb the intended total number of dashes, optional, default 200
  37047. * @returns the VertexData for the DashedLines
  37048. */
  37049. VertexData.CreateDashedLines = function (options) {
  37050. var dashSize = options.dashSize || 3;
  37051. var gapSize = options.gapSize || 1;
  37052. var dashNb = options.dashNb || 200;
  37053. var points = options.points;
  37054. var positions = new Array();
  37055. var indices = new Array();
  37056. var curvect = BABYLON.Vector3.Zero();
  37057. var lg = 0;
  37058. var nb = 0;
  37059. var shft = 0;
  37060. var dashshft = 0;
  37061. var curshft = 0;
  37062. var idx = 0;
  37063. var i = 0;
  37064. for (i = 0; i < points.length - 1; i++) {
  37065. points[i + 1].subtractToRef(points[i], curvect);
  37066. lg += curvect.length();
  37067. }
  37068. shft = lg / dashNb;
  37069. dashshft = dashSize * shft / (dashSize + gapSize);
  37070. for (i = 0; i < points.length - 1; i++) {
  37071. points[i + 1].subtractToRef(points[i], curvect);
  37072. nb = Math.floor(curvect.length() / shft);
  37073. curvect.normalize();
  37074. for (var j = 0; j < nb; j++) {
  37075. curshft = shft * j;
  37076. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37077. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37078. indices.push(idx, idx + 1);
  37079. idx += 2;
  37080. }
  37081. }
  37082. // Result
  37083. var vertexData = new VertexData();
  37084. vertexData.positions = positions;
  37085. vertexData.indices = indices;
  37086. return vertexData;
  37087. };
  37088. /**
  37089. * Creates the VertexData for a Ground
  37090. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37091. * - width the width (x direction) of the ground, optional, default 1
  37092. * - height the height (z direction) of the ground, optional, default 1
  37093. * - subdivisions the number of subdivisions per side, optional, default 1
  37094. * @returns the VertexData of the Ground
  37095. */
  37096. VertexData.CreateGround = function (options) {
  37097. var indices = [];
  37098. var positions = [];
  37099. var normals = [];
  37100. var uvs = [];
  37101. var row, col;
  37102. var width = options.width || 1;
  37103. var height = options.height || 1;
  37104. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37105. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37106. for (row = 0; row <= subdivisionsY; row++) {
  37107. for (col = 0; col <= subdivisionsX; col++) {
  37108. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37109. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37110. positions.push(position.x, position.y, position.z);
  37111. normals.push(normal.x, normal.y, normal.z);
  37112. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37113. }
  37114. }
  37115. for (row = 0; row < subdivisionsY; row++) {
  37116. for (col = 0; col < subdivisionsX; col++) {
  37117. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37118. indices.push(col + 1 + row * (subdivisionsX + 1));
  37119. indices.push(col + row * (subdivisionsX + 1));
  37120. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37121. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37122. indices.push(col + row * (subdivisionsX + 1));
  37123. }
  37124. }
  37125. // Result
  37126. var vertexData = new VertexData();
  37127. vertexData.indices = indices;
  37128. vertexData.positions = positions;
  37129. vertexData.normals = normals;
  37130. vertexData.uvs = uvs;
  37131. return vertexData;
  37132. };
  37133. /**
  37134. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37135. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37136. * * xmin the ground minimum X coordinate, optional, default -1
  37137. * * zmin the ground minimum Z coordinate, optional, default -1
  37138. * * xmax the ground maximum X coordinate, optional, default 1
  37139. * * zmax the ground maximum Z coordinate, optional, default 1
  37140. * * 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}
  37141. * * 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}
  37142. * @returns the VertexData of the TiledGround
  37143. */
  37144. VertexData.CreateTiledGround = function (options) {
  37145. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37146. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37147. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37148. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37149. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37150. var precision = options.precision || { w: 1, h: 1 };
  37151. var indices = new Array();
  37152. var positions = new Array();
  37153. var normals = new Array();
  37154. var uvs = new Array();
  37155. var row, col, tileRow, tileCol;
  37156. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37157. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37158. precision.w = (precision.w < 1) ? 1 : precision.w;
  37159. precision.h = (precision.h < 1) ? 1 : precision.h;
  37160. var tileSize = {
  37161. 'w': (xmax - xmin) / subdivisions.w,
  37162. 'h': (zmax - zmin) / subdivisions.h
  37163. };
  37164. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37165. // Indices
  37166. var base = positions.length / 3;
  37167. var rowLength = precision.w + 1;
  37168. for (row = 0; row < precision.h; row++) {
  37169. for (col = 0; col < precision.w; col++) {
  37170. var square = [
  37171. base + col + row * rowLength,
  37172. base + (col + 1) + row * rowLength,
  37173. base + (col + 1) + (row + 1) * rowLength,
  37174. base + col + (row + 1) * rowLength
  37175. ];
  37176. indices.push(square[1]);
  37177. indices.push(square[2]);
  37178. indices.push(square[3]);
  37179. indices.push(square[0]);
  37180. indices.push(square[1]);
  37181. indices.push(square[3]);
  37182. }
  37183. }
  37184. // Position, normals and uvs
  37185. var position = BABYLON.Vector3.Zero();
  37186. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37187. for (row = 0; row <= precision.h; row++) {
  37188. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37189. for (col = 0; col <= precision.w; col++) {
  37190. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37191. position.y = 0;
  37192. positions.push(position.x, position.y, position.z);
  37193. normals.push(normal.x, normal.y, normal.z);
  37194. uvs.push(col / precision.w, row / precision.h);
  37195. }
  37196. }
  37197. }
  37198. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37199. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37200. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37201. }
  37202. }
  37203. // Result
  37204. var vertexData = new VertexData();
  37205. vertexData.indices = indices;
  37206. vertexData.positions = positions;
  37207. vertexData.normals = normals;
  37208. vertexData.uvs = uvs;
  37209. return vertexData;
  37210. };
  37211. /**
  37212. * Creates the VertexData of the Ground designed from a heightmap
  37213. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37214. * * width the width (x direction) of the ground
  37215. * * height the height (z direction) of the ground
  37216. * * subdivisions the number of subdivisions per side
  37217. * * minHeight the minimum altitude on the ground, optional, default 0
  37218. * * maxHeight the maximum altitude on the ground, optional default 1
  37219. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37220. * * buffer the array holding the image color data
  37221. * * bufferWidth the width of image
  37222. * * bufferHeight the height of image
  37223. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  37224. * @returns the VertexData of the Ground designed from a heightmap
  37225. */
  37226. VertexData.CreateGroundFromHeightMap = function (options) {
  37227. var indices = [];
  37228. var positions = [];
  37229. var normals = [];
  37230. var uvs = [];
  37231. var row, col;
  37232. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37233. var alphaFilter = options.alphaFilter || 0.0;
  37234. // Vertices
  37235. for (row = 0; row <= options.subdivisions; row++) {
  37236. for (col = 0; col <= options.subdivisions; col++) {
  37237. 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));
  37238. // Compute height
  37239. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37240. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37241. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37242. var r = options.buffer[pos] / 255.0;
  37243. var g = options.buffer[pos + 1] / 255.0;
  37244. var b = options.buffer[pos + 2] / 255.0;
  37245. var a = options.buffer[pos + 3] / 255.0;
  37246. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37247. // If our alpha channel is not within our filter then we will assign a 'special' height
  37248. // Then when building the indices, we will ignore any vertex that is using the special height
  37249. if (a >= alphaFilter)
  37250. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37251. else {
  37252. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  37253. }
  37254. // Add vertex
  37255. positions.push(position.x, position.y, position.z);
  37256. normals.push(0, 0, 0);
  37257. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37258. }
  37259. }
  37260. // Indices
  37261. for (row = 0; row < options.subdivisions; row++) {
  37262. for (col = 0; col < options.subdivisions; col++) {
  37263. // Calculate Indices
  37264. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  37265. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  37266. var idx3 = (col + row * (options.subdivisions + 1));
  37267. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  37268. // Check that all indices are visible (based on our special height)
  37269. // Only display the vertex if all Indices are visible
  37270. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  37271. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  37272. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  37273. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  37274. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  37275. indices.push(idx1);
  37276. indices.push(idx2);
  37277. indices.push(idx3);
  37278. }
  37279. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  37280. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  37281. indices.push(idx4);
  37282. indices.push(idx1);
  37283. indices.push(idx3);
  37284. }
  37285. }
  37286. }
  37287. // Normals
  37288. VertexData.ComputeNormals(positions, indices, normals);
  37289. // Result
  37290. var vertexData = new VertexData();
  37291. vertexData.indices = indices;
  37292. vertexData.positions = positions;
  37293. vertexData.normals = normals;
  37294. vertexData.uvs = uvs;
  37295. return vertexData;
  37296. };
  37297. /**
  37298. * Creates the VertexData for a Plane
  37299. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37300. * * size sets the width and height of the plane to the value of size, optional default 1
  37301. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37302. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37303. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37304. * * 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)
  37305. * * 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)
  37306. * @returns the VertexData of the box
  37307. */
  37308. VertexData.CreatePlane = function (options) {
  37309. var indices = [];
  37310. var positions = [];
  37311. var normals = [];
  37312. var uvs = [];
  37313. var width = options.width || options.size || 1;
  37314. var height = options.height || options.size || 1;
  37315. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37316. // Vertices
  37317. var halfWidth = width / 2.0;
  37318. var halfHeight = height / 2.0;
  37319. positions.push(-halfWidth, -halfHeight, 0);
  37320. normals.push(0, 0, -1.0);
  37321. uvs.push(0.0, 0.0);
  37322. positions.push(halfWidth, -halfHeight, 0);
  37323. normals.push(0, 0, -1.0);
  37324. uvs.push(1.0, 0.0);
  37325. positions.push(halfWidth, halfHeight, 0);
  37326. normals.push(0, 0, -1.0);
  37327. uvs.push(1.0, 1.0);
  37328. positions.push(-halfWidth, halfHeight, 0);
  37329. normals.push(0, 0, -1.0);
  37330. uvs.push(0.0, 1.0);
  37331. // Indices
  37332. indices.push(0);
  37333. indices.push(1);
  37334. indices.push(2);
  37335. indices.push(0);
  37336. indices.push(2);
  37337. indices.push(3);
  37338. // Sides
  37339. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37340. // Result
  37341. var vertexData = new VertexData();
  37342. vertexData.indices = indices;
  37343. vertexData.positions = positions;
  37344. vertexData.normals = normals;
  37345. vertexData.uvs = uvs;
  37346. return vertexData;
  37347. };
  37348. /**
  37349. * Creates the VertexData of the Disc or regular Polygon
  37350. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37351. * * radius the radius of the disc, optional default 0.5
  37352. * * tessellation the number of polygon sides, optional, default 64
  37353. * * 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
  37354. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37355. * * 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)
  37356. * * 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)
  37357. * @returns the VertexData of the box
  37358. */
  37359. VertexData.CreateDisc = function (options) {
  37360. var positions = new Array();
  37361. var indices = new Array();
  37362. var normals = new Array();
  37363. var uvs = new Array();
  37364. var radius = options.radius || 0.5;
  37365. var tessellation = options.tessellation || 64;
  37366. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37367. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37368. // positions and uvs
  37369. positions.push(0, 0, 0); // disc center first
  37370. uvs.push(0.5, 0.5);
  37371. var theta = Math.PI * 2 * arc;
  37372. var step = theta / tessellation;
  37373. for (var a = 0; a < theta; a += step) {
  37374. var x = Math.cos(a);
  37375. var y = Math.sin(a);
  37376. var u = (x + 1) / 2;
  37377. var v = (1 - y) / 2;
  37378. positions.push(radius * x, radius * y, 0);
  37379. uvs.push(u, v);
  37380. }
  37381. if (arc === 1) {
  37382. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37383. uvs.push(uvs[2], uvs[3]);
  37384. }
  37385. //indices
  37386. var vertexNb = positions.length / 3;
  37387. for (var i = 1; i < vertexNb - 1; i++) {
  37388. indices.push(i + 1, 0, i);
  37389. }
  37390. // result
  37391. VertexData.ComputeNormals(positions, indices, normals);
  37392. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37393. var vertexData = new VertexData();
  37394. vertexData.indices = indices;
  37395. vertexData.positions = positions;
  37396. vertexData.normals = normals;
  37397. vertexData.uvs = uvs;
  37398. return vertexData;
  37399. };
  37400. /**
  37401. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37402. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37403. * @param polygon a mesh built from polygonTriangulation.build()
  37404. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37405. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37406. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37407. * @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)
  37408. * @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)
  37409. * @returns the VertexData of the Polygon
  37410. */
  37411. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37412. var faceUV = fUV || new Array(3);
  37413. var faceColors = fColors;
  37414. var colors = [];
  37415. // default face colors and UV if undefined
  37416. for (var f = 0; f < 3; f++) {
  37417. if (faceUV[f] === undefined) {
  37418. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37419. }
  37420. if (faceColors && faceColors[f] === undefined) {
  37421. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37422. }
  37423. }
  37424. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37425. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37426. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37427. var indices = polygon.getIndices();
  37428. // set face colours and textures
  37429. var idx = 0;
  37430. var face = 0;
  37431. for (var index = 0; index < normals.length; index += 3) {
  37432. //Edge Face no. 1
  37433. if (Math.abs(normals[index + 1]) < 0.001) {
  37434. face = 1;
  37435. }
  37436. //Top Face no. 0
  37437. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37438. face = 0;
  37439. }
  37440. //Bottom Face no. 2
  37441. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37442. face = 2;
  37443. }
  37444. idx = index / 3;
  37445. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37446. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37447. if (faceColors) {
  37448. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37449. }
  37450. }
  37451. // sides
  37452. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37453. // Result
  37454. var vertexData = new VertexData();
  37455. vertexData.indices = indices;
  37456. vertexData.positions = positions;
  37457. vertexData.normals = normals;
  37458. vertexData.uvs = uvs;
  37459. if (faceColors) {
  37460. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37461. vertexData.colors = totalColors;
  37462. }
  37463. return vertexData;
  37464. };
  37465. /**
  37466. * Creates the VertexData of the IcoSphere
  37467. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37468. * * radius the radius of the IcoSphere, optional default 1
  37469. * * radiusX allows stretching in the x direction, optional, default radius
  37470. * * radiusY allows stretching in the y direction, optional, default radius
  37471. * * radiusZ allows stretching in the z direction, optional, default radius
  37472. * * flat when true creates a flat shaded mesh, optional, default true
  37473. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37474. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37475. * * 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)
  37476. * * 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)
  37477. * @returns the VertexData of the IcoSphere
  37478. */
  37479. VertexData.CreateIcoSphere = function (options) {
  37480. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37481. var radius = options.radius || 1;
  37482. var flat = (options.flat === undefined) ? true : options.flat;
  37483. var subdivisions = options.subdivisions || 4;
  37484. var radiusX = options.radiusX || radius;
  37485. var radiusY = options.radiusY || radius;
  37486. var radiusZ = options.radiusZ || radius;
  37487. var t = (1 + Math.sqrt(5)) / 2;
  37488. // 12 vertex x,y,z
  37489. var ico_vertices = [
  37490. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37491. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37492. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37493. ];
  37494. // index of 3 vertex makes a face of icopshere
  37495. var ico_indices = [
  37496. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37497. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37498. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37499. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37500. ];
  37501. // vertex for uv have aliased position, not for UV
  37502. var vertices_unalias_id = [
  37503. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37504. // vertex alias
  37505. 0,
  37506. 2,
  37507. 3,
  37508. 3,
  37509. 3,
  37510. 4,
  37511. 7,
  37512. 8,
  37513. 9,
  37514. 9,
  37515. 10,
  37516. 11 // 23: B + 12
  37517. ];
  37518. // uv as integer step (not pixels !)
  37519. var ico_vertexuv = [
  37520. 5, 1, 3, 1, 6, 4, 0, 0,
  37521. 5, 3, 4, 2, 2, 2, 4, 0,
  37522. 2, 0, 1, 1, 6, 0, 6, 2,
  37523. // vertex alias (for same vertex on different faces)
  37524. 0, 4,
  37525. 3, 3,
  37526. 4, 4,
  37527. 3, 1,
  37528. 4, 2,
  37529. 4, 4,
  37530. 0, 2,
  37531. 1, 1,
  37532. 2, 2,
  37533. 3, 3,
  37534. 1, 3,
  37535. 2, 4 // 23: B + 12
  37536. ];
  37537. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37538. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37539. // First island of uv mapping
  37540. // v = 4h 3+ 2
  37541. // v = 3h 9+ 4
  37542. // v = 2h 9+ 5 B
  37543. // v = 1h 9 1 0
  37544. // v = 0h 3 8 7 A
  37545. // u = 0 1 2 3 4 5 6 *a
  37546. // Second island of uv mapping
  37547. // v = 4h 0+ B+ 4+
  37548. // v = 3h A+ 2+
  37549. // v = 2h 7+ 6 3+
  37550. // v = 1h 8+ 3+
  37551. // v = 0h
  37552. // u = 0 1 2 3 4 5 6 *a
  37553. // Face layout on texture UV mapping
  37554. // ============
  37555. // \ 4 /\ 16 / ======
  37556. // \ / \ / /\ 11 /
  37557. // \/ 7 \/ / \ /
  37558. // ======= / 10 \/
  37559. // /\ 17 /\ =======
  37560. // / \ / \ \ 15 /\
  37561. // / 8 \/ 12 \ \ / \
  37562. // ============ \/ 6 \
  37563. // \ 18 /\ ============
  37564. // \ / \ \ 5 /\ 0 /
  37565. // \/ 13 \ \ / \ /
  37566. // ======= \/ 1 \/
  37567. // =============
  37568. // /\ 19 /\ 2 /\
  37569. // / \ / \ / \
  37570. // / 14 \/ 9 \/ 3 \
  37571. // ===================
  37572. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37573. var ustep = 138 / 1024;
  37574. var vstep = 239 / 1024;
  37575. var uoffset = 60 / 1024;
  37576. var voffset = 26 / 1024;
  37577. // Second island should have margin, not to touch the first island
  37578. // avoid any borderline artefact in pixel rounding
  37579. var island_u_offset = -40 / 1024;
  37580. var island_v_offset = +20 / 1024;
  37581. // face is either island 0 or 1 :
  37582. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37583. var island = [
  37584. 0, 0, 0, 0, 1,
  37585. 0, 0, 1, 1, 0,
  37586. 0, 0, 1, 1, 0,
  37587. 0, 1, 1, 1, 0 // 15 - 19
  37588. ];
  37589. var indices = new Array();
  37590. var positions = new Array();
  37591. var normals = new Array();
  37592. var uvs = new Array();
  37593. var current_indice = 0;
  37594. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37595. var face_vertex_pos = new Array(3);
  37596. var face_vertex_uv = new Array(3);
  37597. var v012;
  37598. for (v012 = 0; v012 < 3; v012++) {
  37599. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37600. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37601. }
  37602. // create all with normals
  37603. for (var face = 0; face < 20; face++) {
  37604. // 3 vertex per face
  37605. for (v012 = 0; v012 < 3; v012++) {
  37606. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37607. var v_id = ico_indices[3 * face + v012];
  37608. // vertex have 3D position (x,y,z)
  37609. 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]);
  37610. // Normalize to get normal, then scale to radius
  37611. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37612. // uv Coordinates from vertex ID
  37613. 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);
  37614. }
  37615. // Subdivide the face (interpolate pos, norm, uv)
  37616. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37617. // - norm is linear interpolation of vertex corner normal
  37618. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37619. // - uv is linear interpolation
  37620. //
  37621. // Topology is as below for sub-divide by 2
  37622. // vertex shown as v0,v1,v2
  37623. // interp index is i1 to progress in range [v0,v1[
  37624. // interp index is i2 to progress in range [v0,v2[
  37625. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37626. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37627. //
  37628. //
  37629. // i2 v2
  37630. // ^ ^
  37631. // / / \
  37632. // / / \
  37633. // / / \
  37634. // / / (0,1) \
  37635. // / #---------\
  37636. // / / \ (0,0)'/ \
  37637. // / / \ / \
  37638. // / / \ / \
  37639. // / / (0,0) \ / (1,0) \
  37640. // / #---------#---------\
  37641. // v0 v1
  37642. //
  37643. // --------------------> i1
  37644. //
  37645. // interp of (i1,i2):
  37646. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37647. // along i1 : lerp(x0,x1, i1/(S-i2))
  37648. //
  37649. // centroid of triangle is needed to get help normal computation
  37650. // (c1,c2) are used for centroid location
  37651. var interp_vertex = function (i1, i2, c1, c2) {
  37652. // vertex is interpolated from
  37653. // - face_vertex_pos[0..2]
  37654. // - face_vertex_uv[0..2]
  37655. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37656. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37657. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37658. pos_interp.normalize();
  37659. var vertex_normal;
  37660. if (flat) {
  37661. // in flat mode, recalculate normal as face centroid normal
  37662. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37663. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37664. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37665. }
  37666. else {
  37667. // in smooth mode, recalculate normal from each single vertex position
  37668. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37669. }
  37670. // Vertex normal need correction due to X,Y,Z radius scaling
  37671. vertex_normal.x /= radiusX;
  37672. vertex_normal.y /= radiusY;
  37673. vertex_normal.z /= radiusZ;
  37674. vertex_normal.normalize();
  37675. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37676. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37677. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37678. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37679. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37680. uvs.push(uv_interp.x, uv_interp.y);
  37681. // push each vertex has member of a face
  37682. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37683. indices.push(current_indice);
  37684. current_indice++;
  37685. };
  37686. for (var i2 = 0; i2 < subdivisions; i2++) {
  37687. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37688. // face : (i1,i2) for /\ :
  37689. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37690. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37691. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37692. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37693. if (i1 + i2 + 1 < subdivisions) {
  37694. // face : (i1,i2)' for \/ :
  37695. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37696. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37697. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37698. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37699. }
  37700. }
  37701. }
  37702. }
  37703. // Sides
  37704. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37705. // Result
  37706. var vertexData = new VertexData();
  37707. vertexData.indices = indices;
  37708. vertexData.positions = positions;
  37709. vertexData.normals = normals;
  37710. vertexData.uvs = uvs;
  37711. return vertexData;
  37712. };
  37713. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37714. /**
  37715. * Creates the VertexData for a Polyhedron
  37716. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37717. * * type provided types are:
  37718. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37719. * * 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)
  37720. * * size the size of the IcoSphere, optional default 1
  37721. * * sizeX allows stretching in the x direction, optional, default size
  37722. * * sizeY allows stretching in the y direction, optional, default size
  37723. * * sizeZ allows stretching in the z direction, optional, default size
  37724. * * 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
  37725. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37726. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37727. * * flat when true creates a flat shaded mesh, optional, default true
  37728. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37729. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37730. * * 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)
  37731. * * 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)
  37732. * @returns the VertexData of the Polyhedron
  37733. */
  37734. VertexData.CreatePolyhedron = function (options) {
  37735. // provided polyhedron types :
  37736. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37737. // 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)
  37738. var polyhedra = [];
  37739. 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]] };
  37740. 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]] };
  37741. polyhedra[2] = {
  37742. 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]],
  37743. 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]]
  37744. };
  37745. polyhedra[3] = {
  37746. 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]],
  37747. 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]]
  37748. };
  37749. polyhedra[4] = {
  37750. 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]],
  37751. 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]]
  37752. };
  37753. 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]] };
  37754. 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]] };
  37755. 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]] };
  37756. 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]] };
  37757. 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]] };
  37758. 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]] };
  37759. 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]] };
  37760. 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]] };
  37761. 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]] };
  37762. polyhedra[14] = {
  37763. 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]],
  37764. 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]]
  37765. };
  37766. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37767. var size = options.size;
  37768. var sizeX = options.sizeX || size || 1;
  37769. var sizeY = options.sizeY || size || 1;
  37770. var sizeZ = options.sizeZ || size || 1;
  37771. var data = options.custom || polyhedra[type];
  37772. var nbfaces = data.face.length;
  37773. var faceUV = options.faceUV || new Array(nbfaces);
  37774. var faceColors = options.faceColors;
  37775. var flat = (options.flat === undefined) ? true : options.flat;
  37776. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37777. var positions = new Array();
  37778. var indices = new Array();
  37779. var normals = new Array();
  37780. var uvs = new Array();
  37781. var colors = new Array();
  37782. var index = 0;
  37783. var faceIdx = 0; // face cursor in the array "indexes"
  37784. var indexes = new Array();
  37785. var i = 0;
  37786. var f = 0;
  37787. var u, v, ang, x, y, tmp;
  37788. // default face colors and UV if undefined
  37789. if (flat) {
  37790. for (f = 0; f < nbfaces; f++) {
  37791. if (faceColors && faceColors[f] === undefined) {
  37792. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37793. }
  37794. if (faceUV && faceUV[f] === undefined) {
  37795. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37796. }
  37797. }
  37798. }
  37799. if (!flat) {
  37800. for (i = 0; i < data.vertex.length; i++) {
  37801. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37802. uvs.push(0, 0);
  37803. }
  37804. for (f = 0; f < nbfaces; f++) {
  37805. for (i = 0; i < data.face[f].length - 2; i++) {
  37806. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37807. }
  37808. }
  37809. }
  37810. else {
  37811. for (f = 0; f < nbfaces; f++) {
  37812. var fl = data.face[f].length; // number of vertices of the current face
  37813. ang = 2 * Math.PI / fl;
  37814. x = 0.5 * Math.tan(ang / 2);
  37815. y = 0.5;
  37816. // positions, uvs, colors
  37817. for (i = 0; i < fl; i++) {
  37818. // positions
  37819. 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);
  37820. indexes.push(index);
  37821. index++;
  37822. // uvs
  37823. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37824. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37825. uvs.push(u, v);
  37826. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37827. y = x * Math.sin(ang) + y * Math.cos(ang);
  37828. x = tmp;
  37829. // colors
  37830. if (faceColors) {
  37831. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37832. }
  37833. }
  37834. // indices from indexes
  37835. for (i = 0; i < fl - 2; i++) {
  37836. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37837. }
  37838. faceIdx += fl;
  37839. }
  37840. }
  37841. VertexData.ComputeNormals(positions, indices, normals);
  37842. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37843. var vertexData = new VertexData();
  37844. vertexData.positions = positions;
  37845. vertexData.indices = indices;
  37846. vertexData.normals = normals;
  37847. vertexData.uvs = uvs;
  37848. if (faceColors && flat) {
  37849. vertexData.colors = colors;
  37850. }
  37851. return vertexData;
  37852. };
  37853. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37854. /**
  37855. * Creates the VertexData for a TorusKnot
  37856. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  37857. * * radius the radius of the torus knot, optional, default 2
  37858. * * tube the thickness of the tube, optional, default 0.5
  37859. * * radialSegments the number of sides on each tube segments, optional, default 32
  37860. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  37861. * * p the number of windings around the z axis, optional, default 2
  37862. * * q the number of windings around the x axis, optional, default 3
  37863. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37864. * * 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)
  37865. * * 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)
  37866. * @returns the VertexData of the Torus Knot
  37867. */
  37868. VertexData.CreateTorusKnot = function (options) {
  37869. var indices = new Array();
  37870. var positions = new Array();
  37871. var normals = new Array();
  37872. var uvs = new Array();
  37873. var radius = options.radius || 2;
  37874. var tube = options.tube || 0.5;
  37875. var radialSegments = options.radialSegments || 32;
  37876. var tubularSegments = options.tubularSegments || 32;
  37877. var p = options.p || 2;
  37878. var q = options.q || 3;
  37879. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37880. // Helper
  37881. var getPos = function (angle) {
  37882. var cu = Math.cos(angle);
  37883. var su = Math.sin(angle);
  37884. var quOverP = q / p * angle;
  37885. var cs = Math.cos(quOverP);
  37886. var tx = radius * (2 + cs) * 0.5 * cu;
  37887. var ty = radius * (2 + cs) * su * 0.5;
  37888. var tz = radius * Math.sin(quOverP) * 0.5;
  37889. return new BABYLON.Vector3(tx, ty, tz);
  37890. };
  37891. // Vertices
  37892. var i;
  37893. var j;
  37894. for (i = 0; i <= radialSegments; i++) {
  37895. var modI = i % radialSegments;
  37896. var u = modI / radialSegments * 2 * p * Math.PI;
  37897. var p1 = getPos(u);
  37898. var p2 = getPos(u + 0.01);
  37899. var tang = p2.subtract(p1);
  37900. var n = p2.add(p1);
  37901. var bitan = BABYLON.Vector3.Cross(tang, n);
  37902. n = BABYLON.Vector3.Cross(bitan, tang);
  37903. bitan.normalize();
  37904. n.normalize();
  37905. for (j = 0; j < tubularSegments; j++) {
  37906. var modJ = j % tubularSegments;
  37907. var v = modJ / tubularSegments * 2 * Math.PI;
  37908. var cx = -tube * Math.cos(v);
  37909. var cy = tube * Math.sin(v);
  37910. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37911. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37912. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37913. uvs.push(i / radialSegments);
  37914. uvs.push(j / tubularSegments);
  37915. }
  37916. }
  37917. for (i = 0; i < radialSegments; i++) {
  37918. for (j = 0; j < tubularSegments; j++) {
  37919. var jNext = (j + 1) % tubularSegments;
  37920. var a = i * tubularSegments + j;
  37921. var b = (i + 1) * tubularSegments + j;
  37922. var c = (i + 1) * tubularSegments + jNext;
  37923. var d = i * tubularSegments + jNext;
  37924. indices.push(d);
  37925. indices.push(b);
  37926. indices.push(a);
  37927. indices.push(d);
  37928. indices.push(c);
  37929. indices.push(b);
  37930. }
  37931. }
  37932. // Normals
  37933. VertexData.ComputeNormals(positions, indices, normals);
  37934. // Sides
  37935. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37936. // Result
  37937. var vertexData = new VertexData();
  37938. vertexData.indices = indices;
  37939. vertexData.positions = positions;
  37940. vertexData.normals = normals;
  37941. vertexData.uvs = uvs;
  37942. return vertexData;
  37943. };
  37944. // Tools
  37945. /**
  37946. * Compute normals for given positions and indices
  37947. * @param positions an array of vertex positions, [...., x, y, z, ......]
  37948. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  37949. * @param normals an array of vertex normals, [...., x, y, z, ......]
  37950. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  37951. * * facetNormals : optional array of facet normals (vector3)
  37952. * * facetPositions : optional array of facet positions (vector3)
  37953. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  37954. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  37955. * * bInfo : optional bounding info, required for facetPartitioning computation
  37956. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  37957. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  37958. * * useRightHandedSystem: optional boolean to for right handed system computation
  37959. * * depthSort : optional boolean to enable the facet depth sort computation
  37960. * * distanceTo : optional Vector3 to compute the facet depth from this location
  37961. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  37962. */
  37963. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  37964. // temporary scalar variables
  37965. var index = 0; // facet index
  37966. var p1p2x = 0.0; // p1p2 vector x coordinate
  37967. var p1p2y = 0.0; // p1p2 vector y coordinate
  37968. var p1p2z = 0.0; // p1p2 vector z coordinate
  37969. var p3p2x = 0.0; // p3p2 vector x coordinate
  37970. var p3p2y = 0.0; // p3p2 vector y coordinate
  37971. var p3p2z = 0.0; // p3p2 vector z coordinate
  37972. var faceNormalx = 0.0; // facet normal x coordinate
  37973. var faceNormaly = 0.0; // facet normal y coordinate
  37974. var faceNormalz = 0.0; // facet normal z coordinate
  37975. var length = 0.0; // facet normal length before normalization
  37976. var v1x = 0; // vector1 x index in the positions array
  37977. var v1y = 0; // vector1 y index in the positions array
  37978. var v1z = 0; // vector1 z index in the positions array
  37979. var v2x = 0; // vector2 x index in the positions array
  37980. var v2y = 0; // vector2 y index in the positions array
  37981. var v2z = 0; // vector2 z index in the positions array
  37982. var v3x = 0; // vector3 x index in the positions array
  37983. var v3y = 0; // vector3 y index in the positions array
  37984. var v3z = 0; // vector3 z index in the positions array
  37985. var computeFacetNormals = false;
  37986. var computeFacetPositions = false;
  37987. var computeFacetPartitioning = false;
  37988. var computeDepthSort = false;
  37989. var faceNormalSign = 1;
  37990. var ratio = 0;
  37991. var distanceTo = null;
  37992. if (options) {
  37993. computeFacetNormals = (options.facetNormals) ? true : false;
  37994. computeFacetPositions = (options.facetPositions) ? true : false;
  37995. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  37996. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  37997. ratio = options.ratio || 0;
  37998. computeDepthSort = (options.depthSort) ? true : false;
  37999. distanceTo = (options.distanceTo);
  38000. if (computeDepthSort) {
  38001. if (distanceTo === undefined) {
  38002. distanceTo = BABYLON.Vector3.Zero();
  38003. }
  38004. var depthSortedFacets = options.depthSortedFacets;
  38005. }
  38006. }
  38007. // facetPartitioning reinit if needed
  38008. var xSubRatio = 0;
  38009. var ySubRatio = 0;
  38010. var zSubRatio = 0;
  38011. var subSq = 0;
  38012. if (computeFacetPartitioning && options && options.bbSize) {
  38013. var ox = 0; // X partitioning index for facet position
  38014. var oy = 0; // Y partinioning index for facet position
  38015. var oz = 0; // Z partinioning index for facet position
  38016. var b1x = 0; // X partitioning index for facet v1 vertex
  38017. var b1y = 0; // Y partitioning index for facet v1 vertex
  38018. var b1z = 0; // z partitioning index for facet v1 vertex
  38019. var b2x = 0; // X partitioning index for facet v2 vertex
  38020. var b2y = 0; // Y partitioning index for facet v2 vertex
  38021. var b2z = 0; // Z partitioning index for facet v2 vertex
  38022. var b3x = 0; // X partitioning index for facet v3 vertex
  38023. var b3y = 0; // Y partitioning index for facet v3 vertex
  38024. var b3z = 0; // Z partitioning index for facet v3 vertex
  38025. var block_idx_o = 0; // facet barycenter block index
  38026. var block_idx_v1 = 0; // v1 vertex block index
  38027. var block_idx_v2 = 0; // v2 vertex block index
  38028. var block_idx_v3 = 0; // v3 vertex block index
  38029. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38030. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38031. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38032. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38033. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38034. subSq = options.subDiv.max * options.subDiv.max;
  38035. options.facetPartitioning.length = 0;
  38036. }
  38037. // reset the normals
  38038. for (index = 0; index < positions.length; index++) {
  38039. normals[index] = 0.0;
  38040. }
  38041. // Loop : 1 indice triplet = 1 facet
  38042. var nbFaces = (indices.length / 3) | 0;
  38043. for (index = 0; index < nbFaces; index++) {
  38044. // get the indexes of the coordinates of each vertex of the facet
  38045. v1x = indices[index * 3] * 3;
  38046. v1y = v1x + 1;
  38047. v1z = v1x + 2;
  38048. v2x = indices[index * 3 + 1] * 3;
  38049. v2y = v2x + 1;
  38050. v2z = v2x + 2;
  38051. v3x = indices[index * 3 + 2] * 3;
  38052. v3y = v3x + 1;
  38053. v3z = v3x + 2;
  38054. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38055. p1p2y = positions[v1y] - positions[v2y];
  38056. p1p2z = positions[v1z] - positions[v2z];
  38057. p3p2x = positions[v3x] - positions[v2x];
  38058. p3p2y = positions[v3y] - positions[v2y];
  38059. p3p2z = positions[v3z] - positions[v2z];
  38060. // compute the face normal with the cross product
  38061. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38062. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38063. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38064. // normalize this normal and store it in the array facetData
  38065. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38066. length = (length === 0) ? 1.0 : length;
  38067. faceNormalx /= length;
  38068. faceNormaly /= length;
  38069. faceNormalz /= length;
  38070. if (computeFacetNormals && options) {
  38071. options.facetNormals[index].x = faceNormalx;
  38072. options.facetNormals[index].y = faceNormaly;
  38073. options.facetNormals[index].z = faceNormalz;
  38074. }
  38075. if (computeFacetPositions && options) {
  38076. // compute and the facet barycenter coordinates in the array facetPositions
  38077. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38078. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38079. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38080. }
  38081. if (computeFacetPartitioning && options) {
  38082. // store the facet indexes in arrays in the main facetPartitioning array :
  38083. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38084. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38085. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38086. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38087. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38088. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38089. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38090. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38091. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38092. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38093. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38094. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38095. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38096. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38097. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38098. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38099. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38100. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38101. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38102. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38103. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38104. // push each facet index in each block containing the vertex
  38105. options.facetPartitioning[block_idx_v1].push(index);
  38106. if (block_idx_v2 != block_idx_v1) {
  38107. options.facetPartitioning[block_idx_v2].push(index);
  38108. }
  38109. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38110. options.facetPartitioning[block_idx_v3].push(index);
  38111. }
  38112. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38113. options.facetPartitioning[block_idx_o].push(index);
  38114. }
  38115. }
  38116. if (computeDepthSort && options && options.facetPositions) {
  38117. var dsf = depthSortedFacets[index];
  38118. dsf.ind = index * 3;
  38119. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38120. }
  38121. // compute the normals anyway
  38122. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38123. normals[v1y] += faceNormaly;
  38124. normals[v1z] += faceNormalz;
  38125. normals[v2x] += faceNormalx;
  38126. normals[v2y] += faceNormaly;
  38127. normals[v2z] += faceNormalz;
  38128. normals[v3x] += faceNormalx;
  38129. normals[v3y] += faceNormaly;
  38130. normals[v3z] += faceNormalz;
  38131. }
  38132. // last normalization of each normal
  38133. for (index = 0; index < normals.length / 3; index++) {
  38134. faceNormalx = normals[index * 3];
  38135. faceNormaly = normals[index * 3 + 1];
  38136. faceNormalz = normals[index * 3 + 2];
  38137. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38138. length = (length === 0) ? 1.0 : length;
  38139. faceNormalx /= length;
  38140. faceNormaly /= length;
  38141. faceNormalz /= length;
  38142. normals[index * 3] = faceNormalx;
  38143. normals[index * 3 + 1] = faceNormaly;
  38144. normals[index * 3 + 2] = faceNormalz;
  38145. }
  38146. };
  38147. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38148. var li = indices.length;
  38149. var ln = normals.length;
  38150. var i;
  38151. var n;
  38152. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38153. switch (sideOrientation) {
  38154. case BABYLON.Mesh.FRONTSIDE:
  38155. // nothing changed
  38156. break;
  38157. case BABYLON.Mesh.BACKSIDE:
  38158. var tmp;
  38159. // indices
  38160. for (i = 0; i < li; i += 3) {
  38161. tmp = indices[i];
  38162. indices[i] = indices[i + 2];
  38163. indices[i + 2] = tmp;
  38164. }
  38165. // normals
  38166. for (n = 0; n < ln; n++) {
  38167. normals[n] = -normals[n];
  38168. }
  38169. break;
  38170. case BABYLON.Mesh.DOUBLESIDE:
  38171. // positions
  38172. var lp = positions.length;
  38173. var l = lp / 3;
  38174. for (var p = 0; p < lp; p++) {
  38175. positions[lp + p] = positions[p];
  38176. }
  38177. // indices
  38178. for (i = 0; i < li; i += 3) {
  38179. indices[i + li] = indices[i + 2] + l;
  38180. indices[i + 1 + li] = indices[i + 1] + l;
  38181. indices[i + 2 + li] = indices[i] + l;
  38182. }
  38183. // normals
  38184. for (n = 0; n < ln; n++) {
  38185. normals[ln + n] = -normals[n];
  38186. }
  38187. // uvs
  38188. var lu = uvs.length;
  38189. var u = 0;
  38190. for (u = 0; u < lu; u++) {
  38191. uvs[u + lu] = uvs[u];
  38192. }
  38193. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38194. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38195. u = 0;
  38196. for (i = 0; i < lu / 2; i++) {
  38197. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38198. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38199. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38200. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38201. u += 2;
  38202. }
  38203. break;
  38204. }
  38205. };
  38206. /**
  38207. * Applies VertexData created from the imported parameters to the geometry
  38208. * @param parsedVertexData the parsed data from an imported file
  38209. * @param geometry the geometry to apply the VertexData to
  38210. */
  38211. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38212. var vertexData = new VertexData();
  38213. // positions
  38214. var positions = parsedVertexData.positions;
  38215. if (positions) {
  38216. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38217. }
  38218. // normals
  38219. var normals = parsedVertexData.normals;
  38220. if (normals) {
  38221. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38222. }
  38223. // tangents
  38224. var tangents = parsedVertexData.tangents;
  38225. if (tangents) {
  38226. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38227. }
  38228. // uvs
  38229. var uvs = parsedVertexData.uvs;
  38230. if (uvs) {
  38231. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38232. }
  38233. // uv2s
  38234. var uv2s = parsedVertexData.uv2s;
  38235. if (uv2s) {
  38236. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38237. }
  38238. // uv3s
  38239. var uv3s = parsedVertexData.uv3s;
  38240. if (uv3s) {
  38241. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38242. }
  38243. // uv4s
  38244. var uv4s = parsedVertexData.uv4s;
  38245. if (uv4s) {
  38246. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38247. }
  38248. // uv5s
  38249. var uv5s = parsedVertexData.uv5s;
  38250. if (uv5s) {
  38251. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38252. }
  38253. // uv6s
  38254. var uv6s = parsedVertexData.uv6s;
  38255. if (uv6s) {
  38256. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38257. }
  38258. // colors
  38259. var colors = parsedVertexData.colors;
  38260. if (colors) {
  38261. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38262. }
  38263. // matricesIndices
  38264. var matricesIndices = parsedVertexData.matricesIndices;
  38265. if (matricesIndices) {
  38266. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38267. }
  38268. // matricesWeights
  38269. var matricesWeights = parsedVertexData.matricesWeights;
  38270. if (matricesWeights) {
  38271. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38272. }
  38273. // indices
  38274. var indices = parsedVertexData.indices;
  38275. if (indices) {
  38276. vertexData.indices = indices;
  38277. }
  38278. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38279. };
  38280. return VertexData;
  38281. }());
  38282. BABYLON.VertexData = VertexData;
  38283. })(BABYLON || (BABYLON = {}));
  38284. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38285. var BABYLON;
  38286. (function (BABYLON) {
  38287. /**
  38288. * Class used to store geometry data (vertex buffers + index buffer)
  38289. */
  38290. var Geometry = /** @class */ (function () {
  38291. /**
  38292. * Creates a new geometry
  38293. * @param id defines the unique ID
  38294. * @param scene defines the hosting scene
  38295. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38296. * @param updatable defines if geometry must be updatable (false by default)
  38297. * @param mesh defines the mesh that will be associated with the geometry
  38298. */
  38299. function Geometry(id, scene, vertexData, updatable, mesh) {
  38300. if (updatable === void 0) { updatable = false; }
  38301. if (mesh === void 0) { mesh = null; }
  38302. /**
  38303. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38304. */
  38305. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38306. this._totalVertices = 0;
  38307. this._isDisposed = false;
  38308. this._indexBufferIsUpdatable = false;
  38309. this.id = id;
  38310. this._engine = scene.getEngine();
  38311. this._meshes = [];
  38312. this._scene = scene;
  38313. //Init vertex buffer cache
  38314. this._vertexBuffers = {};
  38315. this._indices = [];
  38316. this._updatable = updatable;
  38317. // vertexData
  38318. if (vertexData) {
  38319. this.setAllVerticesData(vertexData, updatable);
  38320. }
  38321. else {
  38322. this._totalVertices = 0;
  38323. this._indices = [];
  38324. }
  38325. if (this._engine.getCaps().vertexArrayObject) {
  38326. this._vertexArrayObjects = {};
  38327. }
  38328. // applyToMesh
  38329. if (mesh) {
  38330. if (mesh.getClassName() === "LinesMesh") {
  38331. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38332. this._updateExtend();
  38333. }
  38334. this.applyToMesh(mesh);
  38335. mesh.computeWorldMatrix(true);
  38336. }
  38337. }
  38338. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38339. /**
  38340. * 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
  38341. */
  38342. get: function () {
  38343. return this._boundingBias;
  38344. },
  38345. /**
  38346. * 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
  38347. */
  38348. set: function (value) {
  38349. if (this._boundingBias && this._boundingBias.equals(value)) {
  38350. return;
  38351. }
  38352. this._boundingBias = value.clone();
  38353. this._updateBoundingInfo(true, null);
  38354. },
  38355. enumerable: true,
  38356. configurable: true
  38357. });
  38358. /**
  38359. * Static function used to attach a new empty geometry to a mesh
  38360. * @param mesh defines the mesh to attach the geometry to
  38361. * @returns the new {BABYLON.Geometry}
  38362. */
  38363. Geometry.CreateGeometryForMesh = function (mesh) {
  38364. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38365. geometry.applyToMesh(mesh);
  38366. return geometry;
  38367. };
  38368. Object.defineProperty(Geometry.prototype, "extend", {
  38369. /**
  38370. * Gets the current extend of the geometry
  38371. */
  38372. get: function () {
  38373. return this._extend;
  38374. },
  38375. enumerable: true,
  38376. configurable: true
  38377. });
  38378. /**
  38379. * Gets the hosting scene
  38380. * @returns the hosting {BABYLON.Scene}
  38381. */
  38382. Geometry.prototype.getScene = function () {
  38383. return this._scene;
  38384. };
  38385. /**
  38386. * Gets the hosting engine
  38387. * @returns the hosting {BABYLON.Engine}
  38388. */
  38389. Geometry.prototype.getEngine = function () {
  38390. return this._engine;
  38391. };
  38392. /**
  38393. * Defines if the geometry is ready to use
  38394. * @returns true if the geometry is ready to be used
  38395. */
  38396. Geometry.prototype.isReady = function () {
  38397. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38398. };
  38399. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38400. /**
  38401. * Gets a value indicating that the geometry should not be serialized
  38402. */
  38403. get: function () {
  38404. for (var index = 0; index < this._meshes.length; index++) {
  38405. if (!this._meshes[index].doNotSerialize) {
  38406. return false;
  38407. }
  38408. }
  38409. return true;
  38410. },
  38411. enumerable: true,
  38412. configurable: true
  38413. });
  38414. /** @hidden */
  38415. Geometry.prototype._rebuild = function () {
  38416. if (this._vertexArrayObjects) {
  38417. this._vertexArrayObjects = {};
  38418. }
  38419. // Index buffer
  38420. if (this._meshes.length !== 0 && this._indices) {
  38421. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38422. }
  38423. // Vertex buffers
  38424. for (var key in this._vertexBuffers) {
  38425. var vertexBuffer = this._vertexBuffers[key];
  38426. vertexBuffer._rebuild();
  38427. }
  38428. };
  38429. /**
  38430. * Affects all geometry data in one call
  38431. * @param vertexData defines the geometry data
  38432. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38433. */
  38434. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38435. vertexData.applyToGeometry(this, updatable);
  38436. this.notifyUpdate();
  38437. };
  38438. /**
  38439. * Set specific vertex data
  38440. * @param kind defines the data kind (Position, normal, etc...)
  38441. * @param data defines the vertex data to use
  38442. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38443. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38444. */
  38445. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38446. if (updatable === void 0) { updatable = false; }
  38447. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38448. this.setVerticesBuffer(buffer);
  38449. };
  38450. /**
  38451. * Removes a specific vertex data
  38452. * @param kind defines the data kind (Position, normal, etc...)
  38453. */
  38454. Geometry.prototype.removeVerticesData = function (kind) {
  38455. if (this._vertexBuffers[kind]) {
  38456. this._vertexBuffers[kind].dispose();
  38457. delete this._vertexBuffers[kind];
  38458. }
  38459. };
  38460. /**
  38461. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38462. * @param buffer defines the vertex buffer to use
  38463. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38464. */
  38465. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38466. if (totalVertices === void 0) { totalVertices = null; }
  38467. var kind = buffer.getKind();
  38468. if (this._vertexBuffers[kind]) {
  38469. this._vertexBuffers[kind].dispose();
  38470. }
  38471. this._vertexBuffers[kind] = buffer;
  38472. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38473. var data = buffer.getData();
  38474. if (totalVertices != null) {
  38475. this._totalVertices = totalVertices;
  38476. }
  38477. else {
  38478. if (data != null) {
  38479. this._totalVertices = data.length / (buffer.byteStride / 4);
  38480. }
  38481. }
  38482. this._updateExtend(data);
  38483. this._resetPointsArrayCache();
  38484. var meshes = this._meshes;
  38485. var numOfMeshes = meshes.length;
  38486. for (var index = 0; index < numOfMeshes; index++) {
  38487. var mesh = meshes[index];
  38488. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38489. mesh._createGlobalSubMesh(false);
  38490. mesh.computeWorldMatrix(true);
  38491. }
  38492. }
  38493. this.notifyUpdate(kind);
  38494. if (this._vertexArrayObjects) {
  38495. this._disposeVertexArrayObjects();
  38496. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38497. }
  38498. };
  38499. /**
  38500. * Update a specific vertex buffer
  38501. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38502. * It will do nothing if the buffer is not updatable
  38503. * @param kind defines the data kind (Position, normal, etc...)
  38504. * @param data defines the data to use
  38505. * @param offset defines the offset in the target buffer where to store the data
  38506. * @param useBytes set to true if the offset is in bytes
  38507. */
  38508. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38509. if (useBytes === void 0) { useBytes = false; }
  38510. var vertexBuffer = this.getVertexBuffer(kind);
  38511. if (!vertexBuffer) {
  38512. return;
  38513. }
  38514. vertexBuffer.updateDirectly(data, offset, useBytes);
  38515. this.notifyUpdate(kind);
  38516. };
  38517. /**
  38518. * Update a specific vertex buffer
  38519. * This function will create a new buffer if the current one is not updatable
  38520. * @param kind defines the data kind (Position, normal, etc...)
  38521. * @param data defines the data to use
  38522. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38523. */
  38524. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38525. if (updateExtends === void 0) { updateExtends = false; }
  38526. var vertexBuffer = this.getVertexBuffer(kind);
  38527. if (!vertexBuffer) {
  38528. return;
  38529. }
  38530. vertexBuffer.update(data);
  38531. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38532. this._updateBoundingInfo(updateExtends, data);
  38533. }
  38534. this.notifyUpdate(kind);
  38535. };
  38536. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38537. if (updateExtends) {
  38538. this._updateExtend(data);
  38539. }
  38540. var meshes = this._meshes;
  38541. var numOfMeshes = meshes.length;
  38542. this._resetPointsArrayCache();
  38543. for (var index = 0; index < numOfMeshes; index++) {
  38544. var mesh = meshes[index];
  38545. if (updateExtends) {
  38546. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38547. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38548. var subMesh = mesh.subMeshes[subIndex];
  38549. subMesh.refreshBoundingInfo();
  38550. }
  38551. }
  38552. }
  38553. };
  38554. /** @hidden */
  38555. Geometry.prototype._bind = function (effect, indexToBind) {
  38556. if (!effect) {
  38557. return;
  38558. }
  38559. if (indexToBind === undefined) {
  38560. indexToBind = this._indexBuffer;
  38561. }
  38562. var vbs = this.getVertexBuffers();
  38563. if (!vbs) {
  38564. return;
  38565. }
  38566. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38567. this._engine.bindBuffers(vbs, indexToBind, effect);
  38568. return;
  38569. }
  38570. // Using VAO
  38571. if (!this._vertexArrayObjects[effect.key]) {
  38572. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38573. }
  38574. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38575. };
  38576. /**
  38577. * Gets total number of vertices
  38578. * @returns the total number of vertices
  38579. */
  38580. Geometry.prototype.getTotalVertices = function () {
  38581. if (!this.isReady()) {
  38582. return 0;
  38583. }
  38584. return this._totalVertices;
  38585. };
  38586. /**
  38587. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38588. * @param kind defines the data kind (Position, normal, etc...)
  38589. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38590. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38591. * @returns a float array containing vertex data
  38592. */
  38593. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38594. var vertexBuffer = this.getVertexBuffer(kind);
  38595. if (!vertexBuffer) {
  38596. return null;
  38597. }
  38598. var data = vertexBuffer.getData();
  38599. if (!data) {
  38600. return null;
  38601. }
  38602. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38603. var count = this._totalVertices * vertexBuffer.getSize();
  38604. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38605. var copy_1 = new Array(count);
  38606. vertexBuffer.forEach(count, function (value, index) {
  38607. copy_1[index] = value;
  38608. });
  38609. return copy_1;
  38610. }
  38611. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38612. if (data instanceof Array) {
  38613. var offset = vertexBuffer.byteOffset / 4;
  38614. return BABYLON.Tools.Slice(data, offset, offset + count);
  38615. }
  38616. else if (data instanceof ArrayBuffer) {
  38617. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38618. }
  38619. else {
  38620. var offset = data.byteOffset + vertexBuffer.byteOffset;
  38621. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38622. var result = new Float32Array(count);
  38623. var source = new Float32Array(data.buffer, offset, count);
  38624. result.set(source);
  38625. return result;
  38626. }
  38627. return new Float32Array(data.buffer, offset, count);
  38628. }
  38629. }
  38630. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38631. return BABYLON.Tools.Slice(data);
  38632. }
  38633. return data;
  38634. };
  38635. /**
  38636. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38637. * @param kind defines the data kind (Position, normal, etc...)
  38638. * @returns true if the vertex buffer with the specified kind is updatable
  38639. */
  38640. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38641. var vb = this._vertexBuffers[kind];
  38642. if (!vb) {
  38643. return false;
  38644. }
  38645. return vb.isUpdatable();
  38646. };
  38647. /**
  38648. * Gets a specific vertex buffer
  38649. * @param kind defines the data kind (Position, normal, etc...)
  38650. * @returns a {BABYLON.VertexBuffer}
  38651. */
  38652. Geometry.prototype.getVertexBuffer = function (kind) {
  38653. if (!this.isReady()) {
  38654. return null;
  38655. }
  38656. return this._vertexBuffers[kind];
  38657. };
  38658. /**
  38659. * Returns all vertex buffers
  38660. * @return an object holding all vertex buffers indexed by kind
  38661. */
  38662. Geometry.prototype.getVertexBuffers = function () {
  38663. if (!this.isReady()) {
  38664. return null;
  38665. }
  38666. return this._vertexBuffers;
  38667. };
  38668. /**
  38669. * Gets a boolean indicating if specific vertex buffer is present
  38670. * @param kind defines the data kind (Position, normal, etc...)
  38671. * @returns true if data is present
  38672. */
  38673. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38674. if (!this._vertexBuffers) {
  38675. if (this._delayInfo) {
  38676. return this._delayInfo.indexOf(kind) !== -1;
  38677. }
  38678. return false;
  38679. }
  38680. return this._vertexBuffers[kind] !== undefined;
  38681. };
  38682. /**
  38683. * Gets a list of all attached data kinds (Position, normal, etc...)
  38684. * @returns a list of string containing all kinds
  38685. */
  38686. Geometry.prototype.getVerticesDataKinds = function () {
  38687. var result = [];
  38688. var kind;
  38689. if (!this._vertexBuffers && this._delayInfo) {
  38690. for (kind in this._delayInfo) {
  38691. result.push(kind);
  38692. }
  38693. }
  38694. else {
  38695. for (kind in this._vertexBuffers) {
  38696. result.push(kind);
  38697. }
  38698. }
  38699. return result;
  38700. };
  38701. /**
  38702. * Update index buffer
  38703. * @param indices defines the indices to store in the index buffer
  38704. * @param offset defines the offset in the target buffer where to store the data
  38705. */
  38706. Geometry.prototype.updateIndices = function (indices, offset) {
  38707. if (!this._indexBuffer) {
  38708. return;
  38709. }
  38710. if (!this._indexBufferIsUpdatable) {
  38711. this.setIndices(indices, null, true);
  38712. }
  38713. else {
  38714. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38715. }
  38716. };
  38717. /**
  38718. * Creates a new index buffer
  38719. * @param indices defines the indices to store in the index buffer
  38720. * @param totalVertices defines the total number of vertices (could be null)
  38721. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38722. */
  38723. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38724. if (totalVertices === void 0) { totalVertices = null; }
  38725. if (updatable === void 0) { updatable = false; }
  38726. if (this._indexBuffer) {
  38727. this._engine._releaseBuffer(this._indexBuffer);
  38728. }
  38729. this._disposeVertexArrayObjects();
  38730. this._indices = indices;
  38731. this._indexBufferIsUpdatable = updatable;
  38732. if (this._meshes.length !== 0 && this._indices) {
  38733. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38734. }
  38735. if (totalVertices != undefined) { // including null and undefined
  38736. this._totalVertices = totalVertices;
  38737. }
  38738. var meshes = this._meshes;
  38739. var numOfMeshes = meshes.length;
  38740. for (var index = 0; index < numOfMeshes; index++) {
  38741. meshes[index]._createGlobalSubMesh(true);
  38742. }
  38743. this.notifyUpdate();
  38744. };
  38745. /**
  38746. * Return the total number of indices
  38747. * @returns the total number of indices
  38748. */
  38749. Geometry.prototype.getTotalIndices = function () {
  38750. if (!this.isReady()) {
  38751. return 0;
  38752. }
  38753. return this._indices.length;
  38754. };
  38755. /**
  38756. * Gets the index buffer array
  38757. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38758. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38759. * @returns the index buffer array
  38760. */
  38761. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  38762. if (!this.isReady()) {
  38763. return null;
  38764. }
  38765. var orig = this._indices;
  38766. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  38767. return orig;
  38768. }
  38769. else {
  38770. var len = orig.length;
  38771. var copy = [];
  38772. for (var i = 0; i < len; i++) {
  38773. copy.push(orig[i]);
  38774. }
  38775. return copy;
  38776. }
  38777. };
  38778. /**
  38779. * Gets the index buffer
  38780. * @return the index buffer
  38781. */
  38782. Geometry.prototype.getIndexBuffer = function () {
  38783. if (!this.isReady()) {
  38784. return null;
  38785. }
  38786. return this._indexBuffer;
  38787. };
  38788. /** @hidden */
  38789. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38790. if (effect === void 0) { effect = null; }
  38791. if (!effect || !this._vertexArrayObjects) {
  38792. return;
  38793. }
  38794. if (this._vertexArrayObjects[effect.key]) {
  38795. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38796. delete this._vertexArrayObjects[effect.key];
  38797. }
  38798. };
  38799. /**
  38800. * Release the associated resources for a specific mesh
  38801. * @param mesh defines the source mesh
  38802. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38803. */
  38804. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38805. var meshes = this._meshes;
  38806. var index = meshes.indexOf(mesh);
  38807. if (index === -1) {
  38808. return;
  38809. }
  38810. meshes.splice(index, 1);
  38811. mesh._geometry = null;
  38812. if (meshes.length === 0 && shouldDispose) {
  38813. this.dispose();
  38814. }
  38815. };
  38816. /**
  38817. * Apply current geometry to a given mesh
  38818. * @param mesh defines the mesh to apply geometry to
  38819. */
  38820. Geometry.prototype.applyToMesh = function (mesh) {
  38821. if (mesh._geometry === this) {
  38822. return;
  38823. }
  38824. var previousGeometry = mesh._geometry;
  38825. if (previousGeometry) {
  38826. previousGeometry.releaseForMesh(mesh);
  38827. }
  38828. var meshes = this._meshes;
  38829. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38830. mesh._geometry = this;
  38831. this._scene.pushGeometry(this);
  38832. meshes.push(mesh);
  38833. if (this.isReady()) {
  38834. this._applyToMesh(mesh);
  38835. }
  38836. else {
  38837. mesh._boundingInfo = this._boundingInfo;
  38838. }
  38839. };
  38840. Geometry.prototype._updateExtend = function (data) {
  38841. if (data === void 0) { data = null; }
  38842. if (!data) {
  38843. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38844. }
  38845. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38846. };
  38847. Geometry.prototype._applyToMesh = function (mesh) {
  38848. var numOfMeshes = this._meshes.length;
  38849. // vertexBuffers
  38850. for (var kind in this._vertexBuffers) {
  38851. if (numOfMeshes === 1) {
  38852. this._vertexBuffers[kind].create();
  38853. }
  38854. var buffer = this._vertexBuffers[kind].getBuffer();
  38855. if (buffer)
  38856. buffer.references = numOfMeshes;
  38857. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38858. if (!this._extend) {
  38859. this._updateExtend();
  38860. }
  38861. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38862. mesh._createGlobalSubMesh(false);
  38863. //bounding info was just created again, world matrix should be applied again.
  38864. mesh._updateBoundingInfo();
  38865. }
  38866. }
  38867. // indexBuffer
  38868. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38869. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38870. }
  38871. if (this._indexBuffer) {
  38872. this._indexBuffer.references = numOfMeshes;
  38873. }
  38874. };
  38875. Geometry.prototype.notifyUpdate = function (kind) {
  38876. if (this.onGeometryUpdated) {
  38877. this.onGeometryUpdated(this, kind);
  38878. }
  38879. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  38880. var mesh = _a[_i];
  38881. mesh._markSubMeshesAsAttributesDirty();
  38882. }
  38883. };
  38884. /**
  38885. * Load the geometry if it was flagged as delay loaded
  38886. * @param scene defines the hosting scene
  38887. * @param onLoaded defines a callback called when the geometry is loaded
  38888. */
  38889. Geometry.prototype.load = function (scene, onLoaded) {
  38890. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  38891. return;
  38892. }
  38893. if (this.isReady()) {
  38894. if (onLoaded) {
  38895. onLoaded();
  38896. }
  38897. return;
  38898. }
  38899. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  38900. this._queueLoad(scene, onLoaded);
  38901. };
  38902. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  38903. var _this = this;
  38904. if (!this.delayLoadingFile) {
  38905. return;
  38906. }
  38907. scene._addPendingData(this);
  38908. scene._loadFile(this.delayLoadingFile, function (data) {
  38909. if (!_this._delayLoadingFunction) {
  38910. return;
  38911. }
  38912. _this._delayLoadingFunction(JSON.parse(data), _this);
  38913. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38914. _this._delayInfo = [];
  38915. scene._removePendingData(_this);
  38916. var meshes = _this._meshes;
  38917. var numOfMeshes = meshes.length;
  38918. for (var index = 0; index < numOfMeshes; index++) {
  38919. _this._applyToMesh(meshes[index]);
  38920. }
  38921. if (onLoaded) {
  38922. onLoaded();
  38923. }
  38924. }, undefined, true);
  38925. };
  38926. /**
  38927. * Invert the geometry to move from a right handed system to a left handed one.
  38928. */
  38929. Geometry.prototype.toLeftHanded = function () {
  38930. // Flip faces
  38931. var tIndices = this.getIndices(false);
  38932. if (tIndices != null && tIndices.length > 0) {
  38933. for (var i = 0; i < tIndices.length; i += 3) {
  38934. var tTemp = tIndices[i + 0];
  38935. tIndices[i + 0] = tIndices[i + 2];
  38936. tIndices[i + 2] = tTemp;
  38937. }
  38938. this.setIndices(tIndices);
  38939. }
  38940. // Negate position.z
  38941. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  38942. if (tPositions != null && tPositions.length > 0) {
  38943. for (var i = 0; i < tPositions.length; i += 3) {
  38944. tPositions[i + 2] = -tPositions[i + 2];
  38945. }
  38946. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  38947. }
  38948. // Negate normal.z
  38949. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  38950. if (tNormals != null && tNormals.length > 0) {
  38951. for (var i = 0; i < tNormals.length; i += 3) {
  38952. tNormals[i + 2] = -tNormals[i + 2];
  38953. }
  38954. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  38955. }
  38956. };
  38957. // Cache
  38958. /** @hidden */
  38959. Geometry.prototype._resetPointsArrayCache = function () {
  38960. this._positions = null;
  38961. };
  38962. /** @hidden */
  38963. Geometry.prototype._generatePointsArray = function () {
  38964. if (this._positions)
  38965. return true;
  38966. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38967. if (!data || data.length === 0) {
  38968. return false;
  38969. }
  38970. this._positions = [];
  38971. for (var index = 0; index < data.length; index += 3) {
  38972. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  38973. }
  38974. return true;
  38975. };
  38976. /**
  38977. * Gets a value indicating if the geometry is disposed
  38978. * @returns true if the geometry was disposed
  38979. */
  38980. Geometry.prototype.isDisposed = function () {
  38981. return this._isDisposed;
  38982. };
  38983. Geometry.prototype._disposeVertexArrayObjects = function () {
  38984. if (this._vertexArrayObjects) {
  38985. for (var kind in this._vertexArrayObjects) {
  38986. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  38987. }
  38988. this._vertexArrayObjects = {};
  38989. }
  38990. };
  38991. /**
  38992. * Free all associated resources
  38993. */
  38994. Geometry.prototype.dispose = function () {
  38995. var meshes = this._meshes;
  38996. var numOfMeshes = meshes.length;
  38997. var index;
  38998. for (index = 0; index < numOfMeshes; index++) {
  38999. this.releaseForMesh(meshes[index]);
  39000. }
  39001. this._meshes = [];
  39002. this._disposeVertexArrayObjects();
  39003. for (var kind in this._vertexBuffers) {
  39004. this._vertexBuffers[kind].dispose();
  39005. }
  39006. this._vertexBuffers = {};
  39007. this._totalVertices = 0;
  39008. if (this._indexBuffer) {
  39009. this._engine._releaseBuffer(this._indexBuffer);
  39010. }
  39011. this._indexBuffer = null;
  39012. this._indices = [];
  39013. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39014. this.delayLoadingFile = null;
  39015. this._delayLoadingFunction = null;
  39016. this._delayInfo = [];
  39017. this._boundingInfo = null;
  39018. this._scene.removeGeometry(this);
  39019. this._isDisposed = true;
  39020. };
  39021. /**
  39022. * Clone the current geometry into a new geometry
  39023. * @param id defines the unique ID of the new geometry
  39024. * @returns a new geometry object
  39025. */
  39026. Geometry.prototype.copy = function (id) {
  39027. var vertexData = new BABYLON.VertexData();
  39028. vertexData.indices = [];
  39029. var indices = this.getIndices();
  39030. if (indices) {
  39031. for (var index = 0; index < indices.length; index++) {
  39032. vertexData.indices.push(indices[index]);
  39033. }
  39034. }
  39035. var updatable = false;
  39036. var stopChecking = false;
  39037. var kind;
  39038. for (kind in this._vertexBuffers) {
  39039. // using slice() to make a copy of the array and not just reference it
  39040. var data = this.getVerticesData(kind);
  39041. if (data instanceof Float32Array) {
  39042. vertexData.set(new Float32Array(data), kind);
  39043. }
  39044. else {
  39045. vertexData.set(data.slice(0), kind);
  39046. }
  39047. if (!stopChecking) {
  39048. var vb = this.getVertexBuffer(kind);
  39049. if (vb) {
  39050. updatable = vb.isUpdatable();
  39051. stopChecking = !updatable;
  39052. }
  39053. }
  39054. }
  39055. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39056. geometry.delayLoadState = this.delayLoadState;
  39057. geometry.delayLoadingFile = this.delayLoadingFile;
  39058. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39059. for (kind in this._delayInfo) {
  39060. geometry._delayInfo = geometry._delayInfo || [];
  39061. geometry._delayInfo.push(kind);
  39062. }
  39063. // Bounding info
  39064. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39065. return geometry;
  39066. };
  39067. /**
  39068. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39069. * @return a JSON representation of the current geometry data (without the vertices data)
  39070. */
  39071. Geometry.prototype.serialize = function () {
  39072. var serializationObject = {};
  39073. serializationObject.id = this.id;
  39074. serializationObject.updatable = this._updatable;
  39075. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39076. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39077. }
  39078. return serializationObject;
  39079. };
  39080. Geometry.prototype.toNumberArray = function (origin) {
  39081. if (Array.isArray(origin)) {
  39082. return origin;
  39083. }
  39084. else {
  39085. return Array.prototype.slice.call(origin);
  39086. }
  39087. };
  39088. /**
  39089. * Serialize all vertices data into a JSON oject
  39090. * @returns a JSON representation of the current geometry data
  39091. */
  39092. Geometry.prototype.serializeVerticeData = function () {
  39093. var serializationObject = this.serialize();
  39094. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39095. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39096. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39097. serializationObject.positions._updatable = true;
  39098. }
  39099. }
  39100. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39101. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39102. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39103. serializationObject.normals._updatable = true;
  39104. }
  39105. }
  39106. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39107. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39108. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39109. serializationObject.tangets._updatable = true;
  39110. }
  39111. }
  39112. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39113. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39114. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39115. serializationObject.uvs._updatable = true;
  39116. }
  39117. }
  39118. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39119. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39120. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39121. serializationObject.uv2s._updatable = true;
  39122. }
  39123. }
  39124. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39125. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39126. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39127. serializationObject.uv3s._updatable = true;
  39128. }
  39129. }
  39130. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39131. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39132. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39133. serializationObject.uv4s._updatable = true;
  39134. }
  39135. }
  39136. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39137. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39138. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39139. serializationObject.uv5s._updatable = true;
  39140. }
  39141. }
  39142. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39143. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39144. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39145. serializationObject.uv6s._updatable = true;
  39146. }
  39147. }
  39148. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39149. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39150. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39151. serializationObject.colors._updatable = true;
  39152. }
  39153. }
  39154. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39155. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39156. serializationObject.matricesIndices._isExpanded = true;
  39157. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39158. serializationObject.matricesIndices._updatable = true;
  39159. }
  39160. }
  39161. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39162. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39163. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39164. serializationObject.matricesWeights._updatable = true;
  39165. }
  39166. }
  39167. serializationObject.indices = this.toNumberArray(this.getIndices());
  39168. return serializationObject;
  39169. };
  39170. // Statics
  39171. /**
  39172. * Extracts a clone of a mesh geometry
  39173. * @param mesh defines the source mesh
  39174. * @param id defines the unique ID of the new geometry object
  39175. * @returns the new geometry object
  39176. */
  39177. Geometry.ExtractFromMesh = function (mesh, id) {
  39178. var geometry = mesh._geometry;
  39179. if (!geometry) {
  39180. return null;
  39181. }
  39182. return geometry.copy(id);
  39183. };
  39184. /**
  39185. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39186. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39187. * Be aware Math.random() could cause collisions, but:
  39188. * "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"
  39189. * @returns a string containing a new GUID
  39190. */
  39191. Geometry.RandomId = function () {
  39192. return BABYLON.Tools.RandomId();
  39193. };
  39194. /** @hidden */
  39195. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39196. var scene = mesh.getScene();
  39197. // Geometry
  39198. var geometryId = parsedGeometry.geometryId;
  39199. if (geometryId) {
  39200. var geometry = scene.getGeometryByID(geometryId);
  39201. if (geometry) {
  39202. geometry.applyToMesh(mesh);
  39203. }
  39204. }
  39205. else if (parsedGeometry instanceof ArrayBuffer) {
  39206. var binaryInfo = mesh._binaryInfo;
  39207. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39208. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39209. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39210. }
  39211. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39212. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39213. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39214. }
  39215. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39216. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39217. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39218. }
  39219. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39220. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39221. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39222. }
  39223. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39224. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39225. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39226. }
  39227. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39228. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39229. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39230. }
  39231. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39232. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39233. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39234. }
  39235. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39236. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39237. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39238. }
  39239. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39240. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39241. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39242. }
  39243. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39244. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39245. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39246. }
  39247. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39248. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39249. var floatIndices = [];
  39250. for (var i = 0; i < matricesIndicesData.length; i++) {
  39251. var index = matricesIndicesData[i];
  39252. floatIndices.push(index & 0x000000FF);
  39253. floatIndices.push((index & 0x0000FF00) >> 8);
  39254. floatIndices.push((index & 0x00FF0000) >> 16);
  39255. floatIndices.push(index >> 24);
  39256. }
  39257. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39258. }
  39259. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39260. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39261. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39262. }
  39263. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39264. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39265. mesh.setIndices(indicesData, null);
  39266. }
  39267. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39268. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39269. mesh.subMeshes = [];
  39270. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39271. var materialIndex = subMeshesData[(i * 5) + 0];
  39272. var verticesStart = subMeshesData[(i * 5) + 1];
  39273. var verticesCount = subMeshesData[(i * 5) + 2];
  39274. var indexStart = subMeshesData[(i * 5) + 3];
  39275. var indexCount = subMeshesData[(i * 5) + 4];
  39276. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39277. }
  39278. }
  39279. }
  39280. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39281. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39282. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39283. if (parsedGeometry.tangents) {
  39284. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39285. }
  39286. if (parsedGeometry.uvs) {
  39287. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39288. }
  39289. if (parsedGeometry.uvs2) {
  39290. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39291. }
  39292. if (parsedGeometry.uvs3) {
  39293. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39294. }
  39295. if (parsedGeometry.uvs4) {
  39296. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39297. }
  39298. if (parsedGeometry.uvs5) {
  39299. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39300. }
  39301. if (parsedGeometry.uvs6) {
  39302. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39303. }
  39304. if (parsedGeometry.colors) {
  39305. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39306. }
  39307. if (parsedGeometry.matricesIndices) {
  39308. if (!parsedGeometry.matricesIndices._isExpanded) {
  39309. var floatIndices = [];
  39310. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39311. var matricesIndex = parsedGeometry.matricesIndices[i];
  39312. floatIndices.push(matricesIndex & 0x000000FF);
  39313. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39314. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39315. floatIndices.push(matricesIndex >> 24);
  39316. }
  39317. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39318. }
  39319. else {
  39320. delete parsedGeometry.matricesIndices._isExpanded;
  39321. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39322. }
  39323. }
  39324. if (parsedGeometry.matricesIndicesExtra) {
  39325. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39326. var floatIndices = [];
  39327. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39328. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39329. floatIndices.push(matricesIndex & 0x000000FF);
  39330. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39331. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39332. floatIndices.push(matricesIndex >> 24);
  39333. }
  39334. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39335. }
  39336. else {
  39337. delete parsedGeometry.matricesIndices._isExpanded;
  39338. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39339. }
  39340. }
  39341. if (parsedGeometry.matricesWeights) {
  39342. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39343. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39344. }
  39345. if (parsedGeometry.matricesWeightsExtra) {
  39346. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39347. }
  39348. mesh.setIndices(parsedGeometry.indices, null);
  39349. }
  39350. // SubMeshes
  39351. if (parsedGeometry.subMeshes) {
  39352. mesh.subMeshes = [];
  39353. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39354. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39355. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39356. }
  39357. }
  39358. // Flat shading
  39359. if (mesh._shouldGenerateFlatShading) {
  39360. mesh.convertToFlatShadedMesh();
  39361. delete mesh._shouldGenerateFlatShading;
  39362. }
  39363. // Update
  39364. mesh.computeWorldMatrix(true);
  39365. scene.onMeshImportedObservable.notifyObservers(mesh);
  39366. };
  39367. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39368. var epsilon = 1e-3;
  39369. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39370. return;
  39371. }
  39372. var noInfluenceBoneIndex = 0.0;
  39373. if (parsedGeometry.skeletonId > -1) {
  39374. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39375. if (!skeleton) {
  39376. return;
  39377. }
  39378. noInfluenceBoneIndex = skeleton.bones.length;
  39379. }
  39380. else {
  39381. return;
  39382. }
  39383. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39384. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39385. var matricesWeights = parsedGeometry.matricesWeights;
  39386. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39387. var influencers = parsedGeometry.numBoneInfluencer;
  39388. var size = matricesWeights.length;
  39389. for (var i = 0; i < size; i += 4) {
  39390. var weight = 0.0;
  39391. var firstZeroWeight = -1;
  39392. for (var j = 0; j < 4; j++) {
  39393. var w = matricesWeights[i + j];
  39394. weight += w;
  39395. if (w < epsilon && firstZeroWeight < 0) {
  39396. firstZeroWeight = j;
  39397. }
  39398. }
  39399. if (matricesWeightsExtra) {
  39400. for (var j = 0; j < 4; j++) {
  39401. var w = matricesWeightsExtra[i + j];
  39402. weight += w;
  39403. if (w < epsilon && firstZeroWeight < 0) {
  39404. firstZeroWeight = j + 4;
  39405. }
  39406. }
  39407. }
  39408. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39409. firstZeroWeight = influencers - 1;
  39410. }
  39411. if (weight > epsilon) {
  39412. var mweight = 1.0 / weight;
  39413. for (var j = 0; j < 4; j++) {
  39414. matricesWeights[i + j] *= mweight;
  39415. }
  39416. if (matricesWeightsExtra) {
  39417. for (var j = 0; j < 4; j++) {
  39418. matricesWeightsExtra[i + j] *= mweight;
  39419. }
  39420. }
  39421. }
  39422. else {
  39423. if (firstZeroWeight >= 4) {
  39424. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39425. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39426. }
  39427. else {
  39428. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39429. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39430. }
  39431. }
  39432. }
  39433. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39434. if (parsedGeometry.matricesWeightsExtra) {
  39435. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39436. }
  39437. };
  39438. /**
  39439. * Create a new geometry from persisted data (Using .babylon file format)
  39440. * @param parsedVertexData defines the persisted data
  39441. * @param scene defines the hosting scene
  39442. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39443. * @returns the new geometry object
  39444. */
  39445. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39446. if (scene.getGeometryByID(parsedVertexData.id)) {
  39447. return null; // null since geometry could be something else than a box...
  39448. }
  39449. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39450. if (BABYLON.Tags) {
  39451. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39452. }
  39453. if (parsedVertexData.delayLoadingFile) {
  39454. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39455. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39456. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39457. geometry._delayInfo = [];
  39458. if (parsedVertexData.hasUVs) {
  39459. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39460. }
  39461. if (parsedVertexData.hasUVs2) {
  39462. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39463. }
  39464. if (parsedVertexData.hasUVs3) {
  39465. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39466. }
  39467. if (parsedVertexData.hasUVs4) {
  39468. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39469. }
  39470. if (parsedVertexData.hasUVs5) {
  39471. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39472. }
  39473. if (parsedVertexData.hasUVs6) {
  39474. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39475. }
  39476. if (parsedVertexData.hasColors) {
  39477. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39478. }
  39479. if (parsedVertexData.hasMatricesIndices) {
  39480. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39481. }
  39482. if (parsedVertexData.hasMatricesWeights) {
  39483. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39484. }
  39485. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39486. }
  39487. else {
  39488. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39489. }
  39490. scene.pushGeometry(geometry, true);
  39491. return geometry;
  39492. };
  39493. return Geometry;
  39494. }());
  39495. BABYLON.Geometry = Geometry;
  39496. // Primitives
  39497. /// Abstract class
  39498. /**
  39499. * Abstract class used to provide common services for all typed geometries
  39500. * @hidden
  39501. */
  39502. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39503. __extends(_PrimitiveGeometry, _super);
  39504. /**
  39505. * Creates a new typed geometry
  39506. * @param id defines the unique ID of the geometry
  39507. * @param scene defines the hosting scene
  39508. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39509. * @param mesh defines the hosting mesh (can be null)
  39510. */
  39511. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39512. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39513. if (mesh === void 0) { mesh = null; }
  39514. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39515. _this._canBeRegenerated = _canBeRegenerated;
  39516. _this._beingRegenerated = true;
  39517. _this.regenerate();
  39518. _this._beingRegenerated = false;
  39519. return _this;
  39520. }
  39521. /**
  39522. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39523. * @returns true if the geometry can be regenerated
  39524. */
  39525. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39526. return this._canBeRegenerated;
  39527. };
  39528. /**
  39529. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39530. */
  39531. _PrimitiveGeometry.prototype.regenerate = function () {
  39532. if (!this._canBeRegenerated) {
  39533. return;
  39534. }
  39535. this._beingRegenerated = true;
  39536. this.setAllVerticesData(this._regenerateVertexData(), false);
  39537. this._beingRegenerated = false;
  39538. };
  39539. /**
  39540. * Clone the geometry
  39541. * @param id defines the unique ID of the new geometry
  39542. * @returns the new geometry
  39543. */
  39544. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39545. return _super.prototype.copy.call(this, id);
  39546. };
  39547. // overrides
  39548. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39549. if (!this._beingRegenerated) {
  39550. return;
  39551. }
  39552. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39553. };
  39554. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39555. if (!this._beingRegenerated) {
  39556. return;
  39557. }
  39558. _super.prototype.setVerticesData.call(this, kind, data, false);
  39559. };
  39560. // to override
  39561. /** @hidden */
  39562. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39563. throw new Error("Abstract method");
  39564. };
  39565. _PrimitiveGeometry.prototype.copy = function (id) {
  39566. throw new Error("Must be overriden in sub-classes.");
  39567. };
  39568. _PrimitiveGeometry.prototype.serialize = function () {
  39569. var serializationObject = _super.prototype.serialize.call(this);
  39570. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39571. return serializationObject;
  39572. };
  39573. return _PrimitiveGeometry;
  39574. }(Geometry));
  39575. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39576. /**
  39577. * Creates a ribbon geometry
  39578. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39579. */
  39580. var RibbonGeometry = /** @class */ (function (_super) {
  39581. __extends(RibbonGeometry, _super);
  39582. /**
  39583. * Creates a ribbon geometry
  39584. * @param id defines the unique ID of the geometry
  39585. * @param scene defines the hosting scene
  39586. * @param pathArray defines the array of paths to use
  39587. * @param closeArray defines if the last path and the first path must be joined
  39588. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39589. * @param offset defines the offset between points
  39590. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39591. * @param mesh defines the hosting mesh (can be null)
  39592. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39593. */
  39594. function RibbonGeometry(id, scene,
  39595. /**
  39596. * Defines the array of paths to use
  39597. */
  39598. pathArray,
  39599. /**
  39600. * Defines if the last and first points of each path in your pathArray must be joined
  39601. */
  39602. closeArray,
  39603. /**
  39604. * Defines if the last and first points of each path in your pathArray must be joined
  39605. */
  39606. closePath,
  39607. /**
  39608. * Defines the offset between points
  39609. */
  39610. offset, canBeRegenerated, mesh,
  39611. /**
  39612. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39613. */
  39614. side) {
  39615. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39616. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39617. _this.pathArray = pathArray;
  39618. _this.closeArray = closeArray;
  39619. _this.closePath = closePath;
  39620. _this.offset = offset;
  39621. _this.side = side;
  39622. return _this;
  39623. }
  39624. /** @hidden */
  39625. RibbonGeometry.prototype._regenerateVertexData = function () {
  39626. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39627. };
  39628. RibbonGeometry.prototype.copy = function (id) {
  39629. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39630. };
  39631. return RibbonGeometry;
  39632. }(_PrimitiveGeometry));
  39633. BABYLON.RibbonGeometry = RibbonGeometry;
  39634. /**
  39635. * Creates a box geometry
  39636. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39637. */
  39638. var BoxGeometry = /** @class */ (function (_super) {
  39639. __extends(BoxGeometry, _super);
  39640. /**
  39641. * Creates a box geometry
  39642. * @param id defines the unique ID of the geometry
  39643. * @param scene defines the hosting scene
  39644. * @param size defines the zise of the box (width, height and depth are the same)
  39645. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39646. * @param mesh defines the hosting mesh (can be null)
  39647. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39648. */
  39649. function BoxGeometry(id, scene,
  39650. /**
  39651. * Defines the zise of the box (width, height and depth are the same)
  39652. */
  39653. size, canBeRegenerated, mesh,
  39654. /**
  39655. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39656. */
  39657. side) {
  39658. if (mesh === void 0) { mesh = null; }
  39659. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39660. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39661. _this.size = size;
  39662. _this.side = side;
  39663. return _this;
  39664. }
  39665. /** @hidden */
  39666. BoxGeometry.prototype._regenerateVertexData = function () {
  39667. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39668. };
  39669. BoxGeometry.prototype.copy = function (id) {
  39670. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39671. };
  39672. BoxGeometry.prototype.serialize = function () {
  39673. var serializationObject = _super.prototype.serialize.call(this);
  39674. serializationObject.size = this.size;
  39675. return serializationObject;
  39676. };
  39677. BoxGeometry.Parse = function (parsedBox, scene) {
  39678. if (scene.getGeometryByID(parsedBox.id)) {
  39679. return null; // null since geometry could be something else than a box...
  39680. }
  39681. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39682. if (BABYLON.Tags) {
  39683. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39684. }
  39685. scene.pushGeometry(box, true);
  39686. return box;
  39687. };
  39688. return BoxGeometry;
  39689. }(_PrimitiveGeometry));
  39690. BABYLON.BoxGeometry = BoxGeometry;
  39691. /**
  39692. * Creates a sphere geometry
  39693. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39694. */
  39695. var SphereGeometry = /** @class */ (function (_super) {
  39696. __extends(SphereGeometry, _super);
  39697. /**
  39698. * Create a new sphere geometry
  39699. * @param id defines the unique ID of the geometry
  39700. * @param scene defines the hosting scene
  39701. * @param segments defines the number of segments to use to create the sphere
  39702. * @param diameter defines the diameter of the sphere
  39703. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39704. * @param mesh defines the hosting mesh (can be null)
  39705. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39706. */
  39707. function SphereGeometry(id, scene,
  39708. /**
  39709. * Defines the number of segments to use to create the sphere
  39710. */
  39711. segments,
  39712. /**
  39713. * Defines the diameter of the sphere
  39714. */
  39715. diameter, canBeRegenerated, mesh,
  39716. /**
  39717. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39718. */
  39719. side) {
  39720. if (mesh === void 0) { mesh = null; }
  39721. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39722. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39723. _this.segments = segments;
  39724. _this.diameter = diameter;
  39725. _this.side = side;
  39726. return _this;
  39727. }
  39728. /** @hidden */
  39729. SphereGeometry.prototype._regenerateVertexData = function () {
  39730. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39731. };
  39732. SphereGeometry.prototype.copy = function (id) {
  39733. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39734. };
  39735. SphereGeometry.prototype.serialize = function () {
  39736. var serializationObject = _super.prototype.serialize.call(this);
  39737. serializationObject.segments = this.segments;
  39738. serializationObject.diameter = this.diameter;
  39739. return serializationObject;
  39740. };
  39741. SphereGeometry.Parse = function (parsedSphere, scene) {
  39742. if (scene.getGeometryByID(parsedSphere.id)) {
  39743. return null; // null since geometry could be something else than a sphere...
  39744. }
  39745. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39746. if (BABYLON.Tags) {
  39747. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39748. }
  39749. scene.pushGeometry(sphere, true);
  39750. return sphere;
  39751. };
  39752. return SphereGeometry;
  39753. }(_PrimitiveGeometry));
  39754. BABYLON.SphereGeometry = SphereGeometry;
  39755. /**
  39756. * Creates a disc geometry
  39757. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39758. */
  39759. var DiscGeometry = /** @class */ (function (_super) {
  39760. __extends(DiscGeometry, _super);
  39761. /**
  39762. * Creates a new disc geometry
  39763. * @param id defines the unique ID of the geometry
  39764. * @param scene defines the hosting scene
  39765. * @param radius defines the radius of the disc
  39766. * @param tessellation defines the tesselation factor to apply to the disc
  39767. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39768. * @param mesh defines the hosting mesh (can be null)
  39769. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39770. */
  39771. function DiscGeometry(id, scene,
  39772. /**
  39773. * Defines the radius of the disc
  39774. */
  39775. radius,
  39776. /**
  39777. * Defines the tesselation factor to apply to the disc
  39778. */
  39779. tessellation, canBeRegenerated, mesh,
  39780. /**
  39781. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39782. */
  39783. side) {
  39784. if (mesh === void 0) { mesh = null; }
  39785. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39786. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39787. _this.radius = radius;
  39788. _this.tessellation = tessellation;
  39789. _this.side = side;
  39790. return _this;
  39791. }
  39792. /** @hidden */
  39793. DiscGeometry.prototype._regenerateVertexData = function () {
  39794. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39795. };
  39796. DiscGeometry.prototype.copy = function (id) {
  39797. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39798. };
  39799. return DiscGeometry;
  39800. }(_PrimitiveGeometry));
  39801. BABYLON.DiscGeometry = DiscGeometry;
  39802. /**
  39803. * Creates a new cylinder geometry
  39804. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39805. */
  39806. var CylinderGeometry = /** @class */ (function (_super) {
  39807. __extends(CylinderGeometry, _super);
  39808. /**
  39809. * Creates a new cylinder geometry
  39810. * @param id defines the unique ID of the geometry
  39811. * @param scene defines the hosting scene
  39812. * @param height defines the height of the cylinder
  39813. * @param diameterTop defines the diameter of the cylinder's top cap
  39814. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39815. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39816. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39817. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39818. * @param mesh defines the hosting mesh (can be null)
  39819. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39820. */
  39821. function CylinderGeometry(id, scene,
  39822. /**
  39823. * Defines the height of the cylinder
  39824. */
  39825. height,
  39826. /**
  39827. * Defines the diameter of the cylinder's top cap
  39828. */
  39829. diameterTop,
  39830. /**
  39831. * Defines the diameter of the cylinder's bottom cap
  39832. */
  39833. diameterBottom,
  39834. /**
  39835. * Defines the tessellation factor to apply to the cylinder
  39836. */
  39837. tessellation,
  39838. /**
  39839. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39840. */
  39841. subdivisions, canBeRegenerated, mesh,
  39842. /**
  39843. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39844. */
  39845. side) {
  39846. if (subdivisions === void 0) { subdivisions = 1; }
  39847. if (mesh === void 0) { mesh = null; }
  39848. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39849. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39850. _this.height = height;
  39851. _this.diameterTop = diameterTop;
  39852. _this.diameterBottom = diameterBottom;
  39853. _this.tessellation = tessellation;
  39854. _this.subdivisions = subdivisions;
  39855. _this.side = side;
  39856. return _this;
  39857. }
  39858. /** @hidden */
  39859. CylinderGeometry.prototype._regenerateVertexData = function () {
  39860. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39861. };
  39862. CylinderGeometry.prototype.copy = function (id) {
  39863. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39864. };
  39865. CylinderGeometry.prototype.serialize = function () {
  39866. var serializationObject = _super.prototype.serialize.call(this);
  39867. serializationObject.height = this.height;
  39868. serializationObject.diameterTop = this.diameterTop;
  39869. serializationObject.diameterBottom = this.diameterBottom;
  39870. serializationObject.tessellation = this.tessellation;
  39871. return serializationObject;
  39872. };
  39873. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39874. if (scene.getGeometryByID(parsedCylinder.id)) {
  39875. return null; // null since geometry could be something else than a cylinder...
  39876. }
  39877. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  39878. if (BABYLON.Tags) {
  39879. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  39880. }
  39881. scene.pushGeometry(cylinder, true);
  39882. return cylinder;
  39883. };
  39884. return CylinderGeometry;
  39885. }(_PrimitiveGeometry));
  39886. BABYLON.CylinderGeometry = CylinderGeometry;
  39887. /**
  39888. * Creates a new torus geometry
  39889. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  39890. */
  39891. var TorusGeometry = /** @class */ (function (_super) {
  39892. __extends(TorusGeometry, _super);
  39893. /**
  39894. * Creates a new torus geometry
  39895. * @param id defines the unique ID of the geometry
  39896. * @param scene defines the hosting scene
  39897. * @param diameter defines the diameter of the torus
  39898. * @param thickness defines the thickness of the torus (ie. internal diameter)
  39899. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  39900. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39901. * @param mesh defines the hosting mesh (can be null)
  39902. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39903. */
  39904. function TorusGeometry(id, scene,
  39905. /**
  39906. * Defines the diameter of the torus
  39907. */
  39908. diameter,
  39909. /**
  39910. * Defines the thickness of the torus (ie. internal diameter)
  39911. */
  39912. thickness,
  39913. /**
  39914. * Defines the tesselation factor to apply to the torus
  39915. */
  39916. tessellation, canBeRegenerated, mesh,
  39917. /**
  39918. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39919. */
  39920. side) {
  39921. if (mesh === void 0) { mesh = null; }
  39922. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39923. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39924. _this.diameter = diameter;
  39925. _this.thickness = thickness;
  39926. _this.tessellation = tessellation;
  39927. _this.side = side;
  39928. return _this;
  39929. }
  39930. /** @hidden */
  39931. TorusGeometry.prototype._regenerateVertexData = function () {
  39932. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  39933. };
  39934. TorusGeometry.prototype.copy = function (id) {
  39935. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  39936. };
  39937. TorusGeometry.prototype.serialize = function () {
  39938. var serializationObject = _super.prototype.serialize.call(this);
  39939. serializationObject.diameter = this.diameter;
  39940. serializationObject.thickness = this.thickness;
  39941. serializationObject.tessellation = this.tessellation;
  39942. return serializationObject;
  39943. };
  39944. TorusGeometry.Parse = function (parsedTorus, scene) {
  39945. if (scene.getGeometryByID(parsedTorus.id)) {
  39946. return null; // null since geometry could be something else than a torus...
  39947. }
  39948. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  39949. if (BABYLON.Tags) {
  39950. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  39951. }
  39952. scene.pushGeometry(torus, true);
  39953. return torus;
  39954. };
  39955. return TorusGeometry;
  39956. }(_PrimitiveGeometry));
  39957. BABYLON.TorusGeometry = TorusGeometry;
  39958. /**
  39959. * Creates a new ground geometry
  39960. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  39961. */
  39962. var GroundGeometry = /** @class */ (function (_super) {
  39963. __extends(GroundGeometry, _super);
  39964. /**
  39965. * Creates a new ground geometry
  39966. * @param id defines the unique ID of the geometry
  39967. * @param scene defines the hosting scene
  39968. * @param width defines the width of the ground
  39969. * @param height defines the height of the ground
  39970. * @param subdivisions defines the subdivisions to apply to the ground
  39971. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39972. * @param mesh defines the hosting mesh (can be null)
  39973. */
  39974. function GroundGeometry(id, scene,
  39975. /**
  39976. * Defines the width of the ground
  39977. */
  39978. width,
  39979. /**
  39980. * Defines the height of the ground
  39981. */
  39982. height,
  39983. /**
  39984. * Defines the subdivisions to apply to the ground
  39985. */
  39986. subdivisions, canBeRegenerated, mesh) {
  39987. if (mesh === void 0) { mesh = null; }
  39988. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39989. _this.width = width;
  39990. _this.height = height;
  39991. _this.subdivisions = subdivisions;
  39992. return _this;
  39993. }
  39994. /** @hidden */
  39995. GroundGeometry.prototype._regenerateVertexData = function () {
  39996. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  39997. };
  39998. GroundGeometry.prototype.copy = function (id) {
  39999. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40000. };
  40001. GroundGeometry.prototype.serialize = function () {
  40002. var serializationObject = _super.prototype.serialize.call(this);
  40003. serializationObject.width = this.width;
  40004. serializationObject.height = this.height;
  40005. serializationObject.subdivisions = this.subdivisions;
  40006. return serializationObject;
  40007. };
  40008. GroundGeometry.Parse = function (parsedGround, scene) {
  40009. if (scene.getGeometryByID(parsedGround.id)) {
  40010. return null; // null since geometry could be something else than a ground...
  40011. }
  40012. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40013. if (BABYLON.Tags) {
  40014. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40015. }
  40016. scene.pushGeometry(ground, true);
  40017. return ground;
  40018. };
  40019. return GroundGeometry;
  40020. }(_PrimitiveGeometry));
  40021. BABYLON.GroundGeometry = GroundGeometry;
  40022. /**
  40023. * Creates a tiled ground geometry
  40024. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40025. */
  40026. var TiledGroundGeometry = /** @class */ (function (_super) {
  40027. __extends(TiledGroundGeometry, _super);
  40028. /**
  40029. * Creates a tiled ground geometry
  40030. * @param id defines the unique ID of the geometry
  40031. * @param scene defines the hosting scene
  40032. * @param xmin defines the minimum value on X axis
  40033. * @param zmin defines the minimum value on Z axis
  40034. * @param xmax defines the maximum value on X axis
  40035. * @param zmax defines the maximum value on Z axis
  40036. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40037. * @param precision defines the precision to use when computing the tiles
  40038. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40039. * @param mesh defines the hosting mesh (can be null)
  40040. */
  40041. function TiledGroundGeometry(id, scene,
  40042. /**
  40043. * Defines the minimum value on X axis
  40044. */
  40045. xmin,
  40046. /**
  40047. * Defines the minimum value on Z axis
  40048. */
  40049. zmin,
  40050. /**
  40051. * Defines the maximum value on X axis
  40052. */
  40053. xmax,
  40054. /**
  40055. * Defines the maximum value on Z axis
  40056. */
  40057. zmax,
  40058. /**
  40059. * Defines the subdivisions to apply to the ground
  40060. */
  40061. subdivisions,
  40062. /**
  40063. * Defines the precision to use when computing the tiles
  40064. */
  40065. precision, canBeRegenerated, mesh) {
  40066. if (mesh === void 0) { mesh = null; }
  40067. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40068. _this.xmin = xmin;
  40069. _this.zmin = zmin;
  40070. _this.xmax = xmax;
  40071. _this.zmax = zmax;
  40072. _this.subdivisions = subdivisions;
  40073. _this.precision = precision;
  40074. return _this;
  40075. }
  40076. /** @hidden */
  40077. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40078. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40079. };
  40080. TiledGroundGeometry.prototype.copy = function (id) {
  40081. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40082. };
  40083. return TiledGroundGeometry;
  40084. }(_PrimitiveGeometry));
  40085. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40086. /**
  40087. * Creates a plane geometry
  40088. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40089. */
  40090. var PlaneGeometry = /** @class */ (function (_super) {
  40091. __extends(PlaneGeometry, _super);
  40092. /**
  40093. * Creates a plane geometry
  40094. * @param id defines the unique ID of the geometry
  40095. * @param scene defines the hosting scene
  40096. * @param size defines the size of the plane (width === height)
  40097. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40098. * @param mesh defines the hosting mesh (can be null)
  40099. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40100. */
  40101. function PlaneGeometry(id, scene,
  40102. /**
  40103. * Defines the size of the plane (width === height)
  40104. */
  40105. size, canBeRegenerated, mesh,
  40106. /**
  40107. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40108. */
  40109. side) {
  40110. if (mesh === void 0) { mesh = null; }
  40111. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40112. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40113. _this.size = size;
  40114. _this.side = side;
  40115. return _this;
  40116. }
  40117. /** @hidden */
  40118. PlaneGeometry.prototype._regenerateVertexData = function () {
  40119. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40120. };
  40121. PlaneGeometry.prototype.copy = function (id) {
  40122. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40123. };
  40124. PlaneGeometry.prototype.serialize = function () {
  40125. var serializationObject = _super.prototype.serialize.call(this);
  40126. serializationObject.size = this.size;
  40127. return serializationObject;
  40128. };
  40129. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40130. if (scene.getGeometryByID(parsedPlane.id)) {
  40131. return null; // null since geometry could be something else than a ground...
  40132. }
  40133. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40134. if (BABYLON.Tags) {
  40135. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40136. }
  40137. scene.pushGeometry(plane, true);
  40138. return plane;
  40139. };
  40140. return PlaneGeometry;
  40141. }(_PrimitiveGeometry));
  40142. BABYLON.PlaneGeometry = PlaneGeometry;
  40143. /**
  40144. * Creates a torus knot geometry
  40145. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40146. */
  40147. var TorusKnotGeometry = /** @class */ (function (_super) {
  40148. __extends(TorusKnotGeometry, _super);
  40149. /**
  40150. * Creates a torus knot geometry
  40151. * @param id defines the unique ID of the geometry
  40152. * @param scene defines the hosting scene
  40153. * @param radius defines the radius of the torus knot
  40154. * @param tube defines the thickness of the torus knot tube
  40155. * @param radialSegments defines the number of radial segments
  40156. * @param tubularSegments defines the number of tubular segments
  40157. * @param p defines the first number of windings
  40158. * @param q defines the second number of windings
  40159. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40160. * @param mesh defines the hosting mesh (can be null)
  40161. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40162. */
  40163. function TorusKnotGeometry(id, scene,
  40164. /**
  40165. * Defines the radius of the torus knot
  40166. */
  40167. radius,
  40168. /**
  40169. * Defines the thickness of the torus knot tube
  40170. */
  40171. tube,
  40172. /**
  40173. * Defines the number of radial segments
  40174. */
  40175. radialSegments,
  40176. /**
  40177. * Defines the number of tubular segments
  40178. */
  40179. tubularSegments,
  40180. /**
  40181. * Defines the first number of windings
  40182. */
  40183. p,
  40184. /**
  40185. * Defines the second number of windings
  40186. */
  40187. q, canBeRegenerated, mesh,
  40188. /**
  40189. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40190. */
  40191. side) {
  40192. if (mesh === void 0) { mesh = null; }
  40193. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40194. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40195. _this.radius = radius;
  40196. _this.tube = tube;
  40197. _this.radialSegments = radialSegments;
  40198. _this.tubularSegments = tubularSegments;
  40199. _this.p = p;
  40200. _this.q = q;
  40201. _this.side = side;
  40202. return _this;
  40203. }
  40204. /** @hidden */
  40205. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40206. 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 });
  40207. };
  40208. TorusKnotGeometry.prototype.copy = function (id) {
  40209. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40210. };
  40211. TorusKnotGeometry.prototype.serialize = function () {
  40212. var serializationObject = _super.prototype.serialize.call(this);
  40213. serializationObject.radius = this.radius;
  40214. serializationObject.tube = this.tube;
  40215. serializationObject.radialSegments = this.radialSegments;
  40216. serializationObject.tubularSegments = this.tubularSegments;
  40217. serializationObject.p = this.p;
  40218. serializationObject.q = this.q;
  40219. return serializationObject;
  40220. };
  40221. ;
  40222. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40223. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40224. return null; // null since geometry could be something else than a ground...
  40225. }
  40226. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40227. if (BABYLON.Tags) {
  40228. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40229. }
  40230. scene.pushGeometry(torusKnot, true);
  40231. return torusKnot;
  40232. };
  40233. return TorusKnotGeometry;
  40234. }(_PrimitiveGeometry));
  40235. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40236. //}
  40237. })(BABYLON || (BABYLON = {}));
  40238. //# sourceMappingURL=babylon.geometry.js.map
  40239. var BABYLON;
  40240. (function (BABYLON) {
  40241. /**
  40242. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40243. */
  40244. var PerformanceMonitor = /** @class */ (function () {
  40245. /**
  40246. * constructor
  40247. * @param frameSampleSize The number of samples required to saturate the sliding window
  40248. */
  40249. function PerformanceMonitor(frameSampleSize) {
  40250. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40251. this._enabled = true;
  40252. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40253. }
  40254. /**
  40255. * Samples current frame
  40256. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40257. */
  40258. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40259. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40260. if (!this._enabled)
  40261. return;
  40262. if (this._lastFrameTimeMs != null) {
  40263. var dt = timeMs - this._lastFrameTimeMs;
  40264. this._rollingFrameTime.add(dt);
  40265. }
  40266. this._lastFrameTimeMs = timeMs;
  40267. };
  40268. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40269. /**
  40270. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40271. * @return Average frame time in milliseconds
  40272. */
  40273. get: function () {
  40274. return this._rollingFrameTime.average;
  40275. },
  40276. enumerable: true,
  40277. configurable: true
  40278. });
  40279. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40280. /**
  40281. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40282. * @return Frame time variance in milliseconds squared
  40283. */
  40284. get: function () {
  40285. return this._rollingFrameTime.variance;
  40286. },
  40287. enumerable: true,
  40288. configurable: true
  40289. });
  40290. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40291. /**
  40292. * Returns the frame time of the most recent frame
  40293. * @return Frame time in milliseconds
  40294. */
  40295. get: function () {
  40296. return this._rollingFrameTime.history(0);
  40297. },
  40298. enumerable: true,
  40299. configurable: true
  40300. });
  40301. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40302. /**
  40303. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40304. * @return Framerate in frames per second
  40305. */
  40306. get: function () {
  40307. return 1000.0 / this._rollingFrameTime.average;
  40308. },
  40309. enumerable: true,
  40310. configurable: true
  40311. });
  40312. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40313. /**
  40314. * Returns the average framerate in frames per second using the most recent frame time
  40315. * @return Framerate in frames per second
  40316. */
  40317. get: function () {
  40318. var history = this._rollingFrameTime.history(0);
  40319. if (history === 0) {
  40320. return 0;
  40321. }
  40322. return 1000.0 / history;
  40323. },
  40324. enumerable: true,
  40325. configurable: true
  40326. });
  40327. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40328. /**
  40329. * Returns true if enough samples have been taken to completely fill the sliding window
  40330. * @return true if saturated
  40331. */
  40332. get: function () {
  40333. return this._rollingFrameTime.isSaturated();
  40334. },
  40335. enumerable: true,
  40336. configurable: true
  40337. });
  40338. /**
  40339. * Enables contributions to the sliding window sample set
  40340. */
  40341. PerformanceMonitor.prototype.enable = function () {
  40342. this._enabled = true;
  40343. };
  40344. /**
  40345. * Disables contributions to the sliding window sample set
  40346. * Samples will not be interpolated over the disabled period
  40347. */
  40348. PerformanceMonitor.prototype.disable = function () {
  40349. this._enabled = false;
  40350. //clear last sample to avoid interpolating over the disabled period when next enabled
  40351. this._lastFrameTimeMs = null;
  40352. };
  40353. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40354. /**
  40355. * Returns true if sampling is enabled
  40356. * @return true if enabled
  40357. */
  40358. get: function () {
  40359. return this._enabled;
  40360. },
  40361. enumerable: true,
  40362. configurable: true
  40363. });
  40364. /**
  40365. * Resets performance monitor
  40366. */
  40367. PerformanceMonitor.prototype.reset = function () {
  40368. //clear last sample to avoid interpolating over the disabled period when next enabled
  40369. this._lastFrameTimeMs = null;
  40370. //wipe record
  40371. this._rollingFrameTime.reset();
  40372. };
  40373. return PerformanceMonitor;
  40374. }());
  40375. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40376. /**
  40377. * RollingAverage
  40378. *
  40379. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40380. */
  40381. var RollingAverage = /** @class */ (function () {
  40382. /**
  40383. * constructor
  40384. * @param length The number of samples required to saturate the sliding window
  40385. */
  40386. function RollingAverage(length) {
  40387. this._samples = new Array(length);
  40388. this.reset();
  40389. }
  40390. /**
  40391. * Adds a sample to the sample set
  40392. * @param v The sample value
  40393. */
  40394. RollingAverage.prototype.add = function (v) {
  40395. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40396. var delta;
  40397. //we need to check if we've already wrapped round
  40398. if (this.isSaturated()) {
  40399. //remove bottom of stack from mean
  40400. var bottomValue = this._samples[this._pos];
  40401. delta = bottomValue - this.average;
  40402. this.average -= delta / (this._sampleCount - 1);
  40403. this._m2 -= delta * (bottomValue - this.average);
  40404. }
  40405. else {
  40406. this._sampleCount++;
  40407. }
  40408. //add new value to mean
  40409. delta = v - this.average;
  40410. this.average += delta / (this._sampleCount);
  40411. this._m2 += delta * (v - this.average);
  40412. //set the new variance
  40413. this.variance = this._m2 / (this._sampleCount - 1);
  40414. this._samples[this._pos] = v;
  40415. this._pos++;
  40416. this._pos %= this._samples.length; //positive wrap around
  40417. };
  40418. /**
  40419. * Returns previously added values or null if outside of history or outside the sliding window domain
  40420. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40421. * @return Value previously recorded with add() or null if outside of range
  40422. */
  40423. RollingAverage.prototype.history = function (i) {
  40424. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40425. return 0;
  40426. }
  40427. var i0 = this._wrapPosition(this._pos - 1.0);
  40428. return this._samples[this._wrapPosition(i0 - i)];
  40429. };
  40430. /**
  40431. * Returns true if enough samples have been taken to completely fill the sliding window
  40432. * @return true if sample-set saturated
  40433. */
  40434. RollingAverage.prototype.isSaturated = function () {
  40435. return this._sampleCount >= this._samples.length;
  40436. };
  40437. /**
  40438. * Resets the rolling average (equivalent to 0 samples taken so far)
  40439. */
  40440. RollingAverage.prototype.reset = function () {
  40441. this.average = 0;
  40442. this.variance = 0;
  40443. this._sampleCount = 0;
  40444. this._pos = 0;
  40445. this._m2 = 0;
  40446. };
  40447. /**
  40448. * Wraps a value around the sample range boundaries
  40449. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40450. * @return Wrapped position in sample range
  40451. */
  40452. RollingAverage.prototype._wrapPosition = function (i) {
  40453. var max = this._samples.length;
  40454. return ((i % max) + max) % max;
  40455. };
  40456. return RollingAverage;
  40457. }());
  40458. BABYLON.RollingAverage = RollingAverage;
  40459. })(BABYLON || (BABYLON = {}));
  40460. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40461. var BABYLON;
  40462. (function (BABYLON) {
  40463. /**
  40464. * "Static Class" containing the most commonly used helper while dealing with material for
  40465. * rendering purpose.
  40466. *
  40467. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40468. *
  40469. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40470. */
  40471. var MaterialHelper = /** @class */ (function () {
  40472. function MaterialHelper() {
  40473. }
  40474. /**
  40475. * Bind the current view position to an effect.
  40476. * @param effect The effect to be bound
  40477. * @param scene The scene the eyes position is used from
  40478. */
  40479. MaterialHelper.BindEyePosition = function (effect, scene) {
  40480. if (scene._forcedViewPosition) {
  40481. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40482. return;
  40483. }
  40484. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40485. };
  40486. /**
  40487. * Helps preparing the defines values about the UVs in used in the effect.
  40488. * UVs are shared as much as we can accross chanels in the shaders.
  40489. * @param texture The texture we are preparing the UVs for
  40490. * @param defines The defines to update
  40491. * @param key The chanel key "diffuse", "specular"... used in the shader
  40492. */
  40493. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40494. defines._needUVs = true;
  40495. defines[key] = true;
  40496. if (texture.getTextureMatrix().isIdentity(true)) {
  40497. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40498. if (texture.coordinatesIndex === 0) {
  40499. defines["MAINUV1"] = true;
  40500. }
  40501. else {
  40502. defines["MAINUV2"] = true;
  40503. }
  40504. }
  40505. else {
  40506. defines[key + "DIRECTUV"] = 0;
  40507. }
  40508. };
  40509. /**
  40510. * Binds a texture matrix value to its corrsponding uniform
  40511. * @param texture The texture to bind the matrix for
  40512. * @param uniformBuffer The uniform buffer receivin the data
  40513. * @param key The chanel key "diffuse", "specular"... used in the shader
  40514. */
  40515. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40516. var matrix = texture.getTextureMatrix();
  40517. if (!matrix.isIdentity(true)) {
  40518. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40519. }
  40520. };
  40521. /**
  40522. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40523. * @param mesh defines the current mesh
  40524. * @param scene defines the current scene
  40525. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40526. * @param pointsCloud defines if point cloud rendering has to be turned on
  40527. * @param fogEnabled defines if fog has to be turned on
  40528. * @param alphaTest defines if alpha testing has to be turned on
  40529. * @param defines defines the current list of defines
  40530. */
  40531. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40532. if (defines._areMiscDirty) {
  40533. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40534. defines["POINTSIZE"] = pointsCloud;
  40535. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40536. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40537. defines["ALPHATEST"] = alphaTest;
  40538. }
  40539. };
  40540. /**
  40541. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40542. * @param scene defines the current scene
  40543. * @param engine defines the current engine
  40544. * @param defines specifies the list of active defines
  40545. * @param useInstances defines if instances have to be turned on
  40546. * @param useClipPlane defines if clip plane have to be turned on
  40547. */
  40548. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40549. if (useClipPlane === void 0) { useClipPlane = null; }
  40550. var changed = false;
  40551. var useClipPlane1 = false;
  40552. var useClipPlane2 = false;
  40553. var useClipPlane3 = false;
  40554. var useClipPlane4 = false;
  40555. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  40556. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  40557. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  40558. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  40559. if (defines["CLIPPLANE"] !== useClipPlane1) {
  40560. defines["CLIPPLANE"] = useClipPlane1;
  40561. changed = true;
  40562. }
  40563. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  40564. defines["CLIPPLANE2"] = useClipPlane2;
  40565. changed = true;
  40566. }
  40567. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  40568. defines["CLIPPLANE3"] = useClipPlane3;
  40569. changed = true;
  40570. }
  40571. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  40572. defines["CLIPPLANE4"] = useClipPlane4;
  40573. changed = true;
  40574. }
  40575. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40576. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40577. changed = true;
  40578. }
  40579. if (defines["INSTANCES"] !== useInstances) {
  40580. defines["INSTANCES"] = useInstances;
  40581. changed = true;
  40582. }
  40583. if (changed) {
  40584. defines.markAsUnprocessed();
  40585. }
  40586. };
  40587. /**
  40588. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40589. * @param mesh The mesh containing the geometry data we will draw
  40590. * @param defines The defines to update
  40591. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40592. * @param useBones Precise whether bones should be used or not (override mesh info)
  40593. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40594. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40595. * @returns false if defines are considered not dirty and have not been checked
  40596. */
  40597. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40598. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40599. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40600. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40601. return false;
  40602. }
  40603. defines._normals = defines._needNormals;
  40604. defines._uvs = defines._needUVs;
  40605. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40606. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40607. defines["TANGENT"] = true;
  40608. }
  40609. if (defines._needUVs) {
  40610. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40611. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40612. }
  40613. else {
  40614. defines["UV1"] = false;
  40615. defines["UV2"] = false;
  40616. }
  40617. if (useVertexColor) {
  40618. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40619. defines["VERTEXCOLOR"] = hasVertexColors;
  40620. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40621. }
  40622. if (useBones) {
  40623. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40624. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40625. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40626. }
  40627. else {
  40628. defines["NUM_BONE_INFLUENCERS"] = 0;
  40629. defines["BonesPerMesh"] = 0;
  40630. }
  40631. }
  40632. if (useMorphTargets) {
  40633. var manager = mesh.morphTargetManager;
  40634. if (manager) {
  40635. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40636. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40637. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40638. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40639. }
  40640. else {
  40641. defines["MORPHTARGETS_TANGENT"] = false;
  40642. defines["MORPHTARGETS_NORMAL"] = false;
  40643. defines["MORPHTARGETS"] = false;
  40644. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40645. }
  40646. }
  40647. return true;
  40648. };
  40649. /**
  40650. * Prepares the defines related to the light information passed in parameter
  40651. * @param scene The scene we are intending to draw
  40652. * @param mesh The mesh the effect is compiling for
  40653. * @param defines The defines to update
  40654. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40655. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40656. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40657. * @returns true if normals will be required for the rest of the effect
  40658. */
  40659. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40660. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40661. if (disableLighting === void 0) { disableLighting = false; }
  40662. if (!defines._areLightsDirty) {
  40663. return defines._needNormals;
  40664. }
  40665. var lightIndex = 0;
  40666. var needNormals = false;
  40667. var needRebuild = false;
  40668. var lightmapMode = false;
  40669. var shadowEnabled = false;
  40670. var specularEnabled = false;
  40671. if (scene.lightsEnabled && !disableLighting) {
  40672. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40673. var light = _a[_i];
  40674. needNormals = true;
  40675. if (defines["LIGHT" + lightIndex] === undefined) {
  40676. needRebuild = true;
  40677. }
  40678. defines["LIGHT" + lightIndex] = true;
  40679. defines["SPOTLIGHT" + lightIndex] = false;
  40680. defines["HEMILIGHT" + lightIndex] = false;
  40681. defines["POINTLIGHT" + lightIndex] = false;
  40682. defines["DIRLIGHT" + lightIndex] = false;
  40683. light.prepareLightSpecificDefines(defines, lightIndex);
  40684. // FallOff.
  40685. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  40686. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  40687. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  40688. switch (light.falloffType) {
  40689. case BABYLON.Light.FALLOFF_GLTF:
  40690. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  40691. break;
  40692. case BABYLON.Light.FALLOFF_PHYSICAL:
  40693. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  40694. break;
  40695. case BABYLON.Light.FALLOFF_STANDARD:
  40696. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  40697. break;
  40698. }
  40699. // Specular
  40700. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  40701. specularEnabled = true;
  40702. }
  40703. // Shadows
  40704. defines["SHADOW" + lightIndex] = false;
  40705. defines["SHADOWPCF" + lightIndex] = false;
  40706. defines["SHADOWPCSS" + lightIndex] = false;
  40707. defines["SHADOWPOISSON" + lightIndex] = false;
  40708. defines["SHADOWESM" + lightIndex] = false;
  40709. defines["SHADOWCUBE" + lightIndex] = false;
  40710. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  40711. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  40712. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  40713. var shadowGenerator = light.getShadowGenerator();
  40714. if (shadowGenerator) {
  40715. var shadowMap = shadowGenerator.getShadowMap();
  40716. if (shadowMap) {
  40717. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  40718. shadowEnabled = true;
  40719. shadowGenerator.prepareDefines(defines, lightIndex);
  40720. }
  40721. }
  40722. }
  40723. }
  40724. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  40725. lightmapMode = true;
  40726. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  40727. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  40728. }
  40729. else {
  40730. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  40731. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  40732. }
  40733. lightIndex++;
  40734. if (lightIndex === maxSimultaneousLights)
  40735. break;
  40736. }
  40737. }
  40738. defines["SPECULARTERM"] = specularEnabled;
  40739. defines["SHADOWS"] = shadowEnabled;
  40740. // Resetting all other lights if any
  40741. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  40742. if (defines["LIGHT" + index] !== undefined) {
  40743. defines["LIGHT" + index] = false;
  40744. defines["HEMILIGHT" + lightIndex] = false;
  40745. defines["POINTLIGHT" + lightIndex] = false;
  40746. defines["DIRLIGHT" + lightIndex] = false;
  40747. defines["SPOTLIGHT" + lightIndex] = false;
  40748. defines["SHADOW" + lightIndex] = false;
  40749. }
  40750. }
  40751. var caps = scene.getEngine().getCaps();
  40752. if (defines["SHADOWFLOAT"] === undefined) {
  40753. needRebuild = true;
  40754. }
  40755. defines["SHADOWFLOAT"] = shadowEnabled &&
  40756. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  40757. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  40758. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  40759. if (needRebuild) {
  40760. defines.rebuild();
  40761. }
  40762. return needNormals;
  40763. };
  40764. /**
  40765. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  40766. * that won t be acctive due to defines being turned off.
  40767. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  40768. * @param samplersList The samplers list
  40769. * @param defines The defines helping in the list generation
  40770. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  40771. */
  40772. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  40773. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40774. var uniformsList;
  40775. var uniformBuffersList = null;
  40776. if (uniformsListOrOptions.uniformsNames) {
  40777. var options = uniformsListOrOptions;
  40778. uniformsList = options.uniformsNames;
  40779. uniformBuffersList = options.uniformBuffersNames;
  40780. samplersList = options.samplers;
  40781. defines = options.defines;
  40782. maxSimultaneousLights = options.maxSimultaneousLights;
  40783. }
  40784. else {
  40785. uniformsList = uniformsListOrOptions;
  40786. if (!samplersList) {
  40787. samplersList = [];
  40788. }
  40789. }
  40790. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40791. if (!defines["LIGHT" + lightIndex]) {
  40792. break;
  40793. }
  40794. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  40795. if (uniformBuffersList) {
  40796. uniformBuffersList.push("Light" + lightIndex);
  40797. }
  40798. samplersList.push("shadowSampler" + lightIndex);
  40799. samplersList.push("depthSampler" + lightIndex);
  40800. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  40801. samplersList.push("projectionLightSampler" + lightIndex);
  40802. uniformsList.push("textureProjectionMatrix" + lightIndex);
  40803. }
  40804. }
  40805. if (defines["NUM_MORPH_INFLUENCERS"]) {
  40806. uniformsList.push("morphTargetInfluences");
  40807. }
  40808. };
  40809. /**
  40810. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  40811. * @param defines The defines to update while falling back
  40812. * @param fallbacks The authorized effect fallbacks
  40813. * @param maxSimultaneousLights The maximum number of lights allowed
  40814. * @param rank the current rank of the Effect
  40815. * @returns The newly affected rank
  40816. */
  40817. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  40818. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40819. if (rank === void 0) { rank = 0; }
  40820. var lightFallbackRank = 0;
  40821. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40822. if (!defines["LIGHT" + lightIndex]) {
  40823. break;
  40824. }
  40825. if (lightIndex > 0) {
  40826. lightFallbackRank = rank + lightIndex;
  40827. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  40828. }
  40829. if (!defines["SHADOWS"]) {
  40830. if (defines["SHADOW" + lightIndex]) {
  40831. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  40832. }
  40833. if (defines["SHADOWPCF" + lightIndex]) {
  40834. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  40835. }
  40836. if (defines["SHADOWPCSS" + lightIndex]) {
  40837. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  40838. }
  40839. if (defines["SHADOWPOISSON" + lightIndex]) {
  40840. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  40841. }
  40842. if (defines["SHADOWESM" + lightIndex]) {
  40843. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  40844. }
  40845. }
  40846. }
  40847. return lightFallbackRank++;
  40848. };
  40849. /**
  40850. * Prepares the list of attributes required for morph targets according to the effect defines.
  40851. * @param attribs The current list of supported attribs
  40852. * @param mesh The mesh to prepare the morph targets attributes for
  40853. * @param defines The current Defines of the effect
  40854. */
  40855. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  40856. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  40857. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  40858. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  40859. var manager = mesh.morphTargetManager;
  40860. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  40861. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  40862. for (var index = 0; index < influencers; index++) {
  40863. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  40864. if (normal) {
  40865. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  40866. }
  40867. if (tangent) {
  40868. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  40869. }
  40870. if (attribs.length > maxAttributesCount) {
  40871. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  40872. }
  40873. }
  40874. }
  40875. };
  40876. /**
  40877. * Prepares the list of attributes required for bones according to the effect defines.
  40878. * @param attribs The current list of supported attribs
  40879. * @param mesh The mesh to prepare the bones attributes for
  40880. * @param defines The current Defines of the effect
  40881. * @param fallbacks The current efffect fallback strategy
  40882. */
  40883. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  40884. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  40885. fallbacks.addCPUSkinningFallback(0, mesh);
  40886. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40887. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40888. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  40889. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40890. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  40891. }
  40892. }
  40893. };
  40894. /**
  40895. * Prepares the list of attributes required for instances according to the effect defines.
  40896. * @param attribs The current list of supported attribs
  40897. * @param defines The current Defines of the effect
  40898. */
  40899. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  40900. if (defines["INSTANCES"]) {
  40901. attribs.push("world0");
  40902. attribs.push("world1");
  40903. attribs.push("world2");
  40904. attribs.push("world3");
  40905. }
  40906. };
  40907. /**
  40908. * Binds the light shadow information to the effect for the given mesh.
  40909. * @param light The light containing the generator
  40910. * @param scene The scene the lights belongs to
  40911. * @param mesh The mesh we are binding the information to render
  40912. * @param lightIndex The light index in the effect used to render the mesh
  40913. * @param effect The effect we are binding the data to
  40914. */
  40915. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  40916. if (light.shadowEnabled && mesh.receiveShadows) {
  40917. var shadowGenerator = light.getShadowGenerator();
  40918. if (shadowGenerator) {
  40919. shadowGenerator.bindShadowLight(lightIndex, effect);
  40920. }
  40921. }
  40922. };
  40923. /**
  40924. * Binds the light information to the effect.
  40925. * @param light The light containing the generator
  40926. * @param effect The effect we are binding the data to
  40927. * @param lightIndex The light index in the effect used to render
  40928. */
  40929. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  40930. light.transferToEffect(effect, lightIndex + "");
  40931. };
  40932. /**
  40933. * Binds the lights information from the scene to the effect for the given mesh.
  40934. * @param scene The scene the lights belongs to
  40935. * @param mesh The mesh we are binding the information to render
  40936. * @param effect The effect we are binding the data to
  40937. * @param defines The generated defines for the effect
  40938. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  40939. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  40940. */
  40941. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  40942. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40943. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  40944. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  40945. for (var i = 0; i < len; i++) {
  40946. var light = mesh._lightSources[i];
  40947. var iAsString = i.toString();
  40948. var scaledIntensity = light.getScaledIntensity();
  40949. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  40950. MaterialHelper.BindLightProperties(light, effect, i);
  40951. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  40952. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  40953. if (defines["SPECULARTERM"]) {
  40954. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  40955. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  40956. }
  40957. // Shadows
  40958. if (scene.shadowsEnabled) {
  40959. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  40960. }
  40961. light._uniformBuffer.update();
  40962. }
  40963. };
  40964. /**
  40965. * Binds the fog information from the scene to the effect for the given mesh.
  40966. * @param scene The scene the lights belongs to
  40967. * @param mesh The mesh we are binding the information to render
  40968. * @param effect The effect we are binding the data to
  40969. */
  40970. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  40971. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  40972. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  40973. effect.setColor3("vFogColor", scene.fogColor);
  40974. }
  40975. };
  40976. /**
  40977. * Binds the bones information from the mesh to the effect.
  40978. * @param mesh The mesh we are binding the information to render
  40979. * @param effect The effect we are binding the data to
  40980. */
  40981. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  40982. if (!effect || !mesh) {
  40983. return;
  40984. }
  40985. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  40986. mesh.computeBonesUsingShaders = false;
  40987. }
  40988. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40989. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  40990. if (matrices) {
  40991. effect.setMatrices("mBones", matrices);
  40992. }
  40993. }
  40994. };
  40995. /**
  40996. * Binds the morph targets information from the mesh to the effect.
  40997. * @param abstractMesh The mesh we are binding the information to render
  40998. * @param effect The effect we are binding the data to
  40999. */
  41000. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41001. var manager = abstractMesh.morphTargetManager;
  41002. if (!abstractMesh || !manager) {
  41003. return;
  41004. }
  41005. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41006. };
  41007. /**
  41008. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41009. * @param defines The generated defines used in the effect
  41010. * @param effect The effect we are binding the data to
  41011. * @param scene The scene we are willing to render with logarithmic scale for
  41012. */
  41013. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41014. if (defines["LOGARITHMICDEPTH"]) {
  41015. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41016. }
  41017. };
  41018. /**
  41019. * Binds the clip plane information from the scene to the effect.
  41020. * @param scene The scene the clip plane information are extracted from
  41021. * @param effect The effect we are binding the data to
  41022. */
  41023. MaterialHelper.BindClipPlane = function (effect, scene) {
  41024. if (scene.clipPlane) {
  41025. var clipPlane = scene.clipPlane;
  41026. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41027. }
  41028. if (scene.clipPlane2) {
  41029. var clipPlane = scene.clipPlane2;
  41030. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41031. }
  41032. if (scene.clipPlane3) {
  41033. var clipPlane = scene.clipPlane3;
  41034. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41035. }
  41036. if (scene.clipPlane4) {
  41037. var clipPlane = scene.clipPlane4;
  41038. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41039. }
  41040. };
  41041. return MaterialHelper;
  41042. }());
  41043. BABYLON.MaterialHelper = MaterialHelper;
  41044. })(BABYLON || (BABYLON = {}));
  41045. //# sourceMappingURL=babylon.materialHelper.js.map
  41046. var BABYLON;
  41047. (function (BABYLON) {
  41048. var PushMaterial = /** @class */ (function (_super) {
  41049. __extends(PushMaterial, _super);
  41050. function PushMaterial(name, scene) {
  41051. var _this = _super.call(this, name, scene) || this;
  41052. _this._normalMatrix = new BABYLON.Matrix();
  41053. _this.storeEffectOnSubMeshes = true;
  41054. return _this;
  41055. }
  41056. PushMaterial.prototype.getEffect = function () {
  41057. return this._activeEffect;
  41058. };
  41059. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41060. if (!mesh) {
  41061. return false;
  41062. }
  41063. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41064. return true;
  41065. }
  41066. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41067. };
  41068. /**
  41069. * Binds the given world matrix to the active effect
  41070. *
  41071. * @param world the matrix to bind
  41072. */
  41073. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41074. this._activeEffect.setMatrix("world", world);
  41075. };
  41076. /**
  41077. * Binds the given normal matrix to the active effect
  41078. *
  41079. * @param normalMatrix the matrix to bind
  41080. */
  41081. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41082. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41083. };
  41084. PushMaterial.prototype.bind = function (world, mesh) {
  41085. if (!mesh) {
  41086. return;
  41087. }
  41088. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41089. };
  41090. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41091. if (effect === void 0) { effect = null; }
  41092. _super.prototype._afterBind.call(this, mesh);
  41093. this.getScene()._cachedEffect = effect;
  41094. };
  41095. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41096. if (visibility === void 0) { visibility = 1; }
  41097. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41098. };
  41099. return PushMaterial;
  41100. }(BABYLON.Material));
  41101. BABYLON.PushMaterial = PushMaterial;
  41102. })(BABYLON || (BABYLON = {}));
  41103. //# sourceMappingURL=babylon.pushMaterial.js.map
  41104. var BABYLON;
  41105. (function (BABYLON) {
  41106. /** @hidden */
  41107. var StandardMaterialDefines = /** @class */ (function (_super) {
  41108. __extends(StandardMaterialDefines, _super);
  41109. function StandardMaterialDefines() {
  41110. var _this = _super.call(this) || this;
  41111. _this.MAINUV1 = false;
  41112. _this.MAINUV2 = false;
  41113. _this.DIFFUSE = false;
  41114. _this.DIFFUSEDIRECTUV = 0;
  41115. _this.AMBIENT = false;
  41116. _this.AMBIENTDIRECTUV = 0;
  41117. _this.OPACITY = false;
  41118. _this.OPACITYDIRECTUV = 0;
  41119. _this.OPACITYRGB = false;
  41120. _this.REFLECTION = false;
  41121. _this.EMISSIVE = false;
  41122. _this.EMISSIVEDIRECTUV = 0;
  41123. _this.SPECULAR = false;
  41124. _this.SPECULARDIRECTUV = 0;
  41125. _this.BUMP = false;
  41126. _this.BUMPDIRECTUV = 0;
  41127. _this.PARALLAX = false;
  41128. _this.PARALLAXOCCLUSION = false;
  41129. _this.SPECULAROVERALPHA = false;
  41130. _this.CLIPPLANE = false;
  41131. _this.CLIPPLANE2 = false;
  41132. _this.CLIPPLANE3 = false;
  41133. _this.CLIPPLANE4 = false;
  41134. _this.ALPHATEST = false;
  41135. _this.DEPTHPREPASS = false;
  41136. _this.ALPHAFROMDIFFUSE = false;
  41137. _this.POINTSIZE = false;
  41138. _this.FOG = false;
  41139. _this.SPECULARTERM = false;
  41140. _this.DIFFUSEFRESNEL = false;
  41141. _this.OPACITYFRESNEL = false;
  41142. _this.REFLECTIONFRESNEL = false;
  41143. _this.REFRACTIONFRESNEL = false;
  41144. _this.EMISSIVEFRESNEL = false;
  41145. _this.FRESNEL = false;
  41146. _this.NORMAL = false;
  41147. _this.UV1 = false;
  41148. _this.UV2 = false;
  41149. _this.VERTEXCOLOR = false;
  41150. _this.VERTEXALPHA = false;
  41151. _this.NUM_BONE_INFLUENCERS = 0;
  41152. _this.BonesPerMesh = 0;
  41153. _this.INSTANCES = false;
  41154. _this.GLOSSINESS = false;
  41155. _this.ROUGHNESS = false;
  41156. _this.EMISSIVEASILLUMINATION = false;
  41157. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41158. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41159. _this.LIGHTMAP = false;
  41160. _this.LIGHTMAPDIRECTUV = 0;
  41161. _this.OBJECTSPACE_NORMALMAP = false;
  41162. _this.USELIGHTMAPASSHADOWMAP = false;
  41163. _this.REFLECTIONMAP_3D = false;
  41164. _this.REFLECTIONMAP_SPHERICAL = false;
  41165. _this.REFLECTIONMAP_PLANAR = false;
  41166. _this.REFLECTIONMAP_CUBIC = false;
  41167. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41168. _this.REFLECTIONMAP_PROJECTION = false;
  41169. _this.REFLECTIONMAP_SKYBOX = false;
  41170. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41171. _this.REFLECTIONMAP_EXPLICIT = false;
  41172. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41173. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41174. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41175. _this.INVERTCUBICMAP = false;
  41176. _this.LOGARITHMICDEPTH = false;
  41177. _this.REFRACTION = false;
  41178. _this.REFRACTIONMAP_3D = false;
  41179. _this.REFLECTIONOVERALPHA = false;
  41180. _this.TWOSIDEDLIGHTING = false;
  41181. _this.SHADOWFLOAT = false;
  41182. _this.MORPHTARGETS = false;
  41183. _this.MORPHTARGETS_NORMAL = false;
  41184. _this.MORPHTARGETS_TANGENT = false;
  41185. _this.NUM_MORPH_INFLUENCERS = 0;
  41186. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41187. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41188. _this.IMAGEPROCESSING = false;
  41189. _this.VIGNETTE = false;
  41190. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41191. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41192. _this.TONEMAPPING = false;
  41193. _this.TONEMAPPING_ACES = false;
  41194. _this.CONTRAST = false;
  41195. _this.COLORCURVES = false;
  41196. _this.COLORGRADING = false;
  41197. _this.COLORGRADING3D = false;
  41198. _this.SAMPLER3DGREENDEPTH = false;
  41199. _this.SAMPLER3DBGRMAP = false;
  41200. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41201. /**
  41202. * If the reflection texture on this material is in linear color space
  41203. * @hidden
  41204. */
  41205. _this.IS_REFLECTION_LINEAR = false;
  41206. /**
  41207. * If the refraction texture on this material is in linear color space
  41208. * @hidden
  41209. */
  41210. _this.IS_REFRACTION_LINEAR = false;
  41211. _this.EXPOSURE = false;
  41212. _this.rebuild();
  41213. return _this;
  41214. }
  41215. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41216. var modes = [
  41217. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41218. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41219. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41220. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41221. ];
  41222. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41223. var mode = modes_1[_i];
  41224. this[mode] = (mode === modeToEnable);
  41225. }
  41226. };
  41227. return StandardMaterialDefines;
  41228. }(BABYLON.MaterialDefines));
  41229. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41230. var StandardMaterial = /** @class */ (function (_super) {
  41231. __extends(StandardMaterial, _super);
  41232. function StandardMaterial(name, scene) {
  41233. var _this = _super.call(this, name, scene) || this;
  41234. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41235. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41236. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41237. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41238. _this.specularPower = 64;
  41239. _this._useAlphaFromDiffuseTexture = false;
  41240. _this._useEmissiveAsIllumination = false;
  41241. _this._linkEmissiveWithDiffuse = false;
  41242. _this._useSpecularOverAlpha = false;
  41243. _this._useReflectionOverAlpha = false;
  41244. _this._disableLighting = false;
  41245. _this._useObjectSpaceNormalMap = false;
  41246. _this._useParallax = false;
  41247. _this._useParallaxOcclusion = false;
  41248. _this.parallaxScaleBias = 0.05;
  41249. _this._roughness = 0;
  41250. _this.indexOfRefraction = 0.98;
  41251. _this.invertRefractionY = true;
  41252. /**
  41253. * Defines the alpha limits in alpha test mode
  41254. */
  41255. _this.alphaCutOff = 0.4;
  41256. _this._useLightmapAsShadowmap = false;
  41257. _this._useReflectionFresnelFromSpecular = false;
  41258. _this._useGlossinessFromSpecularMapAlpha = false;
  41259. _this._maxSimultaneousLights = 4;
  41260. /**
  41261. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41262. */
  41263. _this._invertNormalMapX = false;
  41264. /**
  41265. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41266. */
  41267. _this._invertNormalMapY = false;
  41268. /**
  41269. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41270. */
  41271. _this._twoSidedLighting = false;
  41272. _this._renderTargets = new BABYLON.SmartArray(16);
  41273. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41274. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41275. // Setup the default processing configuration to the scene.
  41276. _this._attachImageProcessingConfiguration(null);
  41277. _this.getRenderTargetTextures = function () {
  41278. _this._renderTargets.reset();
  41279. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41280. _this._renderTargets.push(_this._reflectionTexture);
  41281. }
  41282. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41283. _this._renderTargets.push(_this._refractionTexture);
  41284. }
  41285. return _this._renderTargets;
  41286. };
  41287. return _this;
  41288. }
  41289. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41290. /**
  41291. * Gets the image processing configuration used either in this material.
  41292. */
  41293. get: function () {
  41294. return this._imageProcessingConfiguration;
  41295. },
  41296. /**
  41297. * Sets the Default image processing configuration used either in the this material.
  41298. *
  41299. * If sets to null, the scene one is in use.
  41300. */
  41301. set: function (value) {
  41302. this._attachImageProcessingConfiguration(value);
  41303. // Ensure the effect will be rebuilt.
  41304. this._markAllSubMeshesAsTexturesDirty();
  41305. },
  41306. enumerable: true,
  41307. configurable: true
  41308. });
  41309. /**
  41310. * Attaches a new image processing configuration to the Standard Material.
  41311. * @param configuration
  41312. */
  41313. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41314. var _this = this;
  41315. if (configuration === this._imageProcessingConfiguration) {
  41316. return;
  41317. }
  41318. // Detaches observer.
  41319. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41320. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41321. }
  41322. // Pick the scene configuration if needed.
  41323. if (!configuration) {
  41324. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41325. }
  41326. else {
  41327. this._imageProcessingConfiguration = configuration;
  41328. }
  41329. // Attaches observer.
  41330. if (this._imageProcessingConfiguration) {
  41331. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41332. _this._markAllSubMeshesAsImageProcessingDirty();
  41333. });
  41334. }
  41335. };
  41336. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41337. /**
  41338. * Gets wether the color curves effect is enabled.
  41339. */
  41340. get: function () {
  41341. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41342. },
  41343. /**
  41344. * Sets wether the color curves effect is enabled.
  41345. */
  41346. set: function (value) {
  41347. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41348. },
  41349. enumerable: true,
  41350. configurable: true
  41351. });
  41352. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41353. /**
  41354. * Gets wether the color grading effect is enabled.
  41355. */
  41356. get: function () {
  41357. return this.imageProcessingConfiguration.colorGradingEnabled;
  41358. },
  41359. /**
  41360. * Gets wether the color grading effect is enabled.
  41361. */
  41362. set: function (value) {
  41363. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41364. },
  41365. enumerable: true,
  41366. configurable: true
  41367. });
  41368. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41369. /**
  41370. * Gets wether tonemapping is enabled or not.
  41371. */
  41372. get: function () {
  41373. return this._imageProcessingConfiguration.toneMappingEnabled;
  41374. },
  41375. /**
  41376. * Sets wether tonemapping is enabled or not
  41377. */
  41378. set: function (value) {
  41379. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41380. },
  41381. enumerable: true,
  41382. configurable: true
  41383. });
  41384. ;
  41385. ;
  41386. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41387. /**
  41388. * The camera exposure used on this material.
  41389. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41390. * This corresponds to a photographic exposure.
  41391. */
  41392. get: function () {
  41393. return this._imageProcessingConfiguration.exposure;
  41394. },
  41395. /**
  41396. * The camera exposure used on this material.
  41397. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41398. * This corresponds to a photographic exposure.
  41399. */
  41400. set: function (value) {
  41401. this._imageProcessingConfiguration.exposure = value;
  41402. },
  41403. enumerable: true,
  41404. configurable: true
  41405. });
  41406. ;
  41407. ;
  41408. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41409. /**
  41410. * Gets The camera contrast used on this material.
  41411. */
  41412. get: function () {
  41413. return this._imageProcessingConfiguration.contrast;
  41414. },
  41415. /**
  41416. * Sets The camera contrast used on this material.
  41417. */
  41418. set: function (value) {
  41419. this._imageProcessingConfiguration.contrast = value;
  41420. },
  41421. enumerable: true,
  41422. configurable: true
  41423. });
  41424. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41425. /**
  41426. * Gets the Color Grading 2D Lookup Texture.
  41427. */
  41428. get: function () {
  41429. return this._imageProcessingConfiguration.colorGradingTexture;
  41430. },
  41431. /**
  41432. * Sets the Color Grading 2D Lookup Texture.
  41433. */
  41434. set: function (value) {
  41435. this._imageProcessingConfiguration.colorGradingTexture = value;
  41436. },
  41437. enumerable: true,
  41438. configurable: true
  41439. });
  41440. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41441. /**
  41442. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41443. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41444. * 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;
  41445. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41446. */
  41447. get: function () {
  41448. return this._imageProcessingConfiguration.colorCurves;
  41449. },
  41450. /**
  41451. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41452. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41453. * 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;
  41454. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41455. */
  41456. set: function (value) {
  41457. this._imageProcessingConfiguration.colorCurves = value;
  41458. },
  41459. enumerable: true,
  41460. configurable: true
  41461. });
  41462. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  41463. /**
  41464. * Gets a boolean indicating that current material needs to register RTT
  41465. */
  41466. get: function () {
  41467. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41468. return true;
  41469. }
  41470. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41471. return true;
  41472. }
  41473. return false;
  41474. },
  41475. enumerable: true,
  41476. configurable: true
  41477. });
  41478. StandardMaterial.prototype.getClassName = function () {
  41479. return "StandardMaterial";
  41480. };
  41481. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41482. get: function () {
  41483. return this._useLogarithmicDepth;
  41484. },
  41485. set: function (value) {
  41486. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41487. this._markAllSubMeshesAsMiscDirty();
  41488. },
  41489. enumerable: true,
  41490. configurable: true
  41491. });
  41492. StandardMaterial.prototype.needAlphaBlending = function () {
  41493. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41494. };
  41495. StandardMaterial.prototype.needAlphaTesting = function () {
  41496. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41497. };
  41498. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41499. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41500. };
  41501. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41502. return this._diffuseTexture;
  41503. };
  41504. /**
  41505. * Child classes can use it to update shaders
  41506. */
  41507. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41508. if (useInstances === void 0) { useInstances = false; }
  41509. if (subMesh.effect && this.isFrozen) {
  41510. if (this._wasPreviouslyReady) {
  41511. return true;
  41512. }
  41513. }
  41514. if (!subMesh._materialDefines) {
  41515. subMesh._materialDefines = new StandardMaterialDefines();
  41516. }
  41517. var scene = this.getScene();
  41518. var defines = subMesh._materialDefines;
  41519. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41520. if (defines._renderId === scene.getRenderId()) {
  41521. return true;
  41522. }
  41523. }
  41524. var engine = scene.getEngine();
  41525. // Lights
  41526. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41527. // Textures
  41528. if (defines._areTexturesDirty) {
  41529. defines._needUVs = false;
  41530. defines.MAINUV1 = false;
  41531. defines.MAINUV2 = false;
  41532. if (scene.texturesEnabled) {
  41533. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41534. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41535. return false;
  41536. }
  41537. else {
  41538. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41539. }
  41540. }
  41541. else {
  41542. defines.DIFFUSE = false;
  41543. }
  41544. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41545. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41546. return false;
  41547. }
  41548. else {
  41549. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41550. }
  41551. }
  41552. else {
  41553. defines.AMBIENT = false;
  41554. }
  41555. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41556. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41557. return false;
  41558. }
  41559. else {
  41560. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41561. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41562. }
  41563. }
  41564. else {
  41565. defines.OPACITY = false;
  41566. }
  41567. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41568. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41569. return false;
  41570. }
  41571. else {
  41572. defines._needNormals = true;
  41573. defines.REFLECTION = true;
  41574. defines.ROUGHNESS = (this._roughness > 0);
  41575. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41576. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41577. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41578. switch (this._reflectionTexture.coordinatesMode) {
  41579. case BABYLON.Texture.EXPLICIT_MODE:
  41580. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41581. break;
  41582. case BABYLON.Texture.PLANAR_MODE:
  41583. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41584. break;
  41585. case BABYLON.Texture.PROJECTION_MODE:
  41586. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41587. break;
  41588. case BABYLON.Texture.SKYBOX_MODE:
  41589. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41590. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  41591. break;
  41592. case BABYLON.Texture.SPHERICAL_MODE:
  41593. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41594. break;
  41595. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41596. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41597. break;
  41598. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41599. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41600. break;
  41601. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41602. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41603. break;
  41604. case BABYLON.Texture.CUBIC_MODE:
  41605. case BABYLON.Texture.INVCUBIC_MODE:
  41606. default:
  41607. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41608. break;
  41609. }
  41610. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41611. }
  41612. }
  41613. else {
  41614. defines.REFLECTION = false;
  41615. }
  41616. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41617. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41618. return false;
  41619. }
  41620. else {
  41621. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41622. }
  41623. }
  41624. else {
  41625. defines.EMISSIVE = false;
  41626. }
  41627. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41628. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41629. return false;
  41630. }
  41631. else {
  41632. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41633. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41634. }
  41635. }
  41636. else {
  41637. defines.LIGHTMAP = false;
  41638. }
  41639. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41640. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41641. return false;
  41642. }
  41643. else {
  41644. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41645. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41646. }
  41647. }
  41648. else {
  41649. defines.SPECULAR = false;
  41650. }
  41651. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41652. // Bump texure can not be not blocking.
  41653. if (!this._bumpTexture.isReady()) {
  41654. return false;
  41655. }
  41656. else {
  41657. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41658. defines.PARALLAX = this._useParallax;
  41659. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41660. }
  41661. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41662. }
  41663. else {
  41664. defines.BUMP = false;
  41665. }
  41666. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41667. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41668. return false;
  41669. }
  41670. else {
  41671. defines._needUVs = true;
  41672. defines.REFRACTION = true;
  41673. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41674. }
  41675. }
  41676. else {
  41677. defines.REFRACTION = false;
  41678. }
  41679. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41680. }
  41681. else {
  41682. defines.DIFFUSE = false;
  41683. defines.AMBIENT = false;
  41684. defines.OPACITY = false;
  41685. defines.REFLECTION = false;
  41686. defines.EMISSIVE = false;
  41687. defines.LIGHTMAP = false;
  41688. defines.BUMP = false;
  41689. defines.REFRACTION = false;
  41690. }
  41691. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41692. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41693. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41694. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41695. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41696. }
  41697. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41698. if (!this._imageProcessingConfiguration.isReady()) {
  41699. return false;
  41700. }
  41701. this._imageProcessingConfiguration.prepareDefines(defines);
  41702. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  41703. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  41704. }
  41705. if (defines._areFresnelDirty) {
  41706. if (StandardMaterial.FresnelEnabled) {
  41707. // Fresnel
  41708. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41709. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41710. this._reflectionFresnelParameters) {
  41711. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41712. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41713. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41714. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41715. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41716. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41717. defines._needNormals = true;
  41718. defines.FRESNEL = true;
  41719. }
  41720. }
  41721. else {
  41722. defines.FRESNEL = false;
  41723. }
  41724. }
  41725. // Misc.
  41726. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  41727. // Attribs
  41728. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  41729. // Values that need to be evaluated on every frame
  41730. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  41731. // Get correct effect
  41732. if (defines.isDirty) {
  41733. defines.markAsProcessed();
  41734. scene.resetCachedMaterial();
  41735. // Fallbacks
  41736. var fallbacks = new BABYLON.EffectFallbacks();
  41737. if (defines.REFLECTION) {
  41738. fallbacks.addFallback(0, "REFLECTION");
  41739. }
  41740. if (defines.SPECULAR) {
  41741. fallbacks.addFallback(0, "SPECULAR");
  41742. }
  41743. if (defines.BUMP) {
  41744. fallbacks.addFallback(0, "BUMP");
  41745. }
  41746. if (defines.PARALLAX) {
  41747. fallbacks.addFallback(1, "PARALLAX");
  41748. }
  41749. if (defines.PARALLAXOCCLUSION) {
  41750. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  41751. }
  41752. if (defines.SPECULAROVERALPHA) {
  41753. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  41754. }
  41755. if (defines.FOG) {
  41756. fallbacks.addFallback(1, "FOG");
  41757. }
  41758. if (defines.POINTSIZE) {
  41759. fallbacks.addFallback(0, "POINTSIZE");
  41760. }
  41761. if (defines.LOGARITHMICDEPTH) {
  41762. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  41763. }
  41764. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  41765. if (defines.SPECULARTERM) {
  41766. fallbacks.addFallback(0, "SPECULARTERM");
  41767. }
  41768. if (defines.DIFFUSEFRESNEL) {
  41769. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  41770. }
  41771. if (defines.OPACITYFRESNEL) {
  41772. fallbacks.addFallback(2, "OPACITYFRESNEL");
  41773. }
  41774. if (defines.REFLECTIONFRESNEL) {
  41775. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  41776. }
  41777. if (defines.EMISSIVEFRESNEL) {
  41778. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  41779. }
  41780. if (defines.FRESNEL) {
  41781. fallbacks.addFallback(4, "FRESNEL");
  41782. }
  41783. //Attributes
  41784. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41785. if (defines.NORMAL) {
  41786. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41787. }
  41788. if (defines.UV1) {
  41789. attribs.push(BABYLON.VertexBuffer.UVKind);
  41790. }
  41791. if (defines.UV2) {
  41792. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41793. }
  41794. if (defines.VERTEXCOLOR) {
  41795. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41796. }
  41797. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41798. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41799. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41800. var shaderName = "default";
  41801. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  41802. "vFogInfos", "vFogColor", "pointSize",
  41803. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41804. "mBones",
  41805. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  41806. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  41807. "vReflectionPosition", "vReflectionSize",
  41808. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  41809. ];
  41810. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  41811. var uniformBuffers = ["Material", "Scene"];
  41812. if (BABYLON.ImageProcessingConfiguration) {
  41813. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41814. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41815. }
  41816. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41817. uniformsNames: uniforms,
  41818. uniformBuffersNames: uniformBuffers,
  41819. samplers: samplers,
  41820. defines: defines,
  41821. maxSimultaneousLights: this._maxSimultaneousLights
  41822. });
  41823. if (this.customShaderNameResolve) {
  41824. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  41825. }
  41826. var join = defines.toString();
  41827. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  41828. attributes: attribs,
  41829. uniformsNames: uniforms,
  41830. uniformBuffersNames: uniformBuffers,
  41831. samplers: samplers,
  41832. defines: join,
  41833. fallbacks: fallbacks,
  41834. onCompiled: this.onCompiled,
  41835. onError: this.onError,
  41836. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41837. }, engine), defines);
  41838. this.buildUniformLayout();
  41839. }
  41840. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41841. return false;
  41842. }
  41843. defines._renderId = scene.getRenderId();
  41844. this._wasPreviouslyReady = true;
  41845. return true;
  41846. };
  41847. StandardMaterial.prototype.buildUniformLayout = function () {
  41848. // Order is important !
  41849. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  41850. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  41851. this._uniformBuffer.addUniform("opacityParts", 4);
  41852. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  41853. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  41854. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  41855. this._uniformBuffer.addUniform("refractionRightColor", 4);
  41856. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  41857. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  41858. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  41859. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  41860. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41861. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41862. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41863. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41864. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41865. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41866. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  41867. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41868. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  41869. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41870. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41871. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41872. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41873. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41874. this._uniformBuffer.addUniform("specularMatrix", 16);
  41875. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41876. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41877. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41878. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41879. this._uniformBuffer.addUniform("vSpecularColor", 4);
  41880. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41881. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  41882. this._uniformBuffer.addUniform("pointSize", 1);
  41883. this._uniformBuffer.create();
  41884. };
  41885. StandardMaterial.prototype.unbind = function () {
  41886. if (this._activeEffect) {
  41887. var needFlag = false;
  41888. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41889. this._activeEffect.setTexture("reflection2DSampler", null);
  41890. needFlag = true;
  41891. }
  41892. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41893. this._activeEffect.setTexture("refraction2DSampler", null);
  41894. needFlag = true;
  41895. }
  41896. if (needFlag) {
  41897. this._markAllSubMeshesAsTexturesDirty();
  41898. }
  41899. }
  41900. _super.prototype.unbind.call(this);
  41901. };
  41902. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41903. var scene = this.getScene();
  41904. var defines = subMesh._materialDefines;
  41905. if (!defines) {
  41906. return;
  41907. }
  41908. var effect = subMesh.effect;
  41909. if (!effect) {
  41910. return;
  41911. }
  41912. this._activeEffect = effect;
  41913. // Matrices
  41914. this.bindOnlyWorldMatrix(world);
  41915. // Normal Matrix
  41916. if (defines.OBJECTSPACE_NORMALMAP) {
  41917. world.toNormalMatrix(this._normalMatrix);
  41918. this.bindOnlyNormalMatrix(this._normalMatrix);
  41919. }
  41920. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41921. // Bones
  41922. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  41923. if (mustRebind) {
  41924. this._uniformBuffer.bindToEffect(effect, "Material");
  41925. this.bindViewProjection(effect);
  41926. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41927. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  41928. // Fresnel
  41929. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  41930. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  41931. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  41932. }
  41933. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  41934. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  41935. }
  41936. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  41937. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  41938. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  41939. }
  41940. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  41941. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  41942. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  41943. }
  41944. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  41945. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  41946. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  41947. }
  41948. }
  41949. // Textures
  41950. if (scene.texturesEnabled) {
  41951. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41952. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  41953. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  41954. if (this._diffuseTexture.hasAlpha) {
  41955. effect.setFloat("alphaCutOff", this.alphaCutOff);
  41956. }
  41957. }
  41958. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41959. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  41960. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41961. }
  41962. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41963. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41964. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41965. }
  41966. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41967. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  41968. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  41969. if (this._reflectionTexture.boundingBoxSize) {
  41970. var cubeTexture = this._reflectionTexture;
  41971. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41972. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41973. }
  41974. }
  41975. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41976. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41977. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41978. }
  41979. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41980. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41981. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41982. }
  41983. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41984. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  41985. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  41986. }
  41987. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  41988. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  41989. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41990. if (scene._mirroredCameraPosition) {
  41991. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41992. }
  41993. else {
  41994. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41995. }
  41996. }
  41997. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41998. var depth = 1.0;
  41999. if (!this._refractionTexture.isCube) {
  42000. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42001. if (this._refractionTexture.depth) {
  42002. depth = this._refractionTexture.depth;
  42003. }
  42004. }
  42005. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42006. }
  42007. }
  42008. // Point size
  42009. if (this.pointsCloud) {
  42010. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42011. }
  42012. if (defines.SPECULARTERM) {
  42013. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42014. }
  42015. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42016. // Diffuse
  42017. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42018. }
  42019. // Textures
  42020. if (scene.texturesEnabled) {
  42021. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42022. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42023. }
  42024. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42025. effect.setTexture("ambientSampler", this._ambientTexture);
  42026. }
  42027. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42028. effect.setTexture("opacitySampler", this._opacityTexture);
  42029. }
  42030. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42031. if (this._reflectionTexture.isCube) {
  42032. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42033. }
  42034. else {
  42035. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42036. }
  42037. }
  42038. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42039. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42040. }
  42041. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42042. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42043. }
  42044. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42045. effect.setTexture("specularSampler", this._specularTexture);
  42046. }
  42047. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42048. effect.setTexture("bumpSampler", this._bumpTexture);
  42049. }
  42050. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42051. var depth = 1.0;
  42052. if (this._refractionTexture.isCube) {
  42053. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42054. }
  42055. else {
  42056. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42057. }
  42058. }
  42059. }
  42060. // Clip plane
  42061. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42062. // Colors
  42063. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42064. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42065. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42066. }
  42067. if (mustRebind || !this.isFrozen) {
  42068. // Lights
  42069. if (scene.lightsEnabled && !this._disableLighting) {
  42070. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42071. }
  42072. // View
  42073. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42074. this.bindView(effect);
  42075. }
  42076. // Fog
  42077. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42078. // Morph targets
  42079. if (defines.NUM_MORPH_INFLUENCERS) {
  42080. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42081. }
  42082. // Log. depth
  42083. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42084. // image processing
  42085. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42086. this._imageProcessingConfiguration.bind(this._activeEffect);
  42087. }
  42088. }
  42089. this._uniformBuffer.update();
  42090. this._afterBind(mesh, this._activeEffect);
  42091. };
  42092. StandardMaterial.prototype.getAnimatables = function () {
  42093. var results = [];
  42094. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42095. results.push(this._diffuseTexture);
  42096. }
  42097. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42098. results.push(this._ambientTexture);
  42099. }
  42100. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42101. results.push(this._opacityTexture);
  42102. }
  42103. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42104. results.push(this._reflectionTexture);
  42105. }
  42106. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42107. results.push(this._emissiveTexture);
  42108. }
  42109. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42110. results.push(this._specularTexture);
  42111. }
  42112. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42113. results.push(this._bumpTexture);
  42114. }
  42115. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42116. results.push(this._lightmapTexture);
  42117. }
  42118. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42119. results.push(this._refractionTexture);
  42120. }
  42121. return results;
  42122. };
  42123. StandardMaterial.prototype.getActiveTextures = function () {
  42124. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42125. if (this._diffuseTexture) {
  42126. activeTextures.push(this._diffuseTexture);
  42127. }
  42128. if (this._ambientTexture) {
  42129. activeTextures.push(this._ambientTexture);
  42130. }
  42131. if (this._opacityTexture) {
  42132. activeTextures.push(this._opacityTexture);
  42133. }
  42134. if (this._reflectionTexture) {
  42135. activeTextures.push(this._reflectionTexture);
  42136. }
  42137. if (this._emissiveTexture) {
  42138. activeTextures.push(this._emissiveTexture);
  42139. }
  42140. if (this._specularTexture) {
  42141. activeTextures.push(this._specularTexture);
  42142. }
  42143. if (this._bumpTexture) {
  42144. activeTextures.push(this._bumpTexture);
  42145. }
  42146. if (this._lightmapTexture) {
  42147. activeTextures.push(this._lightmapTexture);
  42148. }
  42149. if (this._refractionTexture) {
  42150. activeTextures.push(this._refractionTexture);
  42151. }
  42152. return activeTextures;
  42153. };
  42154. StandardMaterial.prototype.hasTexture = function (texture) {
  42155. if (_super.prototype.hasTexture.call(this, texture)) {
  42156. return true;
  42157. }
  42158. if (this._diffuseTexture === texture) {
  42159. return true;
  42160. }
  42161. if (this._ambientTexture === texture) {
  42162. return true;
  42163. }
  42164. if (this._opacityTexture === texture) {
  42165. return true;
  42166. }
  42167. if (this._reflectionTexture === texture) {
  42168. return true;
  42169. }
  42170. if (this._emissiveTexture === texture) {
  42171. return true;
  42172. }
  42173. if (this._specularTexture === texture) {
  42174. return true;
  42175. }
  42176. if (this._bumpTexture === texture) {
  42177. return true;
  42178. }
  42179. if (this._lightmapTexture === texture) {
  42180. return true;
  42181. }
  42182. if (this._refractionTexture === texture) {
  42183. return true;
  42184. }
  42185. return false;
  42186. };
  42187. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42188. if (forceDisposeTextures) {
  42189. if (this._diffuseTexture) {
  42190. this._diffuseTexture.dispose();
  42191. }
  42192. if (this._ambientTexture) {
  42193. this._ambientTexture.dispose();
  42194. }
  42195. if (this._opacityTexture) {
  42196. this._opacityTexture.dispose();
  42197. }
  42198. if (this._reflectionTexture) {
  42199. this._reflectionTexture.dispose();
  42200. }
  42201. if (this._emissiveTexture) {
  42202. this._emissiveTexture.dispose();
  42203. }
  42204. if (this._specularTexture) {
  42205. this._specularTexture.dispose();
  42206. }
  42207. if (this._bumpTexture) {
  42208. this._bumpTexture.dispose();
  42209. }
  42210. if (this._lightmapTexture) {
  42211. this._lightmapTexture.dispose();
  42212. }
  42213. if (this._refractionTexture) {
  42214. this._refractionTexture.dispose();
  42215. }
  42216. }
  42217. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42218. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42219. }
  42220. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42221. };
  42222. StandardMaterial.prototype.clone = function (name) {
  42223. var _this = this;
  42224. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42225. result.name = name;
  42226. result.id = name;
  42227. return result;
  42228. };
  42229. StandardMaterial.prototype.serialize = function () {
  42230. return BABYLON.SerializationHelper.Serialize(this);
  42231. };
  42232. // Statics
  42233. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42234. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42235. };
  42236. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42237. get: function () {
  42238. return StandardMaterial._DiffuseTextureEnabled;
  42239. },
  42240. set: function (value) {
  42241. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42242. return;
  42243. }
  42244. StandardMaterial._DiffuseTextureEnabled = value;
  42245. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42246. },
  42247. enumerable: true,
  42248. configurable: true
  42249. });
  42250. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42251. get: function () {
  42252. return StandardMaterial._AmbientTextureEnabled;
  42253. },
  42254. set: function (value) {
  42255. if (StandardMaterial._AmbientTextureEnabled === value) {
  42256. return;
  42257. }
  42258. StandardMaterial._AmbientTextureEnabled = value;
  42259. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42260. },
  42261. enumerable: true,
  42262. configurable: true
  42263. });
  42264. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42265. get: function () {
  42266. return StandardMaterial._OpacityTextureEnabled;
  42267. },
  42268. set: function (value) {
  42269. if (StandardMaterial._OpacityTextureEnabled === value) {
  42270. return;
  42271. }
  42272. StandardMaterial._OpacityTextureEnabled = value;
  42273. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42274. },
  42275. enumerable: true,
  42276. configurable: true
  42277. });
  42278. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42279. get: function () {
  42280. return StandardMaterial._ReflectionTextureEnabled;
  42281. },
  42282. set: function (value) {
  42283. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42284. return;
  42285. }
  42286. StandardMaterial._ReflectionTextureEnabled = value;
  42287. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42288. },
  42289. enumerable: true,
  42290. configurable: true
  42291. });
  42292. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42293. get: function () {
  42294. return StandardMaterial._EmissiveTextureEnabled;
  42295. },
  42296. set: function (value) {
  42297. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42298. return;
  42299. }
  42300. StandardMaterial._EmissiveTextureEnabled = value;
  42301. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42302. },
  42303. enumerable: true,
  42304. configurable: true
  42305. });
  42306. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42307. get: function () {
  42308. return StandardMaterial._SpecularTextureEnabled;
  42309. },
  42310. set: function (value) {
  42311. if (StandardMaterial._SpecularTextureEnabled === value) {
  42312. return;
  42313. }
  42314. StandardMaterial._SpecularTextureEnabled = value;
  42315. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42316. },
  42317. enumerable: true,
  42318. configurable: true
  42319. });
  42320. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42321. get: function () {
  42322. return StandardMaterial._BumpTextureEnabled;
  42323. },
  42324. set: function (value) {
  42325. if (StandardMaterial._BumpTextureEnabled === value) {
  42326. return;
  42327. }
  42328. StandardMaterial._BumpTextureEnabled = value;
  42329. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42330. },
  42331. enumerable: true,
  42332. configurable: true
  42333. });
  42334. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42335. get: function () {
  42336. return StandardMaterial._LightmapTextureEnabled;
  42337. },
  42338. set: function (value) {
  42339. if (StandardMaterial._LightmapTextureEnabled === value) {
  42340. return;
  42341. }
  42342. StandardMaterial._LightmapTextureEnabled = value;
  42343. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42344. },
  42345. enumerable: true,
  42346. configurable: true
  42347. });
  42348. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42349. get: function () {
  42350. return StandardMaterial._RefractionTextureEnabled;
  42351. },
  42352. set: function (value) {
  42353. if (StandardMaterial._RefractionTextureEnabled === value) {
  42354. return;
  42355. }
  42356. StandardMaterial._RefractionTextureEnabled = value;
  42357. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42358. },
  42359. enumerable: true,
  42360. configurable: true
  42361. });
  42362. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42363. get: function () {
  42364. return StandardMaterial._ColorGradingTextureEnabled;
  42365. },
  42366. set: function (value) {
  42367. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42368. return;
  42369. }
  42370. StandardMaterial._ColorGradingTextureEnabled = value;
  42371. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42372. },
  42373. enumerable: true,
  42374. configurable: true
  42375. });
  42376. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42377. get: function () {
  42378. return StandardMaterial._FresnelEnabled;
  42379. },
  42380. set: function (value) {
  42381. if (StandardMaterial._FresnelEnabled === value) {
  42382. return;
  42383. }
  42384. StandardMaterial._FresnelEnabled = value;
  42385. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42386. },
  42387. enumerable: true,
  42388. configurable: true
  42389. });
  42390. // Flags used to enable or disable a type of texture for all Standard Materials
  42391. StandardMaterial._DiffuseTextureEnabled = true;
  42392. StandardMaterial._AmbientTextureEnabled = true;
  42393. StandardMaterial._OpacityTextureEnabled = true;
  42394. StandardMaterial._ReflectionTextureEnabled = true;
  42395. StandardMaterial._EmissiveTextureEnabled = true;
  42396. StandardMaterial._SpecularTextureEnabled = true;
  42397. StandardMaterial._BumpTextureEnabled = true;
  42398. StandardMaterial._LightmapTextureEnabled = true;
  42399. StandardMaterial._RefractionTextureEnabled = true;
  42400. StandardMaterial._ColorGradingTextureEnabled = true;
  42401. StandardMaterial._FresnelEnabled = true;
  42402. __decorate([
  42403. BABYLON.serializeAsTexture("diffuseTexture")
  42404. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42405. __decorate([
  42406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42407. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42408. __decorate([
  42409. BABYLON.serializeAsTexture("ambientTexture")
  42410. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42411. __decorate([
  42412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42413. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42414. __decorate([
  42415. BABYLON.serializeAsTexture("opacityTexture")
  42416. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42417. __decorate([
  42418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42419. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42420. __decorate([
  42421. BABYLON.serializeAsTexture("reflectionTexture")
  42422. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42423. __decorate([
  42424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42425. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42426. __decorate([
  42427. BABYLON.serializeAsTexture("emissiveTexture")
  42428. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42429. __decorate([
  42430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42431. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42432. __decorate([
  42433. BABYLON.serializeAsTexture("specularTexture")
  42434. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42435. __decorate([
  42436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42437. ], StandardMaterial.prototype, "specularTexture", void 0);
  42438. __decorate([
  42439. BABYLON.serializeAsTexture("bumpTexture")
  42440. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42441. __decorate([
  42442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42443. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42444. __decorate([
  42445. BABYLON.serializeAsTexture("lightmapTexture")
  42446. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42447. __decorate([
  42448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42449. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42450. __decorate([
  42451. BABYLON.serializeAsTexture("refractionTexture")
  42452. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42453. __decorate([
  42454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42455. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42456. __decorate([
  42457. BABYLON.serializeAsColor3("ambient")
  42458. ], StandardMaterial.prototype, "ambientColor", void 0);
  42459. __decorate([
  42460. BABYLON.serializeAsColor3("diffuse")
  42461. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42462. __decorate([
  42463. BABYLON.serializeAsColor3("specular")
  42464. ], StandardMaterial.prototype, "specularColor", void 0);
  42465. __decorate([
  42466. BABYLON.serializeAsColor3("emissive")
  42467. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42468. __decorate([
  42469. BABYLON.serialize()
  42470. ], StandardMaterial.prototype, "specularPower", void 0);
  42471. __decorate([
  42472. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42473. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42474. __decorate([
  42475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42476. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42477. __decorate([
  42478. BABYLON.serialize("useEmissiveAsIllumination")
  42479. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42480. __decorate([
  42481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42482. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42483. __decorate([
  42484. BABYLON.serialize("linkEmissiveWithDiffuse")
  42485. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42486. __decorate([
  42487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42488. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42489. __decorate([
  42490. BABYLON.serialize("useSpecularOverAlpha")
  42491. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42492. __decorate([
  42493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42494. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42495. __decorate([
  42496. BABYLON.serialize("useReflectionOverAlpha")
  42497. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42498. __decorate([
  42499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42500. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42501. __decorate([
  42502. BABYLON.serialize("disableLighting")
  42503. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42504. __decorate([
  42505. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42506. ], StandardMaterial.prototype, "disableLighting", void 0);
  42507. __decorate([
  42508. BABYLON.serialize("useObjectSpaceNormalMap")
  42509. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42510. __decorate([
  42511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42512. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42513. __decorate([
  42514. BABYLON.serialize("useParallax")
  42515. ], StandardMaterial.prototype, "_useParallax", void 0);
  42516. __decorate([
  42517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42518. ], StandardMaterial.prototype, "useParallax", void 0);
  42519. __decorate([
  42520. BABYLON.serialize("useParallaxOcclusion")
  42521. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42522. __decorate([
  42523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42524. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42525. __decorate([
  42526. BABYLON.serialize()
  42527. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42528. __decorate([
  42529. BABYLON.serialize("roughness")
  42530. ], StandardMaterial.prototype, "_roughness", void 0);
  42531. __decorate([
  42532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42533. ], StandardMaterial.prototype, "roughness", void 0);
  42534. __decorate([
  42535. BABYLON.serialize()
  42536. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42537. __decorate([
  42538. BABYLON.serialize()
  42539. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42540. __decorate([
  42541. BABYLON.serialize()
  42542. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42543. __decorate([
  42544. BABYLON.serialize("useLightmapAsShadowmap")
  42545. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42546. __decorate([
  42547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42548. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42549. __decorate([
  42550. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42551. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42552. __decorate([
  42553. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42554. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42555. __decorate([
  42556. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42557. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42558. __decorate([
  42559. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42560. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42561. __decorate([
  42562. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42563. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42564. __decorate([
  42565. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42566. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42567. __decorate([
  42568. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42569. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42570. __decorate([
  42571. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42572. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42573. __decorate([
  42574. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42575. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42576. __decorate([
  42577. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42578. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42579. __decorate([
  42580. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42581. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42582. __decorate([
  42583. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42584. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42585. __decorate([
  42586. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42587. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42588. __decorate([
  42589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42590. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42591. __decorate([
  42592. BABYLON.serialize("maxSimultaneousLights")
  42593. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42594. __decorate([
  42595. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42596. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42597. __decorate([
  42598. BABYLON.serialize("invertNormalMapX")
  42599. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42600. __decorate([
  42601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42602. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42603. __decorate([
  42604. BABYLON.serialize("invertNormalMapY")
  42605. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42606. __decorate([
  42607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42608. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42609. __decorate([
  42610. BABYLON.serialize("twoSidedLighting")
  42611. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42612. __decorate([
  42613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42614. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42615. __decorate([
  42616. BABYLON.serialize()
  42617. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42618. return StandardMaterial;
  42619. }(BABYLON.PushMaterial));
  42620. BABYLON.StandardMaterial = StandardMaterial;
  42621. })(BABYLON || (BABYLON = {}));
  42622. //# sourceMappingURL=babylon.standardMaterial.js.map
  42623. var BABYLON;
  42624. (function (BABYLON) {
  42625. /**
  42626. * Class representing spherical polynomial coefficients to the 3rd degree
  42627. */
  42628. var SphericalPolynomial = /** @class */ (function () {
  42629. function SphericalPolynomial() {
  42630. /**
  42631. * The x coefficients of the spherical polynomial
  42632. */
  42633. this.x = BABYLON.Vector3.Zero();
  42634. /**
  42635. * The y coefficients of the spherical polynomial
  42636. */
  42637. this.y = BABYLON.Vector3.Zero();
  42638. /**
  42639. * The z coefficients of the spherical polynomial
  42640. */
  42641. this.z = BABYLON.Vector3.Zero();
  42642. /**
  42643. * The xx coefficients of the spherical polynomial
  42644. */
  42645. this.xx = BABYLON.Vector3.Zero();
  42646. /**
  42647. * The yy coefficients of the spherical polynomial
  42648. */
  42649. this.yy = BABYLON.Vector3.Zero();
  42650. /**
  42651. * The zz coefficients of the spherical polynomial
  42652. */
  42653. this.zz = BABYLON.Vector3.Zero();
  42654. /**
  42655. * The xy coefficients of the spherical polynomial
  42656. */
  42657. this.xy = BABYLON.Vector3.Zero();
  42658. /**
  42659. * The yz coefficients of the spherical polynomial
  42660. */
  42661. this.yz = BABYLON.Vector3.Zero();
  42662. /**
  42663. * The zx coefficients of the spherical polynomial
  42664. */
  42665. this.zx = BABYLON.Vector3.Zero();
  42666. }
  42667. /**
  42668. * Adds an ambient color to the spherical polynomial
  42669. * @param color the color to add
  42670. */
  42671. SphericalPolynomial.prototype.addAmbient = function (color) {
  42672. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42673. this.xx = this.xx.add(colorVector);
  42674. this.yy = this.yy.add(colorVector);
  42675. this.zz = this.zz.add(colorVector);
  42676. };
  42677. /**
  42678. * Scales the spherical polynomial by the given amount
  42679. * @param scale the amount to scale
  42680. */
  42681. SphericalPolynomial.prototype.scale = function (scale) {
  42682. this.x = this.x.scale(scale);
  42683. this.y = this.y.scale(scale);
  42684. this.z = this.z.scale(scale);
  42685. this.xx = this.xx.scale(scale);
  42686. this.yy = this.yy.scale(scale);
  42687. this.zz = this.zz.scale(scale);
  42688. this.yz = this.yz.scale(scale);
  42689. this.zx = this.zx.scale(scale);
  42690. this.xy = this.xy.scale(scale);
  42691. };
  42692. /**
  42693. * Gets the spherical polynomial from harmonics
  42694. * @param harmonics the spherical harmonics
  42695. * @returns the spherical polynomial
  42696. */
  42697. SphericalPolynomial.FromHarmonics = function (harmonics) {
  42698. var result = new SphericalPolynomial();
  42699. result.x = harmonics.l11.scale(1.02333);
  42700. result.y = harmonics.l1_1.scale(1.02333);
  42701. result.z = harmonics.l10.scale(1.02333);
  42702. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  42703. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  42704. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  42705. result.yz = harmonics.l2_1.scale(0.858086);
  42706. result.zx = harmonics.l21.scale(0.858086);
  42707. result.xy = harmonics.l2_2.scale(0.858086);
  42708. result.scale(1.0 / Math.PI);
  42709. return result;
  42710. };
  42711. /**
  42712. * Constructs a spherical polynomial from an array.
  42713. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  42714. * @returns the spherical polynomial
  42715. */
  42716. SphericalPolynomial.FromArray = function (data) {
  42717. var sp = new SphericalPolynomial();
  42718. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  42719. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  42720. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  42721. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  42722. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  42723. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  42724. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  42725. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  42726. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  42727. return sp;
  42728. };
  42729. return SphericalPolynomial;
  42730. }());
  42731. BABYLON.SphericalPolynomial = SphericalPolynomial;
  42732. /**
  42733. * Class representing spherical harmonics coefficients to the 3rd degree
  42734. */
  42735. var SphericalHarmonics = /** @class */ (function () {
  42736. function SphericalHarmonics() {
  42737. /**
  42738. * The l0,0 coefficients of the spherical harmonics
  42739. */
  42740. this.l00 = BABYLON.Vector3.Zero();
  42741. /**
  42742. * The l1,-1 coefficients of the spherical harmonics
  42743. */
  42744. this.l1_1 = BABYLON.Vector3.Zero();
  42745. /**
  42746. * The l1,0 coefficients of the spherical harmonics
  42747. */
  42748. this.l10 = BABYLON.Vector3.Zero();
  42749. /**
  42750. * The l1,1 coefficients of the spherical harmonics
  42751. */
  42752. this.l11 = BABYLON.Vector3.Zero();
  42753. /**
  42754. * The l2,-2 coefficients of the spherical harmonics
  42755. */
  42756. this.l2_2 = BABYLON.Vector3.Zero();
  42757. /**
  42758. * The l2,-1 coefficients of the spherical harmonics
  42759. */
  42760. this.l2_1 = BABYLON.Vector3.Zero();
  42761. /**
  42762. * The l2,0 coefficients of the spherical harmonics
  42763. */
  42764. this.l20 = BABYLON.Vector3.Zero();
  42765. /**
  42766. * The l2,1 coefficients of the spherical harmonics
  42767. */
  42768. this.l21 = BABYLON.Vector3.Zero();
  42769. /**
  42770. * The l2,2 coefficients of the spherical harmonics
  42771. */
  42772. this.lL22 = BABYLON.Vector3.Zero();
  42773. }
  42774. /**
  42775. * Adds a light to the spherical harmonics
  42776. * @param direction the direction of the light
  42777. * @param color the color of the light
  42778. * @param deltaSolidAngle the delta solid angle of the light
  42779. */
  42780. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  42781. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42782. var c = colorVector.scale(deltaSolidAngle);
  42783. this.l00 = this.l00.add(c.scale(0.282095));
  42784. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  42785. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  42786. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  42787. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  42788. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  42789. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  42790. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  42791. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  42792. };
  42793. /**
  42794. * Scales the spherical harmonics by the given amount
  42795. * @param scale the amount to scale
  42796. */
  42797. SphericalHarmonics.prototype.scale = function (scale) {
  42798. this.l00 = this.l00.scale(scale);
  42799. this.l1_1 = this.l1_1.scale(scale);
  42800. this.l10 = this.l10.scale(scale);
  42801. this.l11 = this.l11.scale(scale);
  42802. this.l2_2 = this.l2_2.scale(scale);
  42803. this.l2_1 = this.l2_1.scale(scale);
  42804. this.l20 = this.l20.scale(scale);
  42805. this.l21 = this.l21.scale(scale);
  42806. this.lL22 = this.lL22.scale(scale);
  42807. };
  42808. /**
  42809. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  42810. *
  42811. * ```
  42812. * E_lm = A_l * L_lm
  42813. * ```
  42814. *
  42815. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  42816. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  42817. * the scaling factors are given in equation 9.
  42818. */
  42819. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  42820. // Constant (Band 0)
  42821. this.l00 = this.l00.scale(3.141593);
  42822. // Linear (Band 1)
  42823. this.l1_1 = this.l1_1.scale(2.094395);
  42824. this.l10 = this.l10.scale(2.094395);
  42825. this.l11 = this.l11.scale(2.094395);
  42826. // Quadratic (Band 2)
  42827. this.l2_2 = this.l2_2.scale(0.785398);
  42828. this.l2_1 = this.l2_1.scale(0.785398);
  42829. this.l20 = this.l20.scale(0.785398);
  42830. this.l21 = this.l21.scale(0.785398);
  42831. this.lL22 = this.lL22.scale(0.785398);
  42832. };
  42833. /**
  42834. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  42835. *
  42836. * ```
  42837. * L = (1/pi) * E * rho
  42838. * ```
  42839. *
  42840. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  42841. */
  42842. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  42843. this.scale(1.0 / Math.PI);
  42844. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  42845. // (The pixel shader must apply albedo after texture fetches, etc).
  42846. };
  42847. /**
  42848. * Gets the spherical harmonics from polynomial
  42849. * @param polynomial the spherical polynomial
  42850. * @returns the spherical harmonics
  42851. */
  42852. SphericalHarmonics.FromPolynomial = function (polynomial) {
  42853. var result = new SphericalHarmonics();
  42854. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  42855. result.l1_1 = polynomial.y.scale(0.977204);
  42856. result.l10 = polynomial.z.scale(0.977204);
  42857. result.l11 = polynomial.x.scale(0.977204);
  42858. result.l2_2 = polynomial.xy.scale(1.16538);
  42859. result.l2_1 = polynomial.yz.scale(1.16538);
  42860. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  42861. result.l21 = polynomial.zx.scale(1.16538);
  42862. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  42863. result.scale(Math.PI);
  42864. return result;
  42865. };
  42866. /**
  42867. * Constructs a spherical harmonics from an array.
  42868. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  42869. * @returns the spherical harmonics
  42870. */
  42871. SphericalHarmonics.FromArray = function (data) {
  42872. var sh = new SphericalHarmonics();
  42873. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  42874. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  42875. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  42876. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  42877. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  42878. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  42879. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  42880. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  42881. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  42882. return sh;
  42883. };
  42884. return SphericalHarmonics;
  42885. }());
  42886. BABYLON.SphericalHarmonics = SphericalHarmonics;
  42887. })(BABYLON || (BABYLON = {}));
  42888. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  42889. var BABYLON;
  42890. (function (BABYLON) {
  42891. var FileFaceOrientation = /** @class */ (function () {
  42892. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  42893. this.name = name;
  42894. this.worldAxisForNormal = worldAxisForNormal;
  42895. this.worldAxisForFileX = worldAxisForFileX;
  42896. this.worldAxisForFileY = worldAxisForFileY;
  42897. }
  42898. return FileFaceOrientation;
  42899. }());
  42900. ;
  42901. /**
  42902. * Helper class dealing with the extraction of spherical polynomial dataArray
  42903. * from a cube map.
  42904. */
  42905. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  42906. function CubeMapToSphericalPolynomialTools() {
  42907. }
  42908. /**
  42909. * Converts a texture to the according Spherical Polynomial data.
  42910. * This extracts the first 3 orders only as they are the only one used in the lighting.
  42911. *
  42912. * @param texture The texture to extract the information from.
  42913. * @return The Spherical Polynomial data.
  42914. */
  42915. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  42916. if (!texture.isCube) {
  42917. // Only supports cube Textures currently.
  42918. return null;
  42919. }
  42920. var size = texture.getSize().width;
  42921. var right = texture.readPixels(0);
  42922. var left = texture.readPixels(1);
  42923. var up;
  42924. var down;
  42925. if (texture.isRenderTarget) {
  42926. up = texture.readPixels(3);
  42927. down = texture.readPixels(2);
  42928. }
  42929. else {
  42930. up = texture.readPixels(2);
  42931. down = texture.readPixels(3);
  42932. }
  42933. var front = texture.readPixels(4);
  42934. var back = texture.readPixels(5);
  42935. var gammaSpace = texture.gammaSpace;
  42936. // Always read as RGBA.
  42937. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  42938. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  42939. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  42940. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  42941. }
  42942. var cubeInfo = {
  42943. size: size,
  42944. right: right,
  42945. left: left,
  42946. up: up,
  42947. down: down,
  42948. front: front,
  42949. back: back,
  42950. format: format,
  42951. type: type,
  42952. gammaSpace: gammaSpace,
  42953. };
  42954. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  42955. };
  42956. /**
  42957. * Converts a cubemap to the according Spherical Polynomial data.
  42958. * This extracts the first 3 orders only as they are the only one used in the lighting.
  42959. *
  42960. * @param cubeInfo The Cube map to extract the information from.
  42961. * @return The Spherical Polynomial data.
  42962. */
  42963. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  42964. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  42965. var totalSolidAngle = 0.0;
  42966. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  42967. var du = 2.0 / cubeInfo.size;
  42968. var dv = du;
  42969. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  42970. var minUV = du * 0.5 - 1.0;
  42971. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  42972. var fileFace = this.FileFaces[faceIndex];
  42973. var dataArray = cubeInfo[fileFace.name];
  42974. var v = minUV;
  42975. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  42976. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  42977. // Because SP is still linear, so summation is fine in that basis.
  42978. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  42979. for (var y = 0; y < cubeInfo.size; y++) {
  42980. var u = minUV;
  42981. for (var x = 0; x < cubeInfo.size; x++) {
  42982. // World direction (not normalised)
  42983. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  42984. worldDirection.normalize();
  42985. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  42986. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  42987. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  42988. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  42989. // Handle Integer types.
  42990. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  42991. r /= 255;
  42992. g /= 255;
  42993. b /= 255;
  42994. }
  42995. // Handle Gamma space textures.
  42996. if (cubeInfo.gammaSpace) {
  42997. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  42998. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  42999. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43000. }
  43001. var color = new BABYLON.Color3(r, g, b);
  43002. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43003. totalSolidAngle += deltaSolidAngle;
  43004. u += du;
  43005. }
  43006. v += dv;
  43007. }
  43008. }
  43009. // Solid angle for entire sphere is 4*pi
  43010. var sphereSolidAngle = 4.0 * Math.PI;
  43011. // Adjust the solid angle to allow for how many faces we processed.
  43012. var facesProcessed = 6.0;
  43013. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43014. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43015. // This is needed because the numerical integration over the cube uses a
  43016. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43017. // and also to compensate for accumulative error due to float precision in the summation.
  43018. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43019. sphericalHarmonics.scale(correctionFactor);
  43020. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43021. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43022. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43023. };
  43024. CubeMapToSphericalPolynomialTools.FileFaces = [
  43025. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43026. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43027. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43028. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43029. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43030. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43031. ];
  43032. return CubeMapToSphericalPolynomialTools;
  43033. }());
  43034. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43035. })(BABYLON || (BABYLON = {}));
  43036. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43037. var BABYLON;
  43038. (function (BABYLON) {
  43039. /**
  43040. * Manages the defines for the PBR Material.
  43041. * @hiddenChildren
  43042. */
  43043. var PBRMaterialDefines = /** @class */ (function (_super) {
  43044. __extends(PBRMaterialDefines, _super);
  43045. /**
  43046. * Initializes the PBR Material defines.
  43047. */
  43048. function PBRMaterialDefines() {
  43049. var _this = _super.call(this) || this;
  43050. _this.PBR = true;
  43051. _this.MAINUV1 = false;
  43052. _this.MAINUV2 = false;
  43053. _this.UV1 = false;
  43054. _this.UV2 = false;
  43055. _this.ALBEDO = false;
  43056. _this.ALBEDODIRECTUV = 0;
  43057. _this.VERTEXCOLOR = false;
  43058. _this.AMBIENT = false;
  43059. _this.AMBIENTDIRECTUV = 0;
  43060. _this.AMBIENTINGRAYSCALE = false;
  43061. _this.OPACITY = false;
  43062. _this.VERTEXALPHA = false;
  43063. _this.OPACITYDIRECTUV = 0;
  43064. _this.OPACITYRGB = false;
  43065. _this.ALPHATEST = false;
  43066. _this.DEPTHPREPASS = false;
  43067. _this.ALPHABLEND = false;
  43068. _this.ALPHAFROMALBEDO = false;
  43069. _this.ALPHATESTVALUE = "0.5";
  43070. _this.SPECULAROVERALPHA = false;
  43071. _this.RADIANCEOVERALPHA = false;
  43072. _this.ALPHAFRESNEL = false;
  43073. _this.LINEARALPHAFRESNEL = false;
  43074. _this.PREMULTIPLYALPHA = false;
  43075. _this.EMISSIVE = false;
  43076. _this.EMISSIVEDIRECTUV = 0;
  43077. _this.REFLECTIVITY = false;
  43078. _this.REFLECTIVITYDIRECTUV = 0;
  43079. _this.SPECULARTERM = false;
  43080. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43081. _this.MICROSURFACEAUTOMATIC = false;
  43082. _this.LODBASEDMICROSFURACE = false;
  43083. _this.MICROSURFACEMAP = false;
  43084. _this.MICROSURFACEMAPDIRECTUV = 0;
  43085. _this.METALLICWORKFLOW = false;
  43086. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43087. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43088. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43089. _this.AOSTOREINMETALMAPRED = false;
  43090. _this.ENVIRONMENTBRDF = false;
  43091. _this.NORMAL = false;
  43092. _this.TANGENT = false;
  43093. _this.BUMP = false;
  43094. _this.BUMPDIRECTUV = 0;
  43095. _this.OBJECTSPACE_NORMALMAP = false;
  43096. _this.PARALLAX = false;
  43097. _this.PARALLAXOCCLUSION = false;
  43098. _this.NORMALXYSCALE = true;
  43099. _this.LIGHTMAP = false;
  43100. _this.LIGHTMAPDIRECTUV = 0;
  43101. _this.USELIGHTMAPASSHADOWMAP = false;
  43102. _this.GAMMALIGHTMAP = false;
  43103. _this.REFLECTION = false;
  43104. _this.REFLECTIONMAP_3D = false;
  43105. _this.REFLECTIONMAP_SPHERICAL = false;
  43106. _this.REFLECTIONMAP_PLANAR = false;
  43107. _this.REFLECTIONMAP_CUBIC = false;
  43108. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43109. _this.REFLECTIONMAP_PROJECTION = false;
  43110. _this.REFLECTIONMAP_SKYBOX = false;
  43111. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43112. _this.REFLECTIONMAP_EXPLICIT = false;
  43113. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43114. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43115. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43116. _this.INVERTCUBICMAP = false;
  43117. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43118. _this.USESPHERICALINVERTEX = false;
  43119. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43120. _this.LODINREFLECTIONALPHA = false;
  43121. _this.GAMMAREFLECTION = false;
  43122. _this.RGBDREFLECTION = false;
  43123. _this.RADIANCEOCCLUSION = false;
  43124. _this.HORIZONOCCLUSION = false;
  43125. _this.REFRACTION = false;
  43126. _this.REFRACTIONMAP_3D = false;
  43127. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43128. _this.LODINREFRACTIONALPHA = false;
  43129. _this.GAMMAREFRACTION = false;
  43130. _this.RGBDREFRACTION = false;
  43131. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43132. _this.INSTANCES = false;
  43133. _this.NUM_BONE_INFLUENCERS = 0;
  43134. _this.BonesPerMesh = 0;
  43135. _this.NONUNIFORMSCALING = false;
  43136. _this.MORPHTARGETS = false;
  43137. _this.MORPHTARGETS_NORMAL = false;
  43138. _this.MORPHTARGETS_TANGENT = false;
  43139. _this.NUM_MORPH_INFLUENCERS = 0;
  43140. _this.IMAGEPROCESSING = false;
  43141. _this.VIGNETTE = false;
  43142. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43143. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43144. _this.TONEMAPPING = false;
  43145. _this.TONEMAPPING_ACES = false;
  43146. _this.CONTRAST = false;
  43147. _this.COLORCURVES = false;
  43148. _this.COLORGRADING = false;
  43149. _this.COLORGRADING3D = false;
  43150. _this.SAMPLER3DGREENDEPTH = false;
  43151. _this.SAMPLER3DBGRMAP = false;
  43152. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43153. _this.EXPOSURE = false;
  43154. _this.USEPHYSICALLIGHTFALLOFF = false;
  43155. _this.USEGLTFLIGHTFALLOFF = false;
  43156. _this.TWOSIDEDLIGHTING = false;
  43157. _this.SHADOWFLOAT = false;
  43158. _this.CLIPPLANE = false;
  43159. _this.CLIPPLANE2 = false;
  43160. _this.CLIPPLANE3 = false;
  43161. _this.CLIPPLANE4 = false;
  43162. _this.POINTSIZE = false;
  43163. _this.FOG = false;
  43164. _this.LOGARITHMICDEPTH = false;
  43165. _this.FORCENORMALFORWARD = false;
  43166. _this.SPECULARAA = false;
  43167. _this.UNLIT = false;
  43168. _this.rebuild();
  43169. return _this;
  43170. }
  43171. /**
  43172. * Resets the PBR Material defines.
  43173. */
  43174. PBRMaterialDefines.prototype.reset = function () {
  43175. _super.prototype.reset.call(this);
  43176. this.ALPHATESTVALUE = "0.5";
  43177. this.PBR = true;
  43178. };
  43179. return PBRMaterialDefines;
  43180. }(BABYLON.MaterialDefines));
  43181. /**
  43182. * The Physically based material base class of BJS.
  43183. *
  43184. * This offers the main features of a standard PBR material.
  43185. * For more information, please refer to the documentation :
  43186. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43187. */
  43188. var PBRBaseMaterial = /** @class */ (function (_super) {
  43189. __extends(PBRBaseMaterial, _super);
  43190. /**
  43191. * Instantiates a new PBRMaterial instance.
  43192. *
  43193. * @param name The material name
  43194. * @param scene The scene the material will be use in.
  43195. */
  43196. function PBRBaseMaterial(name, scene) {
  43197. var _this = _super.call(this, name, scene) || this;
  43198. /**
  43199. * Intensity of the direct lights e.g. the four lights available in your scene.
  43200. * This impacts both the direct diffuse and specular highlights.
  43201. */
  43202. _this._directIntensity = 1.0;
  43203. /**
  43204. * Intensity of the emissive part of the material.
  43205. * This helps controlling the emissive effect without modifying the emissive color.
  43206. */
  43207. _this._emissiveIntensity = 1.0;
  43208. /**
  43209. * Intensity of the environment e.g. how much the environment will light the object
  43210. * either through harmonics for rough material or through the refelction for shiny ones.
  43211. */
  43212. _this._environmentIntensity = 1.0;
  43213. /**
  43214. * This is a special control allowing the reduction of the specular highlights coming from the
  43215. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43216. */
  43217. _this._specularIntensity = 1.0;
  43218. /**
  43219. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43220. */
  43221. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43222. /**
  43223. * Debug Control allowing disabling the bump map on this material.
  43224. */
  43225. _this._disableBumpMap = false;
  43226. /**
  43227. * AKA Occlusion Texture Intensity in other nomenclature.
  43228. */
  43229. _this._ambientTextureStrength = 1.0;
  43230. /**
  43231. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43232. * 1 means it completely occludes it
  43233. * 0 mean it has no impact
  43234. */
  43235. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43236. /**
  43237. * The color of a material in ambient lighting.
  43238. */
  43239. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43240. /**
  43241. * AKA Diffuse Color in other nomenclature.
  43242. */
  43243. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43244. /**
  43245. * AKA Specular Color in other nomenclature.
  43246. */
  43247. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43248. /**
  43249. * The color applied when light is reflected from a material.
  43250. */
  43251. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43252. /**
  43253. * The color applied when light is emitted from a material.
  43254. */
  43255. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43256. /**
  43257. * AKA Glossiness in other nomenclature.
  43258. */
  43259. _this._microSurface = 0.9;
  43260. /**
  43261. * source material index of refraction (IOR)' / 'destination material IOR.
  43262. */
  43263. _this._indexOfRefraction = 0.66;
  43264. /**
  43265. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43266. */
  43267. _this._invertRefractionY = false;
  43268. /**
  43269. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43270. * Materials half opaque for instance using refraction could benefit from this control.
  43271. */
  43272. _this._linkRefractionWithTransparency = false;
  43273. /**
  43274. * Specifies that the material will use the light map as a show map.
  43275. */
  43276. _this._useLightmapAsShadowmap = false;
  43277. /**
  43278. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43279. * makes the reflect vector face the model (under horizon).
  43280. */
  43281. _this._useHorizonOcclusion = true;
  43282. /**
  43283. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43284. * too much the area relying on ambient texture to define their ambient occlusion.
  43285. */
  43286. _this._useRadianceOcclusion = true;
  43287. /**
  43288. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43289. */
  43290. _this._useAlphaFromAlbedoTexture = false;
  43291. /**
  43292. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43293. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43294. */
  43295. _this._useSpecularOverAlpha = true;
  43296. /**
  43297. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43298. */
  43299. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43300. /**
  43301. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43302. */
  43303. _this._useRoughnessFromMetallicTextureAlpha = true;
  43304. /**
  43305. * Specifies if the metallic texture contains the roughness information in its green channel.
  43306. */
  43307. _this._useRoughnessFromMetallicTextureGreen = false;
  43308. /**
  43309. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43310. */
  43311. _this._useMetallnessFromMetallicTextureBlue = false;
  43312. /**
  43313. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43314. */
  43315. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43316. /**
  43317. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43318. */
  43319. _this._useAmbientInGrayScale = false;
  43320. /**
  43321. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43322. * The material will try to infer what glossiness each pixel should be.
  43323. */
  43324. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43325. /**
  43326. * Defines the falloff type used in this material.
  43327. * It by default is Physical.
  43328. */
  43329. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43330. /**
  43331. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43332. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43333. */
  43334. _this._useRadianceOverAlpha = true;
  43335. /**
  43336. * Allows using an object space normal map (instead of tangent space).
  43337. */
  43338. _this._useObjectSpaceNormalMap = false;
  43339. /**
  43340. * Allows using the bump map in parallax mode.
  43341. */
  43342. _this._useParallax = false;
  43343. /**
  43344. * Allows using the bump map in parallax occlusion mode.
  43345. */
  43346. _this._useParallaxOcclusion = false;
  43347. /**
  43348. * Controls the scale bias of the parallax mode.
  43349. */
  43350. _this._parallaxScaleBias = 0.05;
  43351. /**
  43352. * If sets to true, disables all the lights affecting the material.
  43353. */
  43354. _this._disableLighting = false;
  43355. /**
  43356. * Number of Simultaneous lights allowed on the material.
  43357. */
  43358. _this._maxSimultaneousLights = 4;
  43359. /**
  43360. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43361. */
  43362. _this._invertNormalMapX = false;
  43363. /**
  43364. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43365. */
  43366. _this._invertNormalMapY = false;
  43367. /**
  43368. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43369. */
  43370. _this._twoSidedLighting = false;
  43371. /**
  43372. * Defines the alpha limits in alpha test mode.
  43373. */
  43374. _this._alphaCutOff = 0.4;
  43375. /**
  43376. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43377. */
  43378. _this._forceAlphaTest = false;
  43379. /**
  43380. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43381. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43382. */
  43383. _this._useAlphaFresnel = false;
  43384. /**
  43385. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43386. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43387. */
  43388. _this._useLinearAlphaFresnel = false;
  43389. /**
  43390. * The transparency mode of the material.
  43391. */
  43392. _this._transparencyMode = null;
  43393. /**
  43394. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43395. * from cos thetav and roughness:
  43396. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43397. */
  43398. _this._environmentBRDFTexture = null;
  43399. /**
  43400. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43401. */
  43402. _this._forceIrradianceInFragment = false;
  43403. /**
  43404. * Force normal to face away from face.
  43405. */
  43406. _this._forceNormalForward = false;
  43407. /**
  43408. * Enables specular anti aliasing in the PBR shader.
  43409. * It will both interacts on the Geometry for analytical and IBL lighting.
  43410. * It also prefilter the roughness map based on the bump values.
  43411. */
  43412. _this._enableSpecularAntiAliasing = false;
  43413. /**
  43414. * Stores the available render targets.
  43415. */
  43416. _this._renderTargets = new BABYLON.SmartArray(16);
  43417. /**
  43418. * Sets the global ambient color for the material used in lighting calculations.
  43419. */
  43420. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43421. /**
  43422. * If set to true, no lighting calculations will be applied.
  43423. */
  43424. _this._unlit = false;
  43425. // Setup the default processing configuration to the scene.
  43426. _this._attachImageProcessingConfiguration(null);
  43427. _this.getRenderTargetTextures = function () {
  43428. _this._renderTargets.reset();
  43429. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43430. _this._renderTargets.push(_this._reflectionTexture);
  43431. }
  43432. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43433. _this._renderTargets.push(_this._refractionTexture);
  43434. }
  43435. return _this._renderTargets;
  43436. };
  43437. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43438. return _this;
  43439. }
  43440. /**
  43441. * Attaches a new image processing configuration to the PBR Material.
  43442. * @param configuration
  43443. */
  43444. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43445. var _this = this;
  43446. if (configuration === this._imageProcessingConfiguration) {
  43447. return;
  43448. }
  43449. // Detaches observer.
  43450. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43451. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43452. }
  43453. // Pick the scene configuration if needed.
  43454. if (!configuration) {
  43455. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43456. }
  43457. else {
  43458. this._imageProcessingConfiguration = configuration;
  43459. }
  43460. // Attaches observer.
  43461. if (this._imageProcessingConfiguration) {
  43462. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43463. _this._markAllSubMeshesAsImageProcessingDirty();
  43464. });
  43465. }
  43466. };
  43467. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  43468. /**
  43469. * Gets a boolean indicating that current material needs to register RTT
  43470. */
  43471. get: function () {
  43472. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43473. return true;
  43474. }
  43475. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43476. return true;
  43477. }
  43478. return false;
  43479. },
  43480. enumerable: true,
  43481. configurable: true
  43482. });
  43483. /**
  43484. * Gets the name of the material class.
  43485. */
  43486. PBRBaseMaterial.prototype.getClassName = function () {
  43487. return "PBRBaseMaterial";
  43488. };
  43489. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43490. /**
  43491. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43492. */
  43493. get: function () {
  43494. return this._useLogarithmicDepth;
  43495. },
  43496. /**
  43497. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43498. */
  43499. set: function (value) {
  43500. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43501. },
  43502. enumerable: true,
  43503. configurable: true
  43504. });
  43505. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43506. /**
  43507. * Gets the current transparency mode.
  43508. */
  43509. get: function () {
  43510. return this._transparencyMode;
  43511. },
  43512. /**
  43513. * Sets the transparency mode of the material.
  43514. *
  43515. * | Value | Type | Description |
  43516. * | ----- | ----------------------------------- | ----------- |
  43517. * | 0 | OPAQUE | |
  43518. * | 1 | ALPHATEST | |
  43519. * | 2 | ALPHABLEND | |
  43520. * | 3 | ALPHATESTANDBLEND | |
  43521. *
  43522. */
  43523. set: function (value) {
  43524. if (this._transparencyMode === value) {
  43525. return;
  43526. }
  43527. this._transparencyMode = value;
  43528. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43529. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43530. },
  43531. enumerable: true,
  43532. configurable: true
  43533. });
  43534. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43535. /**
  43536. * Returns true if alpha blending should be disabled.
  43537. */
  43538. get: function () {
  43539. return (this._linkRefractionWithTransparency ||
  43540. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43541. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43542. },
  43543. enumerable: true,
  43544. configurable: true
  43545. });
  43546. /**
  43547. * Specifies whether or not this material should be rendered in alpha blend mode.
  43548. */
  43549. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43550. if (this._disableAlphaBlending) {
  43551. return false;
  43552. }
  43553. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43554. };
  43555. /**
  43556. * Specifies if the mesh will require alpha blending.
  43557. * @param mesh - BJS mesh.
  43558. */
  43559. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43560. if (this._disableAlphaBlending) {
  43561. return false;
  43562. }
  43563. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43564. };
  43565. /**
  43566. * Specifies whether or not this material should be rendered in alpha test mode.
  43567. */
  43568. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43569. if (this._forceAlphaTest) {
  43570. return true;
  43571. }
  43572. if (this._linkRefractionWithTransparency) {
  43573. return false;
  43574. }
  43575. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43576. };
  43577. /**
  43578. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43579. */
  43580. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43581. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43582. };
  43583. /**
  43584. * Gets the texture used for the alpha test.
  43585. */
  43586. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43587. return this._albedoTexture;
  43588. };
  43589. /**
  43590. * Specifies that the submesh is ready to be used.
  43591. * @param mesh - BJS mesh.
  43592. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43593. * @param useInstances - Specifies that instances should be used.
  43594. * @returns - boolean indicating that the submesh is ready or not.
  43595. */
  43596. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43597. if (subMesh.effect && this.isFrozen) {
  43598. if (this._wasPreviouslyReady) {
  43599. return true;
  43600. }
  43601. }
  43602. if (!subMesh._materialDefines) {
  43603. subMesh._materialDefines = new PBRMaterialDefines();
  43604. }
  43605. var defines = subMesh._materialDefines;
  43606. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43607. if (defines._renderId === this.getScene().getRenderId()) {
  43608. return true;
  43609. }
  43610. }
  43611. var scene = this.getScene();
  43612. var engine = scene.getEngine();
  43613. if (defines._areTexturesDirty) {
  43614. if (scene.texturesEnabled) {
  43615. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43616. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43617. return false;
  43618. }
  43619. }
  43620. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43621. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43622. return false;
  43623. }
  43624. }
  43625. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43626. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43627. return false;
  43628. }
  43629. }
  43630. var reflectionTexture = this._getReflectionTexture();
  43631. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43632. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43633. return false;
  43634. }
  43635. }
  43636. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43637. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43638. return false;
  43639. }
  43640. }
  43641. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43642. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43643. return false;
  43644. }
  43645. }
  43646. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43647. if (this._metallicTexture) {
  43648. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43649. return false;
  43650. }
  43651. }
  43652. else if (this._reflectivityTexture) {
  43653. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43654. return false;
  43655. }
  43656. }
  43657. if (this._microSurfaceTexture) {
  43658. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43659. return false;
  43660. }
  43661. }
  43662. }
  43663. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43664. // Bump texture cannot be not blocking.
  43665. if (!this._bumpTexture.isReady()) {
  43666. return false;
  43667. }
  43668. }
  43669. var refractionTexture = this._getRefractionTexture();
  43670. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43671. if (!refractionTexture.isReadyOrNotBlocking()) {
  43672. return false;
  43673. }
  43674. }
  43675. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43676. // This is blocking.
  43677. if (!this._environmentBRDFTexture.isReady()) {
  43678. return false;
  43679. }
  43680. }
  43681. }
  43682. }
  43683. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43684. if (!this._imageProcessingConfiguration.isReady()) {
  43685. return false;
  43686. }
  43687. }
  43688. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43689. mesh.createNormals(true);
  43690. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43691. }
  43692. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43693. if (effect) {
  43694. scene.resetCachedMaterial();
  43695. subMesh.setEffect(effect, defines);
  43696. this.buildUniformLayout();
  43697. }
  43698. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43699. return false;
  43700. }
  43701. defines._renderId = scene.getRenderId();
  43702. this._wasPreviouslyReady = true;
  43703. return true;
  43704. };
  43705. /**
  43706. * Specifies if the material uses metallic roughness workflow.
  43707. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43708. */
  43709. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43710. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43711. return true;
  43712. }
  43713. return false;
  43714. };
  43715. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43716. if (onCompiled === void 0) { onCompiled = null; }
  43717. if (onError === void 0) { onError = null; }
  43718. if (useInstances === void 0) { useInstances = null; }
  43719. if (useClipPlane === void 0) { useClipPlane = null; }
  43720. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43721. if (!defines.isDirty) {
  43722. return null;
  43723. }
  43724. defines.markAsProcessed();
  43725. var scene = this.getScene();
  43726. var engine = scene.getEngine();
  43727. // Fallbacks
  43728. var fallbacks = new BABYLON.EffectFallbacks();
  43729. var fallbackRank = 0;
  43730. if (defines.USESPHERICALINVERTEX) {
  43731. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43732. }
  43733. if (defines.FOG) {
  43734. fallbacks.addFallback(fallbackRank, "FOG");
  43735. }
  43736. if (defines.SPECULARAA) {
  43737. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43738. }
  43739. if (defines.POINTSIZE) {
  43740. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43741. }
  43742. if (defines.LOGARITHMICDEPTH) {
  43743. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43744. }
  43745. if (defines.PARALLAX) {
  43746. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43747. }
  43748. if (defines.PARALLAXOCCLUSION) {
  43749. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43750. }
  43751. if (defines.ENVIRONMENTBRDF) {
  43752. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43753. }
  43754. if (defines.TANGENT) {
  43755. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43756. }
  43757. if (defines.BUMP) {
  43758. fallbacks.addFallback(fallbackRank++, "BUMP");
  43759. }
  43760. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43761. if (defines.SPECULARTERM) {
  43762. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43763. }
  43764. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43765. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43766. }
  43767. if (defines.LIGHTMAP) {
  43768. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43769. }
  43770. if (defines.NORMAL) {
  43771. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43772. }
  43773. if (defines.AMBIENT) {
  43774. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43775. }
  43776. if (defines.EMISSIVE) {
  43777. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43778. }
  43779. if (defines.VERTEXCOLOR) {
  43780. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43781. }
  43782. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43783. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43784. }
  43785. if (defines.MORPHTARGETS) {
  43786. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43787. }
  43788. //Attributes
  43789. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43790. if (defines.NORMAL) {
  43791. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43792. }
  43793. if (defines.TANGENT) {
  43794. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43795. }
  43796. if (defines.UV1) {
  43797. attribs.push(BABYLON.VertexBuffer.UVKind);
  43798. }
  43799. if (defines.UV2) {
  43800. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43801. }
  43802. if (defines.VERTEXCOLOR) {
  43803. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43804. }
  43805. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43806. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43807. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43808. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43809. "vFogInfos", "vFogColor", "pointSize",
  43810. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43811. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43812. "mBones",
  43813. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43814. "vLightingIntensity",
  43815. "logarithmicDepthConstant",
  43816. "vSphericalX", "vSphericalY", "vSphericalZ",
  43817. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43818. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43819. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  43820. "vTangentSpaceParams"
  43821. ];
  43822. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  43823. "bumpSampler", "lightmapSampler", "opacitySampler",
  43824. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  43825. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  43826. "microSurfaceSampler", "environmentBrdfSampler"];
  43827. var uniformBuffers = ["Material", "Scene"];
  43828. if (BABYLON.ImageProcessingConfiguration) {
  43829. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43830. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43831. }
  43832. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43833. uniformsNames: uniforms,
  43834. uniformBuffersNames: uniformBuffers,
  43835. samplers: samplers,
  43836. defines: defines,
  43837. maxSimultaneousLights: this._maxSimultaneousLights
  43838. });
  43839. var join = defines.toString();
  43840. return engine.createEffect("pbr", {
  43841. attributes: attribs,
  43842. uniformsNames: uniforms,
  43843. uniformBuffersNames: uniformBuffers,
  43844. samplers: samplers,
  43845. defines: join,
  43846. fallbacks: fallbacks,
  43847. onCompiled: onCompiled,
  43848. onError: onError,
  43849. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43850. }, engine);
  43851. };
  43852. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  43853. if (useInstances === void 0) { useInstances = null; }
  43854. if (useClipPlane === void 0) { useClipPlane = null; }
  43855. var scene = this.getScene();
  43856. var engine = scene.getEngine();
  43857. // Lights
  43858. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43859. defines._needNormals = true;
  43860. // Textures
  43861. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  43862. if (defines._areTexturesDirty) {
  43863. defines._needUVs = false;
  43864. if (scene.texturesEnabled) {
  43865. if (scene.getEngine().getCaps().textureLOD) {
  43866. defines.LODBASEDMICROSFURACE = true;
  43867. }
  43868. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43869. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  43870. }
  43871. else {
  43872. defines.ALBEDO = false;
  43873. }
  43874. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43875. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43876. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  43877. }
  43878. else {
  43879. defines.AMBIENT = false;
  43880. }
  43881. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43882. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43883. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43884. }
  43885. else {
  43886. defines.OPACITY = false;
  43887. }
  43888. var reflectionTexture = this._getReflectionTexture();
  43889. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43890. defines.REFLECTION = true;
  43891. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  43892. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  43893. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  43894. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  43895. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  43896. defines.INVERTCUBICMAP = true;
  43897. }
  43898. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  43899. switch (reflectionTexture.coordinatesMode) {
  43900. case BABYLON.Texture.EXPLICIT_MODE:
  43901. defines.REFLECTIONMAP_EXPLICIT = true;
  43902. break;
  43903. case BABYLON.Texture.PLANAR_MODE:
  43904. defines.REFLECTIONMAP_PLANAR = true;
  43905. break;
  43906. case BABYLON.Texture.PROJECTION_MODE:
  43907. defines.REFLECTIONMAP_PROJECTION = true;
  43908. break;
  43909. case BABYLON.Texture.SKYBOX_MODE:
  43910. defines.REFLECTIONMAP_SKYBOX = true;
  43911. break;
  43912. case BABYLON.Texture.SPHERICAL_MODE:
  43913. defines.REFLECTIONMAP_SPHERICAL = true;
  43914. break;
  43915. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43916. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  43917. break;
  43918. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43919. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  43920. break;
  43921. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43922. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  43923. break;
  43924. case BABYLON.Texture.CUBIC_MODE:
  43925. case BABYLON.Texture.INVCUBIC_MODE:
  43926. default:
  43927. defines.REFLECTIONMAP_CUBIC = true;
  43928. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  43929. break;
  43930. }
  43931. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  43932. if (reflectionTexture.sphericalPolynomial) {
  43933. defines.USESPHERICALFROMREFLECTIONMAP = true;
  43934. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  43935. defines.USESPHERICALINVERTEX = false;
  43936. }
  43937. else {
  43938. defines.USESPHERICALINVERTEX = true;
  43939. }
  43940. }
  43941. }
  43942. else {
  43943. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  43944. }
  43945. }
  43946. else {
  43947. defines.REFLECTION = false;
  43948. defines.REFLECTIONMAP_3D = false;
  43949. defines.REFLECTIONMAP_SPHERICAL = false;
  43950. defines.REFLECTIONMAP_PLANAR = false;
  43951. defines.REFLECTIONMAP_CUBIC = false;
  43952. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43953. defines.REFLECTIONMAP_PROJECTION = false;
  43954. defines.REFLECTIONMAP_SKYBOX = false;
  43955. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43956. defines.REFLECTIONMAP_EXPLICIT = false;
  43957. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43958. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43959. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43960. defines.INVERTCUBICMAP = false;
  43961. defines.USESPHERICALFROMREFLECTIONMAP = false;
  43962. defines.USESPHERICALINVERTEX = false;
  43963. defines.REFLECTIONMAP_OPPOSITEZ = false;
  43964. defines.LODINREFLECTIONALPHA = false;
  43965. defines.GAMMAREFLECTION = false;
  43966. defines.RGBDREFLECTION = false;
  43967. }
  43968. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43969. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43970. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43971. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  43972. }
  43973. else {
  43974. defines.LIGHTMAP = false;
  43975. }
  43976. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43977. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43978. }
  43979. else {
  43980. defines.EMISSIVE = false;
  43981. }
  43982. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43983. if (this._metallicTexture) {
  43984. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  43985. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  43986. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  43987. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  43988. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  43989. }
  43990. else if (this._reflectivityTexture) {
  43991. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  43992. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  43993. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  43994. }
  43995. else {
  43996. defines.REFLECTIVITY = false;
  43997. }
  43998. if (this._microSurfaceTexture) {
  43999. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44000. }
  44001. else {
  44002. defines.MICROSURFACEMAP = false;
  44003. }
  44004. }
  44005. else {
  44006. defines.REFLECTIVITY = false;
  44007. defines.MICROSURFACEMAP = false;
  44008. }
  44009. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44010. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44011. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44012. defines.PARALLAX = true;
  44013. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44014. }
  44015. else {
  44016. defines.PARALLAX = false;
  44017. }
  44018. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44019. }
  44020. else {
  44021. defines.BUMP = false;
  44022. }
  44023. var refractionTexture = this._getRefractionTexture();
  44024. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44025. defines.REFRACTION = true;
  44026. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44027. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44028. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44029. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44030. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44031. if (this._linkRefractionWithTransparency) {
  44032. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44033. }
  44034. }
  44035. else {
  44036. defines.REFRACTION = false;
  44037. }
  44038. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44039. defines.ENVIRONMENTBRDF = true;
  44040. }
  44041. else {
  44042. defines.ENVIRONMENTBRDF = false;
  44043. }
  44044. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44045. defines.ALPHAFROMALBEDO = true;
  44046. }
  44047. else {
  44048. defines.ALPHAFROMALBEDO = false;
  44049. }
  44050. }
  44051. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44052. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44053. defines.USEPHYSICALLIGHTFALLOFF = false;
  44054. defines.USEGLTFLIGHTFALLOFF = false;
  44055. }
  44056. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44057. defines.USEPHYSICALLIGHTFALLOFF = false;
  44058. defines.USEGLTFLIGHTFALLOFF = true;
  44059. }
  44060. else {
  44061. defines.USEPHYSICALLIGHTFALLOFF = true;
  44062. defines.USEGLTFLIGHTFALLOFF = false;
  44063. }
  44064. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44065. if (!this.backFaceCulling && this._twoSidedLighting) {
  44066. defines.TWOSIDEDLIGHTING = true;
  44067. }
  44068. else {
  44069. defines.TWOSIDEDLIGHTING = false;
  44070. }
  44071. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44072. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44073. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44074. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44075. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44076. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44077. }
  44078. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44079. this._imageProcessingConfiguration.prepareDefines(defines);
  44080. }
  44081. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44082. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44083. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44084. // Misc.
  44085. if (defines._areMiscDirty) {
  44086. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44087. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44088. }
  44089. // Values that need to be evaluated on every frame
  44090. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44091. // Attribs
  44092. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44093. };
  44094. /**
  44095. * Force shader compilation
  44096. */
  44097. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44098. var _this = this;
  44099. var localOptions = __assign({ clipPlane: false }, options);
  44100. var defines = new PBRMaterialDefines();
  44101. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44102. if (effect.isReady()) {
  44103. if (onCompiled) {
  44104. onCompiled(this);
  44105. }
  44106. }
  44107. else {
  44108. effect.onCompileObservable.add(function () {
  44109. if (onCompiled) {
  44110. onCompiled(_this);
  44111. }
  44112. });
  44113. }
  44114. };
  44115. /**
  44116. * Initializes the uniform buffer layout for the shader.
  44117. */
  44118. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44119. // Order is important !
  44120. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44121. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44122. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44123. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44124. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44125. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44126. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44127. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44128. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44129. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44130. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44131. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44132. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44133. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44134. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44135. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44136. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44137. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44138. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44139. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44140. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44141. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44142. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44143. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44144. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44145. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44146. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44147. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44148. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44149. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44150. this._uniformBuffer.addUniform("pointSize", 1);
  44151. this._uniformBuffer.create();
  44152. };
  44153. /**
  44154. * Unbinds the textures.
  44155. */
  44156. PBRBaseMaterial.prototype.unbind = function () {
  44157. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44158. this._uniformBuffer.setTexture("reflectionSampler", null);
  44159. }
  44160. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44161. this._uniformBuffer.setTexture("refractionSampler", null);
  44162. }
  44163. _super.prototype.unbind.call(this);
  44164. };
  44165. /**
  44166. * Binds the submesh data.
  44167. * @param world - The world matrix.
  44168. * @param mesh - The BJS mesh.
  44169. * @param subMesh - A submesh of the BJS mesh.
  44170. */
  44171. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44172. var scene = this.getScene();
  44173. var defines = subMesh._materialDefines;
  44174. if (!defines) {
  44175. return;
  44176. }
  44177. var effect = subMesh.effect;
  44178. if (!effect) {
  44179. return;
  44180. }
  44181. this._activeEffect = effect;
  44182. // Matrices
  44183. this.bindOnlyWorldMatrix(world);
  44184. // Normal Matrix
  44185. if (defines.OBJECTSPACE_NORMALMAP) {
  44186. world.toNormalMatrix(this._normalMatrix);
  44187. this.bindOnlyNormalMatrix(this._normalMatrix);
  44188. }
  44189. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44190. // Bones
  44191. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44192. var reflectionTexture = null;
  44193. if (mustRebind) {
  44194. this._uniformBuffer.bindToEffect(effect, "Material");
  44195. this.bindViewProjection(effect);
  44196. reflectionTexture = this._getReflectionTexture();
  44197. var refractionTexture = this._getRefractionTexture();
  44198. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44199. // Texture uniforms
  44200. if (scene.texturesEnabled) {
  44201. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44202. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44203. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44204. }
  44205. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44206. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44207. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44208. }
  44209. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44210. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44211. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44212. }
  44213. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44214. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44215. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44216. if (reflectionTexture.boundingBoxSize) {
  44217. var cubeTexture = reflectionTexture;
  44218. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44219. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44220. }
  44221. var polynomials = reflectionTexture.sphericalPolynomial;
  44222. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44223. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44224. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44225. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44226. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44227. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44228. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44229. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44230. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44231. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44232. }
  44233. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44234. }
  44235. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44236. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44237. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44238. }
  44239. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44240. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44241. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44242. }
  44243. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44244. if (this._metallicTexture) {
  44245. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44246. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44247. }
  44248. else if (this._reflectivityTexture) {
  44249. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44250. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44251. }
  44252. if (this._microSurfaceTexture) {
  44253. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44254. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44255. }
  44256. }
  44257. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44258. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44259. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44260. if (scene._mirroredCameraPosition) {
  44261. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44262. }
  44263. else {
  44264. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44265. }
  44266. }
  44267. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44268. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44269. var depth = 1.0;
  44270. if (!refractionTexture.isCube) {
  44271. if (refractionTexture.depth) {
  44272. depth = refractionTexture.depth;
  44273. }
  44274. }
  44275. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44276. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44277. }
  44278. }
  44279. // Point size
  44280. if (this.pointsCloud) {
  44281. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44282. }
  44283. // Colors
  44284. if (defines.METALLICWORKFLOW) {
  44285. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44286. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44287. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44288. }
  44289. else {
  44290. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44291. }
  44292. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44293. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44294. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44295. // Misc
  44296. this._lightingInfos.x = this._directIntensity;
  44297. this._lightingInfos.y = this._emissiveIntensity;
  44298. this._lightingInfos.z = this._environmentIntensity;
  44299. this._lightingInfos.w = this._specularIntensity;
  44300. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44301. }
  44302. // Textures
  44303. if (scene.texturesEnabled) {
  44304. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44305. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44306. }
  44307. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44308. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44309. }
  44310. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44311. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44312. }
  44313. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44314. if (defines.LODBASEDMICROSFURACE) {
  44315. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44316. }
  44317. else {
  44318. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44319. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44320. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44321. }
  44322. }
  44323. if (defines.ENVIRONMENTBRDF) {
  44324. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44325. }
  44326. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44327. if (defines.LODBASEDMICROSFURACE) {
  44328. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44329. }
  44330. else {
  44331. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44332. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44333. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44334. }
  44335. }
  44336. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44337. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44338. }
  44339. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44340. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44341. }
  44342. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44343. if (this._metallicTexture) {
  44344. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44345. }
  44346. else if (this._reflectivityTexture) {
  44347. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44348. }
  44349. if (this._microSurfaceTexture) {
  44350. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44351. }
  44352. }
  44353. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44354. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44355. }
  44356. }
  44357. // Clip plane
  44358. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44359. // Colors
  44360. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44361. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44362. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44363. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44364. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44365. }
  44366. if (mustRebind || !this.isFrozen) {
  44367. // Lights
  44368. if (scene.lightsEnabled && !this._disableLighting) {
  44369. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44370. }
  44371. // View
  44372. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44373. this.bindView(effect);
  44374. }
  44375. // Fog
  44376. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44377. // Morph targets
  44378. if (defines.NUM_MORPH_INFLUENCERS) {
  44379. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44380. }
  44381. // image processing
  44382. this._imageProcessingConfiguration.bind(this._activeEffect);
  44383. // Log. depth
  44384. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44385. }
  44386. this._uniformBuffer.update();
  44387. this._afterBind(mesh, this._activeEffect);
  44388. };
  44389. /**
  44390. * Returns the animatable textures.
  44391. * @returns - Array of animatable textures.
  44392. */
  44393. PBRBaseMaterial.prototype.getAnimatables = function () {
  44394. var results = [];
  44395. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44396. results.push(this._albedoTexture);
  44397. }
  44398. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44399. results.push(this._ambientTexture);
  44400. }
  44401. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44402. results.push(this._opacityTexture);
  44403. }
  44404. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44405. results.push(this._reflectionTexture);
  44406. }
  44407. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44408. results.push(this._emissiveTexture);
  44409. }
  44410. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44411. results.push(this._metallicTexture);
  44412. }
  44413. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44414. results.push(this._reflectivityTexture);
  44415. }
  44416. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44417. results.push(this._bumpTexture);
  44418. }
  44419. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44420. results.push(this._lightmapTexture);
  44421. }
  44422. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44423. results.push(this._refractionTexture);
  44424. }
  44425. return results;
  44426. };
  44427. /**
  44428. * Returns the texture used for reflections.
  44429. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44430. */
  44431. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44432. if (this._reflectionTexture) {
  44433. return this._reflectionTexture;
  44434. }
  44435. return this.getScene().environmentTexture;
  44436. };
  44437. /**
  44438. * Returns the texture used for refraction or null if none is used.
  44439. * @returns - Refection texture if present. If no refraction texture and refraction
  44440. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44441. */
  44442. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44443. if (this._refractionTexture) {
  44444. return this._refractionTexture;
  44445. }
  44446. if (this._linkRefractionWithTransparency) {
  44447. return this.getScene().environmentTexture;
  44448. }
  44449. return null;
  44450. };
  44451. /**
  44452. * Disposes the resources of the material.
  44453. * @param forceDisposeEffect - Forces the disposal of effects.
  44454. * @param forceDisposeTextures - Forces the disposal of all textures.
  44455. */
  44456. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44457. if (forceDisposeTextures) {
  44458. if (this._albedoTexture) {
  44459. this._albedoTexture.dispose();
  44460. }
  44461. if (this._ambientTexture) {
  44462. this._ambientTexture.dispose();
  44463. }
  44464. if (this._opacityTexture) {
  44465. this._opacityTexture.dispose();
  44466. }
  44467. if (this._reflectionTexture) {
  44468. this._reflectionTexture.dispose();
  44469. }
  44470. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44471. this._environmentBRDFTexture.dispose();
  44472. }
  44473. if (this._emissiveTexture) {
  44474. this._emissiveTexture.dispose();
  44475. }
  44476. if (this._metallicTexture) {
  44477. this._metallicTexture.dispose();
  44478. }
  44479. if (this._reflectivityTexture) {
  44480. this._reflectivityTexture.dispose();
  44481. }
  44482. if (this._bumpTexture) {
  44483. this._bumpTexture.dispose();
  44484. }
  44485. if (this._lightmapTexture) {
  44486. this._lightmapTexture.dispose();
  44487. }
  44488. if (this._refractionTexture) {
  44489. this._refractionTexture.dispose();
  44490. }
  44491. }
  44492. this._renderTargets.dispose();
  44493. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44494. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44495. }
  44496. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44497. };
  44498. /**
  44499. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  44500. */
  44501. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  44502. /**
  44503. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  44504. * to enhance interoperability with other engines.
  44505. */
  44506. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  44507. /**
  44508. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  44509. * to enhance interoperability with other materials.
  44510. */
  44511. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  44512. /**
  44513. * Stores the reflectivity values based on metallic roughness workflow.
  44514. */
  44515. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44516. __decorate([
  44517. BABYLON.serializeAsImageProcessingConfiguration()
  44518. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44519. __decorate([
  44520. BABYLON.serialize()
  44521. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44522. __decorate([
  44523. BABYLON.serialize()
  44524. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44525. return PBRBaseMaterial;
  44526. }(BABYLON.PushMaterial));
  44527. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44528. })(BABYLON || (BABYLON = {}));
  44529. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44530. var BABYLON;
  44531. (function (BABYLON) {
  44532. /**
  44533. * The Physically based simple base material of BJS.
  44534. *
  44535. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44536. * It is used as the base class for both the specGloss and metalRough conventions.
  44537. */
  44538. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44539. __extends(PBRBaseSimpleMaterial, _super);
  44540. /**
  44541. * Instantiates a new PBRMaterial instance.
  44542. *
  44543. * @param name The material name
  44544. * @param scene The scene the material will be use in.
  44545. */
  44546. function PBRBaseSimpleMaterial(name, scene) {
  44547. var _this = _super.call(this, name, scene) || this;
  44548. /**
  44549. * Number of Simultaneous lights allowed on the material.
  44550. */
  44551. _this.maxSimultaneousLights = 4;
  44552. /**
  44553. * If sets to true, disables all the lights affecting the material.
  44554. */
  44555. _this.disableLighting = false;
  44556. /**
  44557. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44558. */
  44559. _this.invertNormalMapX = false;
  44560. /**
  44561. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44562. */
  44563. _this.invertNormalMapY = false;
  44564. /**
  44565. * Emissivie color used to self-illuminate the model.
  44566. */
  44567. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44568. /**
  44569. * Occlusion Channel Strenght.
  44570. */
  44571. _this.occlusionStrength = 1.0;
  44572. _this.useLightmapAsShadowmap = false;
  44573. _this._useAlphaFromAlbedoTexture = true;
  44574. _this._useAmbientInGrayScale = true;
  44575. return _this;
  44576. }
  44577. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44578. /**
  44579. * Gets the current double sided mode.
  44580. */
  44581. get: function () {
  44582. return this._twoSidedLighting;
  44583. },
  44584. /**
  44585. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44586. */
  44587. set: function (value) {
  44588. if (this._twoSidedLighting === value) {
  44589. return;
  44590. }
  44591. this._twoSidedLighting = value;
  44592. this.backFaceCulling = !value;
  44593. this._markAllSubMeshesAsTexturesDirty();
  44594. },
  44595. enumerable: true,
  44596. configurable: true
  44597. });
  44598. /**
  44599. * Return the active textures of the material.
  44600. */
  44601. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44602. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44603. if (this.environmentTexture) {
  44604. activeTextures.push(this.environmentTexture);
  44605. }
  44606. if (this.normalTexture) {
  44607. activeTextures.push(this.normalTexture);
  44608. }
  44609. if (this.emissiveTexture) {
  44610. activeTextures.push(this.emissiveTexture);
  44611. }
  44612. if (this.occlusionTexture) {
  44613. activeTextures.push(this.occlusionTexture);
  44614. }
  44615. if (this.lightmapTexture) {
  44616. activeTextures.push(this.lightmapTexture);
  44617. }
  44618. return activeTextures;
  44619. };
  44620. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44621. if (_super.prototype.hasTexture.call(this, texture)) {
  44622. return true;
  44623. }
  44624. if (this.lightmapTexture === texture) {
  44625. return true;
  44626. }
  44627. return false;
  44628. };
  44629. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44630. return "PBRBaseSimpleMaterial";
  44631. };
  44632. __decorate([
  44633. BABYLON.serialize(),
  44634. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44635. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44636. __decorate([
  44637. BABYLON.serialize(),
  44638. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44639. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44640. __decorate([
  44641. BABYLON.serializeAsTexture(),
  44642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44643. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44644. __decorate([
  44645. BABYLON.serialize(),
  44646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44647. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44648. __decorate([
  44649. BABYLON.serialize(),
  44650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44651. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44652. __decorate([
  44653. BABYLON.serializeAsTexture(),
  44654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44655. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44656. __decorate([
  44657. BABYLON.serializeAsColor3("emissive"),
  44658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44659. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44660. __decorate([
  44661. BABYLON.serializeAsTexture(),
  44662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44663. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44664. __decorate([
  44665. BABYLON.serialize(),
  44666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44667. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44668. __decorate([
  44669. BABYLON.serializeAsTexture(),
  44670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44671. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44672. __decorate([
  44673. BABYLON.serialize(),
  44674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44675. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44676. __decorate([
  44677. BABYLON.serialize()
  44678. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44679. __decorate([
  44680. BABYLON.serializeAsTexture(),
  44681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44682. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44683. __decorate([
  44684. BABYLON.serialize(),
  44685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44686. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44687. return PBRBaseSimpleMaterial;
  44688. }(BABYLON.PBRBaseMaterial));
  44689. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44690. })(BABYLON || (BABYLON = {}));
  44691. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44692. var BABYLON;
  44693. (function (BABYLON) {
  44694. /**
  44695. * The Physically based material of BJS.
  44696. *
  44697. * This offers the main features of a standard PBR material.
  44698. * For more information, please refer to the documentation :
  44699. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44700. */
  44701. var PBRMaterial = /** @class */ (function (_super) {
  44702. __extends(PBRMaterial, _super);
  44703. /**
  44704. * Instantiates a new PBRMaterial instance.
  44705. *
  44706. * @param name The material name
  44707. * @param scene The scene the material will be use in.
  44708. */
  44709. function PBRMaterial(name, scene) {
  44710. var _this = _super.call(this, name, scene) || this;
  44711. /**
  44712. * Intensity of the direct lights e.g. the four lights available in your scene.
  44713. * This impacts both the direct diffuse and specular highlights.
  44714. */
  44715. _this.directIntensity = 1.0;
  44716. /**
  44717. * Intensity of the emissive part of the material.
  44718. * This helps controlling the emissive effect without modifying the emissive color.
  44719. */
  44720. _this.emissiveIntensity = 1.0;
  44721. /**
  44722. * Intensity of the environment e.g. how much the environment will light the object
  44723. * either through harmonics for rough material or through the refelction for shiny ones.
  44724. */
  44725. _this.environmentIntensity = 1.0;
  44726. /**
  44727. * This is a special control allowing the reduction of the specular highlights coming from the
  44728. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44729. */
  44730. _this.specularIntensity = 1.0;
  44731. /**
  44732. * Debug Control allowing disabling the bump map on this material.
  44733. */
  44734. _this.disableBumpMap = false;
  44735. /**
  44736. * AKA Occlusion Texture Intensity in other nomenclature.
  44737. */
  44738. _this.ambientTextureStrength = 1.0;
  44739. /**
  44740. * Defines how much the AO map is occluding the analytical lights (point spot...).
  44741. * 1 means it completely occludes it
  44742. * 0 mean it has no impact
  44743. */
  44744. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  44745. /**
  44746. * The color of a material in ambient lighting.
  44747. */
  44748. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44749. /**
  44750. * AKA Diffuse Color in other nomenclature.
  44751. */
  44752. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44753. /**
  44754. * AKA Specular Color in other nomenclature.
  44755. */
  44756. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44757. /**
  44758. * The color reflected from the material.
  44759. */
  44760. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44761. /**
  44762. * The color emitted from the material.
  44763. */
  44764. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44765. /**
  44766. * AKA Glossiness in other nomenclature.
  44767. */
  44768. _this.microSurface = 1.0;
  44769. /**
  44770. * source material index of refraction (IOR)' / 'destination material IOR.
  44771. */
  44772. _this.indexOfRefraction = 0.66;
  44773. /**
  44774. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44775. */
  44776. _this.invertRefractionY = false;
  44777. /**
  44778. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44779. * Materials half opaque for instance using refraction could benefit from this control.
  44780. */
  44781. _this.linkRefractionWithTransparency = false;
  44782. _this.useLightmapAsShadowmap = false;
  44783. /**
  44784. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44785. */
  44786. _this.useAlphaFromAlbedoTexture = false;
  44787. /**
  44788. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44789. */
  44790. _this.forceAlphaTest = false;
  44791. /**
  44792. * Defines the alpha limits in alpha test mode.
  44793. */
  44794. _this.alphaCutOff = 0.4;
  44795. /**
  44796. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44797. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44798. */
  44799. _this.useSpecularOverAlpha = true;
  44800. /**
  44801. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44802. */
  44803. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44804. /**
  44805. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44806. */
  44807. _this.useRoughnessFromMetallicTextureAlpha = true;
  44808. /**
  44809. * Specifies if the metallic texture contains the roughness information in its green channel.
  44810. */
  44811. _this.useRoughnessFromMetallicTextureGreen = false;
  44812. /**
  44813. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44814. */
  44815. _this.useMetallnessFromMetallicTextureBlue = false;
  44816. /**
  44817. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44818. */
  44819. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44820. /**
  44821. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44822. */
  44823. _this.useAmbientInGrayScale = false;
  44824. /**
  44825. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44826. * The material will try to infer what glossiness each pixel should be.
  44827. */
  44828. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44829. /**
  44830. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44831. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44832. */
  44833. _this.useRadianceOverAlpha = true;
  44834. /**
  44835. * Allows using an object space normal map (instead of tangent space).
  44836. */
  44837. _this.useObjectSpaceNormalMap = false;
  44838. /**
  44839. * Allows using the bump map in parallax mode.
  44840. */
  44841. _this.useParallax = false;
  44842. /**
  44843. * Allows using the bump map in parallax occlusion mode.
  44844. */
  44845. _this.useParallaxOcclusion = false;
  44846. /**
  44847. * Controls the scale bias of the parallax mode.
  44848. */
  44849. _this.parallaxScaleBias = 0.05;
  44850. /**
  44851. * If sets to true, disables all the lights affecting the material.
  44852. */
  44853. _this.disableLighting = false;
  44854. /**
  44855. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44856. */
  44857. _this.forceIrradianceInFragment = false;
  44858. /**
  44859. * Number of Simultaneous lights allowed on the material.
  44860. */
  44861. _this.maxSimultaneousLights = 4;
  44862. /**
  44863. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44864. */
  44865. _this.invertNormalMapX = false;
  44866. /**
  44867. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44868. */
  44869. _this.invertNormalMapY = false;
  44870. /**
  44871. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44872. */
  44873. _this.twoSidedLighting = false;
  44874. /**
  44875. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44876. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44877. */
  44878. _this.useAlphaFresnel = false;
  44879. /**
  44880. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44881. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44882. */
  44883. _this.useLinearAlphaFresnel = false;
  44884. /**
  44885. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44886. * And/Or occlude the blended part.
  44887. */
  44888. _this.environmentBRDFTexture = null;
  44889. /**
  44890. * Force normal to face away from face.
  44891. */
  44892. _this.forceNormalForward = false;
  44893. /**
  44894. * Enables specular anti aliasing in the PBR shader.
  44895. * It will both interacts on the Geometry for analytical and IBL lighting.
  44896. * It also prefilter the roughness map based on the bump values.
  44897. */
  44898. _this.enableSpecularAntiAliasing = false;
  44899. /**
  44900. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44901. * makes the reflect vector face the model (under horizon).
  44902. */
  44903. _this.useHorizonOcclusion = true;
  44904. /**
  44905. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44906. * too much the area relying on ambient texture to define their ambient occlusion.
  44907. */
  44908. _this.useRadianceOcclusion = true;
  44909. /**
  44910. * If set to true, no lighting calculations will be applied.
  44911. */
  44912. _this.unlit = false;
  44913. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44914. return _this;
  44915. }
  44916. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  44917. /**
  44918. * BJS is using an harcoded light falloff based on a manually sets up range.
  44919. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44920. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44921. */
  44922. get: function () {
  44923. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  44924. },
  44925. /**
  44926. * BJS is using an harcoded light falloff based on a manually sets up range.
  44927. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44928. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44929. */
  44930. set: function (value) {
  44931. if (value !== this.usePhysicalLightFalloff) {
  44932. // Ensure the effect will be rebuilt.
  44933. this._markAllSubMeshesAsTexturesDirty();
  44934. if (value) {
  44935. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  44936. }
  44937. else {
  44938. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  44939. }
  44940. }
  44941. },
  44942. enumerable: true,
  44943. configurable: true
  44944. });
  44945. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  44946. /**
  44947. * In order to support the falloff compatibility with gltf, a special mode has been added
  44948. * to reproduce the gltf light falloff.
  44949. */
  44950. get: function () {
  44951. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  44952. },
  44953. /**
  44954. * In order to support the falloff compatibility with gltf, a special mode has been added
  44955. * to reproduce the gltf light falloff.
  44956. */
  44957. set: function (value) {
  44958. if (value !== this.useGLTFLightFalloff) {
  44959. // Ensure the effect will be rebuilt.
  44960. this._markAllSubMeshesAsTexturesDirty();
  44961. if (value) {
  44962. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  44963. }
  44964. else {
  44965. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  44966. }
  44967. }
  44968. },
  44969. enumerable: true,
  44970. configurable: true
  44971. });
  44972. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  44973. /**
  44974. * Gets the image processing configuration used either in this material.
  44975. */
  44976. get: function () {
  44977. return this._imageProcessingConfiguration;
  44978. },
  44979. /**
  44980. * Sets the Default image processing configuration used either in the this material.
  44981. *
  44982. * If sets to null, the scene one is in use.
  44983. */
  44984. set: function (value) {
  44985. this._attachImageProcessingConfiguration(value);
  44986. // Ensure the effect will be rebuilt.
  44987. this._markAllSubMeshesAsTexturesDirty();
  44988. },
  44989. enumerable: true,
  44990. configurable: true
  44991. });
  44992. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  44993. /**
  44994. * Gets wether the color curves effect is enabled.
  44995. */
  44996. get: function () {
  44997. return this.imageProcessingConfiguration.colorCurvesEnabled;
  44998. },
  44999. /**
  45000. * Sets wether the color curves effect is enabled.
  45001. */
  45002. set: function (value) {
  45003. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45004. },
  45005. enumerable: true,
  45006. configurable: true
  45007. });
  45008. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45009. /**
  45010. * Gets wether the color grading effect is enabled.
  45011. */
  45012. get: function () {
  45013. return this.imageProcessingConfiguration.colorGradingEnabled;
  45014. },
  45015. /**
  45016. * Gets wether the color grading effect is enabled.
  45017. */
  45018. set: function (value) {
  45019. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45020. },
  45021. enumerable: true,
  45022. configurable: true
  45023. });
  45024. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45025. /**
  45026. * Gets wether tonemapping is enabled or not.
  45027. */
  45028. get: function () {
  45029. return this._imageProcessingConfiguration.toneMappingEnabled;
  45030. },
  45031. /**
  45032. * Sets wether tonemapping is enabled or not
  45033. */
  45034. set: function (value) {
  45035. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45036. },
  45037. enumerable: true,
  45038. configurable: true
  45039. });
  45040. ;
  45041. ;
  45042. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45043. /**
  45044. * The camera exposure used on this material.
  45045. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45046. * This corresponds to a photographic exposure.
  45047. */
  45048. get: function () {
  45049. return this._imageProcessingConfiguration.exposure;
  45050. },
  45051. /**
  45052. * The camera exposure used on this material.
  45053. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45054. * This corresponds to a photographic exposure.
  45055. */
  45056. set: function (value) {
  45057. this._imageProcessingConfiguration.exposure = value;
  45058. },
  45059. enumerable: true,
  45060. configurable: true
  45061. });
  45062. ;
  45063. ;
  45064. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45065. /**
  45066. * Gets The camera contrast used on this material.
  45067. */
  45068. get: function () {
  45069. return this._imageProcessingConfiguration.contrast;
  45070. },
  45071. /**
  45072. * Sets The camera contrast used on this material.
  45073. */
  45074. set: function (value) {
  45075. this._imageProcessingConfiguration.contrast = value;
  45076. },
  45077. enumerable: true,
  45078. configurable: true
  45079. });
  45080. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45081. /**
  45082. * Gets the Color Grading 2D Lookup Texture.
  45083. */
  45084. get: function () {
  45085. return this._imageProcessingConfiguration.colorGradingTexture;
  45086. },
  45087. /**
  45088. * Sets the Color Grading 2D Lookup Texture.
  45089. */
  45090. set: function (value) {
  45091. this._imageProcessingConfiguration.colorGradingTexture = value;
  45092. },
  45093. enumerable: true,
  45094. configurable: true
  45095. });
  45096. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45097. /**
  45098. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45099. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45100. * 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;
  45101. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45102. */
  45103. get: function () {
  45104. return this._imageProcessingConfiguration.colorCurves;
  45105. },
  45106. /**
  45107. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45108. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45109. * 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;
  45110. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45111. */
  45112. set: function (value) {
  45113. this._imageProcessingConfiguration.colorCurves = value;
  45114. },
  45115. enumerable: true,
  45116. configurable: true
  45117. });
  45118. /**
  45119. * Returns the name of this material class.
  45120. */
  45121. PBRMaterial.prototype.getClassName = function () {
  45122. return "PBRMaterial";
  45123. };
  45124. /**
  45125. * Returns an array of the actively used textures.
  45126. * @returns - Array of BaseTextures
  45127. */
  45128. PBRMaterial.prototype.getActiveTextures = function () {
  45129. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45130. if (this._albedoTexture) {
  45131. activeTextures.push(this._albedoTexture);
  45132. }
  45133. if (this._ambientTexture) {
  45134. activeTextures.push(this._ambientTexture);
  45135. }
  45136. if (this._opacityTexture) {
  45137. activeTextures.push(this._opacityTexture);
  45138. }
  45139. if (this._reflectionTexture) {
  45140. activeTextures.push(this._reflectionTexture);
  45141. }
  45142. if (this._emissiveTexture) {
  45143. activeTextures.push(this._emissiveTexture);
  45144. }
  45145. if (this._reflectivityTexture) {
  45146. activeTextures.push(this._reflectivityTexture);
  45147. }
  45148. if (this._metallicTexture) {
  45149. activeTextures.push(this._metallicTexture);
  45150. }
  45151. if (this._microSurfaceTexture) {
  45152. activeTextures.push(this._microSurfaceTexture);
  45153. }
  45154. if (this._bumpTexture) {
  45155. activeTextures.push(this._bumpTexture);
  45156. }
  45157. if (this._lightmapTexture) {
  45158. activeTextures.push(this._lightmapTexture);
  45159. }
  45160. if (this._refractionTexture) {
  45161. activeTextures.push(this._refractionTexture);
  45162. }
  45163. return activeTextures;
  45164. };
  45165. /**
  45166. * Checks to see if a texture is used in the material.
  45167. * @param texture - Base texture to use.
  45168. * @returns - Boolean specifying if a texture is used in the material.
  45169. */
  45170. PBRMaterial.prototype.hasTexture = function (texture) {
  45171. if (_super.prototype.hasTexture.call(this, texture)) {
  45172. return true;
  45173. }
  45174. if (this._albedoTexture === texture) {
  45175. return true;
  45176. }
  45177. if (this._ambientTexture === texture) {
  45178. return true;
  45179. }
  45180. if (this._opacityTexture === texture) {
  45181. return true;
  45182. }
  45183. if (this._reflectionTexture === texture) {
  45184. return true;
  45185. }
  45186. if (this._reflectivityTexture === texture) {
  45187. return true;
  45188. }
  45189. if (this._metallicTexture === texture) {
  45190. return true;
  45191. }
  45192. if (this._microSurfaceTexture === texture) {
  45193. return true;
  45194. }
  45195. if (this._bumpTexture === texture) {
  45196. return true;
  45197. }
  45198. if (this._lightmapTexture === texture) {
  45199. return true;
  45200. }
  45201. if (this._refractionTexture === texture) {
  45202. return true;
  45203. }
  45204. return false;
  45205. };
  45206. /**
  45207. * Makes a duplicate of the current material.
  45208. * @param name - name to use for the new material.
  45209. */
  45210. PBRMaterial.prototype.clone = function (name) {
  45211. var _this = this;
  45212. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45213. clone.id = name;
  45214. clone.name = name;
  45215. return clone;
  45216. };
  45217. /**
  45218. * Serializes this PBR Material.
  45219. * @returns - An object with the serialized material.
  45220. */
  45221. PBRMaterial.prototype.serialize = function () {
  45222. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45223. serializationObject.customType = "BABYLON.PBRMaterial";
  45224. return serializationObject;
  45225. };
  45226. // Statics
  45227. /**
  45228. * Parses a PBR Material from a serialized object.
  45229. * @param source - Serialized object.
  45230. * @param scene - BJS scene instance.
  45231. * @param rootUrl - url for the scene object
  45232. * @returns - PBRMaterial
  45233. */
  45234. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45235. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45236. };
  45237. /**
  45238. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45239. */
  45240. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45241. /**
  45242. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45243. */
  45244. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45245. /**
  45246. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45247. */
  45248. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45249. /**
  45250. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45251. * They are also discarded below the alpha cutoff threshold to improve performances.
  45252. */
  45253. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45254. /**
  45255. * Defines the default value of how much AO map is occluding the analytical lights
  45256. * (point spot...).
  45257. */
  45258. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45259. __decorate([
  45260. BABYLON.serialize(),
  45261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45262. ], PBRMaterial.prototype, "directIntensity", void 0);
  45263. __decorate([
  45264. BABYLON.serialize(),
  45265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45266. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45267. __decorate([
  45268. BABYLON.serialize(),
  45269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45270. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45271. __decorate([
  45272. BABYLON.serialize(),
  45273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45274. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45275. __decorate([
  45276. BABYLON.serialize(),
  45277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45278. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45279. __decorate([
  45280. BABYLON.serializeAsTexture(),
  45281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45282. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45283. __decorate([
  45284. BABYLON.serializeAsTexture(),
  45285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45286. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45287. __decorate([
  45288. BABYLON.serialize(),
  45289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45290. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45291. __decorate([
  45292. BABYLON.serialize(),
  45293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45294. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45295. __decorate([
  45296. BABYLON.serializeAsTexture(),
  45297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45298. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45299. __decorate([
  45300. BABYLON.serializeAsTexture(),
  45301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45302. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45303. __decorate([
  45304. BABYLON.serializeAsTexture(),
  45305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45306. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45307. __decorate([
  45308. BABYLON.serializeAsTexture(),
  45309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45310. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45311. __decorate([
  45312. BABYLON.serializeAsTexture(),
  45313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45314. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45315. __decorate([
  45316. BABYLON.serialize(),
  45317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45318. ], PBRMaterial.prototype, "metallic", void 0);
  45319. __decorate([
  45320. BABYLON.serialize(),
  45321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45322. ], PBRMaterial.prototype, "roughness", void 0);
  45323. __decorate([
  45324. BABYLON.serializeAsTexture(),
  45325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45326. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45327. __decorate([
  45328. BABYLON.serializeAsTexture(),
  45329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45330. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45331. __decorate([
  45332. BABYLON.serializeAsTexture(),
  45333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45334. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45335. __decorate([
  45336. BABYLON.serializeAsTexture(),
  45337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45338. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45339. __decorate([
  45340. BABYLON.serializeAsColor3("ambient"),
  45341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45342. ], PBRMaterial.prototype, "ambientColor", void 0);
  45343. __decorate([
  45344. BABYLON.serializeAsColor3("albedo"),
  45345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45346. ], PBRMaterial.prototype, "albedoColor", void 0);
  45347. __decorate([
  45348. BABYLON.serializeAsColor3("reflectivity"),
  45349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45350. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45351. __decorate([
  45352. BABYLON.serializeAsColor3("reflection"),
  45353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45354. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45355. __decorate([
  45356. BABYLON.serializeAsColor3("emissive"),
  45357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45358. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45359. __decorate([
  45360. BABYLON.serialize(),
  45361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45362. ], PBRMaterial.prototype, "microSurface", void 0);
  45363. __decorate([
  45364. BABYLON.serialize(),
  45365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45366. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45367. __decorate([
  45368. BABYLON.serialize(),
  45369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45370. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45371. __decorate([
  45372. BABYLON.serialize(),
  45373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45374. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45375. __decorate([
  45376. BABYLON.serialize(),
  45377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45378. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45379. __decorate([
  45380. BABYLON.serialize(),
  45381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45382. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45383. __decorate([
  45384. BABYLON.serialize(),
  45385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45386. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45387. __decorate([
  45388. BABYLON.serialize(),
  45389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45390. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45391. __decorate([
  45392. BABYLON.serialize(),
  45393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45394. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45395. __decorate([
  45396. BABYLON.serialize(),
  45397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45398. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45399. __decorate([
  45400. BABYLON.serialize(),
  45401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45402. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45403. __decorate([
  45404. BABYLON.serialize(),
  45405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45406. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45407. __decorate([
  45408. BABYLON.serialize(),
  45409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45410. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45411. __decorate([
  45412. BABYLON.serialize(),
  45413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45414. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45415. __decorate([
  45416. BABYLON.serialize(),
  45417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45418. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45419. __decorate([
  45420. BABYLON.serialize(),
  45421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45422. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45423. __decorate([
  45424. BABYLON.serialize()
  45425. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45426. __decorate([
  45427. BABYLON.serialize()
  45428. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45429. __decorate([
  45430. BABYLON.serialize(),
  45431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45432. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45433. __decorate([
  45434. BABYLON.serialize(),
  45435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45436. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45437. __decorate([
  45438. BABYLON.serialize(),
  45439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45440. ], PBRMaterial.prototype, "useParallax", void 0);
  45441. __decorate([
  45442. BABYLON.serialize(),
  45443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45444. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45445. __decorate([
  45446. BABYLON.serialize(),
  45447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45448. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45449. __decorate([
  45450. BABYLON.serialize(),
  45451. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45452. ], PBRMaterial.prototype, "disableLighting", void 0);
  45453. __decorate([
  45454. BABYLON.serialize(),
  45455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45456. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45457. __decorate([
  45458. BABYLON.serialize(),
  45459. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45460. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45461. __decorate([
  45462. BABYLON.serialize(),
  45463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45464. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45465. __decorate([
  45466. BABYLON.serialize(),
  45467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45468. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45469. __decorate([
  45470. BABYLON.serialize(),
  45471. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45472. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45473. __decorate([
  45474. BABYLON.serialize(),
  45475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45476. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45477. __decorate([
  45478. BABYLON.serialize(),
  45479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45480. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45481. __decorate([
  45482. BABYLON.serializeAsTexture(),
  45483. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45484. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45485. __decorate([
  45486. BABYLON.serialize(),
  45487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45488. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45489. __decorate([
  45490. BABYLON.serialize(),
  45491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45492. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45493. __decorate([
  45494. BABYLON.serialize(),
  45495. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45496. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45497. __decorate([
  45498. BABYLON.serialize(),
  45499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45500. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45501. __decorate([
  45502. BABYLON.serialize(),
  45503. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45504. ], PBRMaterial.prototype, "unlit", void 0);
  45505. return PBRMaterial;
  45506. }(BABYLON.PBRBaseMaterial));
  45507. BABYLON.PBRMaterial = PBRMaterial;
  45508. })(BABYLON || (BABYLON = {}));
  45509. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45510. var BABYLON;
  45511. (function (BABYLON) {
  45512. /**
  45513. * The PBR material of BJS following the metal roughness convention.
  45514. *
  45515. * This fits to the PBR convention in the GLTF definition:
  45516. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45517. */
  45518. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45519. __extends(PBRMetallicRoughnessMaterial, _super);
  45520. /**
  45521. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45522. *
  45523. * @param name The material name
  45524. * @param scene The scene the material will be use in.
  45525. */
  45526. function PBRMetallicRoughnessMaterial(name, scene) {
  45527. var _this = _super.call(this, name, scene) || this;
  45528. _this._useRoughnessFromMetallicTextureAlpha = false;
  45529. _this._useRoughnessFromMetallicTextureGreen = true;
  45530. _this._useMetallnessFromMetallicTextureBlue = true;
  45531. _this.metallic = 1.0;
  45532. _this.roughness = 1.0;
  45533. return _this;
  45534. }
  45535. /**
  45536. * Return the currrent class name of the material.
  45537. */
  45538. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45539. return "PBRMetallicRoughnessMaterial";
  45540. };
  45541. /**
  45542. * Return the active textures of the material.
  45543. */
  45544. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45545. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45546. if (this.baseTexture) {
  45547. activeTextures.push(this.baseTexture);
  45548. }
  45549. if (this.metallicRoughnessTexture) {
  45550. activeTextures.push(this.metallicRoughnessTexture);
  45551. }
  45552. return activeTextures;
  45553. };
  45554. /**
  45555. * Checks to see if a texture is used in the material.
  45556. * @param texture - Base texture to use.
  45557. * @returns - Boolean specifying if a texture is used in the material.
  45558. */
  45559. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45560. if (_super.prototype.hasTexture.call(this, texture)) {
  45561. return true;
  45562. }
  45563. if (this.baseTexture === texture) {
  45564. return true;
  45565. }
  45566. if (this.metallicRoughnessTexture === texture) {
  45567. return true;
  45568. }
  45569. return false;
  45570. };
  45571. /**
  45572. * Makes a duplicate of the current material.
  45573. * @param name - name to use for the new material.
  45574. */
  45575. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45576. var _this = this;
  45577. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45578. clone.id = name;
  45579. clone.name = name;
  45580. return clone;
  45581. };
  45582. /**
  45583. * Serialize the material to a parsable JSON object.
  45584. */
  45585. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45586. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45587. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45588. return serializationObject;
  45589. };
  45590. /**
  45591. * Parses a JSON object correponding to the serialize function.
  45592. */
  45593. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45594. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45595. };
  45596. __decorate([
  45597. BABYLON.serializeAsColor3(),
  45598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45599. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45600. __decorate([
  45601. BABYLON.serializeAsTexture(),
  45602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45603. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45604. __decorate([
  45605. BABYLON.serialize(),
  45606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45607. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45608. __decorate([
  45609. BABYLON.serialize(),
  45610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45611. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45612. __decorate([
  45613. BABYLON.serializeAsTexture(),
  45614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45615. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45616. return PBRMetallicRoughnessMaterial;
  45617. }(BABYLON.PBRBaseSimpleMaterial));
  45618. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45619. })(BABYLON || (BABYLON = {}));
  45620. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45621. var BABYLON;
  45622. (function (BABYLON) {
  45623. /**
  45624. * The PBR material of BJS following the specular glossiness convention.
  45625. *
  45626. * This fits to the PBR convention in the GLTF definition:
  45627. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45628. */
  45629. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45630. __extends(PBRSpecularGlossinessMaterial, _super);
  45631. /**
  45632. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45633. *
  45634. * @param name The material name
  45635. * @param scene The scene the material will be use in.
  45636. */
  45637. function PBRSpecularGlossinessMaterial(name, scene) {
  45638. var _this = _super.call(this, name, scene) || this;
  45639. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45640. return _this;
  45641. }
  45642. /**
  45643. * Return the currrent class name of the material.
  45644. */
  45645. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45646. return "PBRSpecularGlossinessMaterial";
  45647. };
  45648. /**
  45649. * Return the active textures of the material.
  45650. */
  45651. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45652. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45653. if (this.diffuseTexture) {
  45654. activeTextures.push(this.diffuseTexture);
  45655. }
  45656. if (this.specularGlossinessTexture) {
  45657. activeTextures.push(this.specularGlossinessTexture);
  45658. }
  45659. return activeTextures;
  45660. };
  45661. /**
  45662. * Checks to see if a texture is used in the material.
  45663. * @param texture - Base texture to use.
  45664. * @returns - Boolean specifying if a texture is used in the material.
  45665. */
  45666. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45667. if (_super.prototype.hasTexture.call(this, texture)) {
  45668. return true;
  45669. }
  45670. if (this.diffuseTexture === texture) {
  45671. return true;
  45672. }
  45673. if (this.specularGlossinessTexture === texture) {
  45674. return true;
  45675. }
  45676. return false;
  45677. };
  45678. /**
  45679. * Makes a duplicate of the current material.
  45680. * @param name - name to use for the new material.
  45681. */
  45682. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45683. var _this = this;
  45684. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45685. clone.id = name;
  45686. clone.name = name;
  45687. return clone;
  45688. };
  45689. /**
  45690. * Serialize the material to a parsable JSON object.
  45691. */
  45692. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45693. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45694. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45695. return serializationObject;
  45696. };
  45697. /**
  45698. * Parses a JSON object correponding to the serialize function.
  45699. */
  45700. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45701. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45702. };
  45703. __decorate([
  45704. BABYLON.serializeAsColor3("diffuse"),
  45705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45706. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45707. __decorate([
  45708. BABYLON.serializeAsTexture(),
  45709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45710. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45711. __decorate([
  45712. BABYLON.serializeAsColor3("specular"),
  45713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45714. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45715. __decorate([
  45716. BABYLON.serialize(),
  45717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45718. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45719. __decorate([
  45720. BABYLON.serializeAsTexture(),
  45721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45722. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45723. return PBRSpecularGlossinessMaterial;
  45724. }(BABYLON.PBRBaseSimpleMaterial));
  45725. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45726. })(BABYLON || (BABYLON = {}));
  45727. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45728. var BABYLON;
  45729. (function (BABYLON) {
  45730. BABYLON.CameraInputTypes = {};
  45731. var CameraInputsManager = /** @class */ (function () {
  45732. function CameraInputsManager(camera) {
  45733. this.attached = {};
  45734. this.camera = camera;
  45735. this.checkInputs = function () { };
  45736. }
  45737. /**
  45738. * Add an input method to a camera
  45739. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  45740. * @param input camera input method
  45741. */
  45742. CameraInputsManager.prototype.add = function (input) {
  45743. var type = input.getSimpleName();
  45744. if (this.attached[type]) {
  45745. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45746. return;
  45747. }
  45748. this.attached[type] = input;
  45749. input.camera = this.camera;
  45750. //for checkInputs, we are dynamically creating a function
  45751. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45752. if (input.checkInputs) {
  45753. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45754. }
  45755. if (this.attachedElement) {
  45756. input.attachControl(this.attachedElement);
  45757. }
  45758. };
  45759. /**
  45760. * Remove a specific input method from a camera
  45761. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45762. * @param inputToRemove camera input method
  45763. */
  45764. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45765. for (var cam in this.attached) {
  45766. var input = this.attached[cam];
  45767. if (input === inputToRemove) {
  45768. input.detachControl(this.attachedElement);
  45769. input.camera = null;
  45770. delete this.attached[cam];
  45771. this.rebuildInputCheck();
  45772. }
  45773. }
  45774. };
  45775. CameraInputsManager.prototype.removeByType = function (inputType) {
  45776. for (var cam in this.attached) {
  45777. var input = this.attached[cam];
  45778. if (input.getClassName() === inputType) {
  45779. input.detachControl(this.attachedElement);
  45780. input.camera = null;
  45781. delete this.attached[cam];
  45782. this.rebuildInputCheck();
  45783. }
  45784. }
  45785. };
  45786. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45787. var current = this.checkInputs;
  45788. return function () {
  45789. current();
  45790. fn();
  45791. };
  45792. };
  45793. CameraInputsManager.prototype.attachInput = function (input) {
  45794. if (this.attachedElement) {
  45795. input.attachControl(this.attachedElement, this.noPreventDefault);
  45796. }
  45797. };
  45798. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45799. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45800. if (this.attachedElement) {
  45801. return;
  45802. }
  45803. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45804. this.attachedElement = element;
  45805. this.noPreventDefault = noPreventDefault;
  45806. for (var cam in this.attached) {
  45807. this.attached[cam].attachControl(element, noPreventDefault);
  45808. }
  45809. };
  45810. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45811. if (disconnect === void 0) { disconnect = false; }
  45812. if (this.attachedElement !== element) {
  45813. return;
  45814. }
  45815. for (var cam in this.attached) {
  45816. this.attached[cam].detachControl(element);
  45817. if (disconnect) {
  45818. this.attached[cam].camera = null;
  45819. }
  45820. }
  45821. this.attachedElement = null;
  45822. };
  45823. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45824. this.checkInputs = function () { };
  45825. for (var cam in this.attached) {
  45826. var input = this.attached[cam];
  45827. if (input.checkInputs) {
  45828. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45829. }
  45830. }
  45831. };
  45832. /**
  45833. * Remove all attached input methods from a camera
  45834. */
  45835. CameraInputsManager.prototype.clear = function () {
  45836. if (this.attachedElement) {
  45837. this.detachElement(this.attachedElement, true);
  45838. }
  45839. this.attached = {};
  45840. this.attachedElement = null;
  45841. this.checkInputs = function () { };
  45842. };
  45843. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45844. var inputs = {};
  45845. for (var cam in this.attached) {
  45846. var input = this.attached[cam];
  45847. var res = BABYLON.SerializationHelper.Serialize(input);
  45848. inputs[input.getClassName()] = res;
  45849. }
  45850. serializedCamera.inputsmgr = inputs;
  45851. };
  45852. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45853. var parsedInputs = parsedCamera.inputsmgr;
  45854. if (parsedInputs) {
  45855. this.clear();
  45856. for (var n in parsedInputs) {
  45857. var construct = BABYLON.CameraInputTypes[n];
  45858. if (construct) {
  45859. var parsedinput = parsedInputs[n];
  45860. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45861. this.add(input);
  45862. }
  45863. }
  45864. }
  45865. else {
  45866. //2016-03-08 this part is for managing backward compatibility
  45867. for (var n in this.attached) {
  45868. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45869. if (construct) {
  45870. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45871. this.remove(this.attached[n]);
  45872. this.add(input);
  45873. }
  45874. }
  45875. }
  45876. };
  45877. return CameraInputsManager;
  45878. }());
  45879. BABYLON.CameraInputsManager = CameraInputsManager;
  45880. })(BABYLON || (BABYLON = {}));
  45881. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  45882. var BABYLON;
  45883. (function (BABYLON) {
  45884. var TargetCamera = /** @class */ (function (_super) {
  45885. __extends(TargetCamera, _super);
  45886. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  45887. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  45888. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  45889. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45890. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  45891. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  45892. _this.speed = 2.0;
  45893. _this.noRotationConstraint = false;
  45894. _this.lockedTarget = null;
  45895. /** @hidden */
  45896. _this._currentTarget = BABYLON.Vector3.Zero();
  45897. /** @hidden */
  45898. _this._viewMatrix = BABYLON.Matrix.Zero();
  45899. /** @hidden */
  45900. _this._camMatrix = BABYLON.Matrix.Zero();
  45901. /** @hidden */
  45902. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  45903. /** @hidden */
  45904. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  45905. /** @hidden */
  45906. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  45907. /** @hidden */
  45908. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  45909. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  45910. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  45911. _this._defaultUp = BABYLON.Vector3.Up();
  45912. _this._cachedRotationZ = 0;
  45913. return _this;
  45914. }
  45915. TargetCamera.prototype.getFrontPosition = function (distance) {
  45916. this.getWorldMatrix();
  45917. var direction = this.getTarget().subtract(this.position);
  45918. direction.normalize();
  45919. direction.scaleInPlace(distance);
  45920. return this.globalPosition.add(direction);
  45921. };
  45922. /** @hidden */
  45923. TargetCamera.prototype._getLockedTargetPosition = function () {
  45924. if (!this.lockedTarget) {
  45925. return null;
  45926. }
  45927. if (this.lockedTarget.absolutePosition) {
  45928. this.lockedTarget.computeWorldMatrix();
  45929. }
  45930. return this.lockedTarget.absolutePosition || this.lockedTarget;
  45931. };
  45932. TargetCamera.prototype.storeState = function () {
  45933. this._storedPosition = this.position.clone();
  45934. this._storedRotation = this.rotation.clone();
  45935. if (this.rotationQuaternion) {
  45936. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  45937. }
  45938. return _super.prototype.storeState.call(this);
  45939. };
  45940. /**
  45941. * Restored camera state. You must call storeState() first
  45942. * @returns whether it was successful or not
  45943. * @hidden
  45944. */
  45945. TargetCamera.prototype._restoreStateValues = function () {
  45946. if (!_super.prototype._restoreStateValues.call(this)) {
  45947. return false;
  45948. }
  45949. this.position = this._storedPosition.clone();
  45950. this.rotation = this._storedRotation.clone();
  45951. if (this.rotationQuaternion) {
  45952. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  45953. }
  45954. this.cameraDirection.copyFromFloats(0, 0, 0);
  45955. this.cameraRotation.copyFromFloats(0, 0);
  45956. return true;
  45957. };
  45958. // Cache
  45959. /** @hidden */
  45960. TargetCamera.prototype._initCache = function () {
  45961. _super.prototype._initCache.call(this);
  45962. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45963. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45964. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45965. };
  45966. /** @hidden */
  45967. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  45968. if (!ignoreParentClass) {
  45969. _super.prototype._updateCache.call(this);
  45970. }
  45971. var lockedTargetPosition = this._getLockedTargetPosition();
  45972. if (!lockedTargetPosition) {
  45973. this._cache.lockedTarget = null;
  45974. }
  45975. else {
  45976. if (!this._cache.lockedTarget) {
  45977. this._cache.lockedTarget = lockedTargetPosition.clone();
  45978. }
  45979. else {
  45980. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  45981. }
  45982. }
  45983. this._cache.rotation.copyFrom(this.rotation);
  45984. if (this.rotationQuaternion)
  45985. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45986. };
  45987. // Synchronized
  45988. /** @hidden */
  45989. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  45990. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  45991. return false;
  45992. }
  45993. var lockedTargetPosition = this._getLockedTargetPosition();
  45994. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  45995. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  45996. };
  45997. // Methods
  45998. /** @hidden */
  45999. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46000. var engine = this.getEngine();
  46001. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46002. };
  46003. // Target
  46004. /** @hidden */
  46005. TargetCamera.prototype.setTarget = function (target) {
  46006. this.upVector.normalize();
  46007. if (this.position.z === target.z) {
  46008. this.position.z += BABYLON.Epsilon;
  46009. }
  46010. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46011. this._camMatrix.invert();
  46012. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46013. var vDir = target.subtract(this.position);
  46014. if (vDir.x >= 0.0) {
  46015. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46016. }
  46017. else {
  46018. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46019. }
  46020. this.rotation.z = 0;
  46021. if (isNaN(this.rotation.x)) {
  46022. this.rotation.x = 0;
  46023. }
  46024. if (isNaN(this.rotation.y)) {
  46025. this.rotation.y = 0;
  46026. }
  46027. if (isNaN(this.rotation.z)) {
  46028. this.rotation.z = 0;
  46029. }
  46030. if (this.rotationQuaternion) {
  46031. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46032. }
  46033. };
  46034. /**
  46035. * Return the current target position of the camera. This value is expressed in local space.
  46036. */
  46037. TargetCamera.prototype.getTarget = function () {
  46038. return this._currentTarget;
  46039. };
  46040. /** @hidden */
  46041. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46042. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46043. };
  46044. /** @hidden */
  46045. TargetCamera.prototype._updatePosition = function () {
  46046. if (this.parent) {
  46047. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46048. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46049. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46050. return;
  46051. }
  46052. this.position.addInPlace(this.cameraDirection);
  46053. };
  46054. /** @hidden */
  46055. TargetCamera.prototype._checkInputs = function () {
  46056. var needToMove = this._decideIfNeedsToMove();
  46057. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46058. // Move
  46059. if (needToMove) {
  46060. this._updatePosition();
  46061. }
  46062. // Rotate
  46063. if (needToRotate) {
  46064. this.rotation.x += this.cameraRotation.x;
  46065. this.rotation.y += this.cameraRotation.y;
  46066. //rotate, if quaternion is set and rotation was used
  46067. if (this.rotationQuaternion) {
  46068. var len = this.rotation.lengthSquared();
  46069. if (len) {
  46070. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46071. }
  46072. }
  46073. if (!this.noRotationConstraint) {
  46074. var limit = (Math.PI / 2) * 0.95;
  46075. if (this.rotation.x > limit)
  46076. this.rotation.x = limit;
  46077. if (this.rotation.x < -limit)
  46078. this.rotation.x = -limit;
  46079. }
  46080. }
  46081. // Inertia
  46082. if (needToMove) {
  46083. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46084. this.cameraDirection.x = 0;
  46085. }
  46086. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46087. this.cameraDirection.y = 0;
  46088. }
  46089. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46090. this.cameraDirection.z = 0;
  46091. }
  46092. this.cameraDirection.scaleInPlace(this.inertia);
  46093. }
  46094. if (needToRotate) {
  46095. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46096. this.cameraRotation.x = 0;
  46097. }
  46098. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46099. this.cameraRotation.y = 0;
  46100. }
  46101. this.cameraRotation.scaleInPlace(this.inertia);
  46102. }
  46103. _super.prototype._checkInputs.call(this);
  46104. };
  46105. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46106. if (this.rotationQuaternion) {
  46107. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46108. }
  46109. else {
  46110. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46111. }
  46112. };
  46113. /**
  46114. * 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)
  46115. * @returns the current camera
  46116. */
  46117. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46118. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46119. return this;
  46120. };
  46121. /** @hidden */
  46122. TargetCamera.prototype._getViewMatrix = function () {
  46123. if (this.lockedTarget) {
  46124. this.setTarget(this._getLockedTargetPosition());
  46125. }
  46126. // Compute
  46127. this._updateCameraRotationMatrix();
  46128. // Apply the changed rotation to the upVector.
  46129. if (this._cachedRotationZ != this.rotation.z) {
  46130. this._rotateUpVectorWithCameraRotationMatrix();
  46131. this._cachedRotationZ = this.rotation.z;
  46132. }
  46133. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46134. // Computing target and final matrix
  46135. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46136. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46137. return this._viewMatrix;
  46138. };
  46139. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46140. if (this.parent) {
  46141. var parentWorldMatrix = this.parent.getWorldMatrix();
  46142. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46143. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46144. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46145. this._markSyncedWithParent();
  46146. }
  46147. else {
  46148. this._globalPosition.copyFrom(position);
  46149. this._globalCurrentTarget.copyFrom(target);
  46150. this._globalCurrentUpVector.copyFrom(up);
  46151. }
  46152. if (this.getScene().useRightHandedSystem) {
  46153. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46154. }
  46155. else {
  46156. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46157. }
  46158. };
  46159. /**
  46160. * @override
  46161. * Override Camera.createRigCamera
  46162. */
  46163. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46164. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46165. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46166. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46167. if (!this.rotationQuaternion) {
  46168. this.rotationQuaternion = new BABYLON.Quaternion();
  46169. }
  46170. rigCamera._cameraRigParams = {};
  46171. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46172. }
  46173. return rigCamera;
  46174. }
  46175. return null;
  46176. };
  46177. /**
  46178. * @hidden
  46179. * @override
  46180. * Override Camera._updateRigCameras
  46181. */
  46182. TargetCamera.prototype._updateRigCameras = function () {
  46183. var camLeft = this._rigCameras[0];
  46184. var camRight = this._rigCameras[1];
  46185. switch (this.cameraRigMode) {
  46186. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46187. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46188. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46189. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46190. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46191. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46192. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46193. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46194. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46195. camLeft.setTarget(this.getTarget());
  46196. camRight.setTarget(this.getTarget());
  46197. break;
  46198. case BABYLON.Camera.RIG_MODE_VR:
  46199. if (camLeft.rotationQuaternion) {
  46200. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46201. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46202. }
  46203. else {
  46204. camLeft.rotation.copyFrom(this.rotation);
  46205. camRight.rotation.copyFrom(this.rotation);
  46206. }
  46207. camLeft.position.copyFrom(this.position);
  46208. camRight.position.copyFrom(this.position);
  46209. break;
  46210. }
  46211. _super.prototype._updateRigCameras.call(this);
  46212. };
  46213. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46214. if (!this._rigCamTransformMatrix) {
  46215. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46216. }
  46217. var target = this.getTarget();
  46218. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46219. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46220. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46221. };
  46222. TargetCamera.prototype.getClassName = function () {
  46223. return "TargetCamera";
  46224. };
  46225. __decorate([
  46226. BABYLON.serializeAsVector3()
  46227. ], TargetCamera.prototype, "rotation", void 0);
  46228. __decorate([
  46229. BABYLON.serialize()
  46230. ], TargetCamera.prototype, "speed", void 0);
  46231. __decorate([
  46232. BABYLON.serializeAsMeshReference("lockedTargetId")
  46233. ], TargetCamera.prototype, "lockedTarget", void 0);
  46234. return TargetCamera;
  46235. }(BABYLON.Camera));
  46236. BABYLON.TargetCamera = TargetCamera;
  46237. })(BABYLON || (BABYLON = {}));
  46238. //# sourceMappingURL=babylon.targetCamera.js.map
  46239. var BABYLON;
  46240. (function (BABYLON) {
  46241. var FreeCameraMouseInput = /** @class */ (function () {
  46242. function FreeCameraMouseInput(touchEnabled) {
  46243. if (touchEnabled === void 0) { touchEnabled = true; }
  46244. this.touchEnabled = touchEnabled;
  46245. this.buttons = [0, 1, 2];
  46246. this.angularSensibility = 2000.0;
  46247. this.previousPosition = null;
  46248. }
  46249. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46250. var _this = this;
  46251. var engine = this.camera.getEngine();
  46252. if (!this._pointerInput) {
  46253. this._pointerInput = function (p, s) {
  46254. var evt = p.event;
  46255. if (engine.isInVRExclusivePointerMode) {
  46256. return;
  46257. }
  46258. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46259. return;
  46260. }
  46261. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46262. return;
  46263. }
  46264. var srcElement = (evt.srcElement || evt.target);
  46265. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46266. try {
  46267. srcElement.setPointerCapture(evt.pointerId);
  46268. }
  46269. catch (e) {
  46270. //Nothing to do with the error. Execution will continue.
  46271. }
  46272. _this.previousPosition = {
  46273. x: evt.clientX,
  46274. y: evt.clientY
  46275. };
  46276. if (!noPreventDefault) {
  46277. evt.preventDefault();
  46278. element.focus();
  46279. }
  46280. }
  46281. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46282. try {
  46283. srcElement.releasePointerCapture(evt.pointerId);
  46284. }
  46285. catch (e) {
  46286. //Nothing to do with the error.
  46287. }
  46288. _this.previousPosition = null;
  46289. if (!noPreventDefault) {
  46290. evt.preventDefault();
  46291. }
  46292. }
  46293. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46294. if (!_this.previousPosition || engine.isPointerLock) {
  46295. return;
  46296. }
  46297. var offsetX = evt.clientX - _this.previousPosition.x;
  46298. if (_this.camera.getScene().useRightHandedSystem)
  46299. offsetX *= -1;
  46300. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46301. offsetX *= -1;
  46302. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46303. var offsetY = evt.clientY - _this.previousPosition.y;
  46304. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46305. _this.previousPosition = {
  46306. x: evt.clientX,
  46307. y: evt.clientY
  46308. };
  46309. if (!noPreventDefault) {
  46310. evt.preventDefault();
  46311. }
  46312. }
  46313. };
  46314. }
  46315. this._onMouseMove = function (evt) {
  46316. if (!engine.isPointerLock) {
  46317. return;
  46318. }
  46319. if (engine.isInVRExclusivePointerMode) {
  46320. return;
  46321. }
  46322. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46323. if (_this.camera.getScene().useRightHandedSystem)
  46324. offsetX *= -1;
  46325. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46326. offsetX *= -1;
  46327. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46328. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46329. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46330. _this.previousPosition = null;
  46331. if (!noPreventDefault) {
  46332. evt.preventDefault();
  46333. }
  46334. };
  46335. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46336. element.addEventListener("mousemove", this._onMouseMove, false);
  46337. };
  46338. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46339. if (this._observer && element) {
  46340. this.camera.getScene().onPointerObservable.remove(this._observer);
  46341. if (this._onMouseMove) {
  46342. element.removeEventListener("mousemove", this._onMouseMove);
  46343. }
  46344. this._observer = null;
  46345. this._onMouseMove = null;
  46346. this.previousPosition = null;
  46347. }
  46348. };
  46349. FreeCameraMouseInput.prototype.getClassName = function () {
  46350. return "FreeCameraMouseInput";
  46351. };
  46352. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46353. return "mouse";
  46354. };
  46355. __decorate([
  46356. BABYLON.serialize()
  46357. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46358. __decorate([
  46359. BABYLON.serialize()
  46360. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46361. return FreeCameraMouseInput;
  46362. }());
  46363. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46364. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46365. })(BABYLON || (BABYLON = {}));
  46366. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46367. var BABYLON;
  46368. (function (BABYLON) {
  46369. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46370. function FreeCameraKeyboardMoveInput() {
  46371. this._keys = new Array();
  46372. this.keysUp = [38];
  46373. this.keysDown = [40];
  46374. this.keysLeft = [37];
  46375. this.keysRight = [39];
  46376. }
  46377. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46378. var _this = this;
  46379. if (this._onCanvasBlurObserver) {
  46380. return;
  46381. }
  46382. this._scene = this.camera.getScene();
  46383. this._engine = this._scene.getEngine();
  46384. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46385. _this._keys = [];
  46386. });
  46387. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46388. var evt = info.event;
  46389. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46390. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46391. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46392. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46393. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46394. var index = _this._keys.indexOf(evt.keyCode);
  46395. if (index === -1) {
  46396. _this._keys.push(evt.keyCode);
  46397. }
  46398. if (!noPreventDefault) {
  46399. evt.preventDefault();
  46400. }
  46401. }
  46402. }
  46403. else {
  46404. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46405. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46406. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46407. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46408. var index = _this._keys.indexOf(evt.keyCode);
  46409. if (index >= 0) {
  46410. _this._keys.splice(index, 1);
  46411. }
  46412. if (!noPreventDefault) {
  46413. evt.preventDefault();
  46414. }
  46415. }
  46416. }
  46417. });
  46418. };
  46419. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46420. if (this._scene) {
  46421. if (this._onKeyboardObserver) {
  46422. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46423. }
  46424. if (this._onCanvasBlurObserver) {
  46425. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46426. }
  46427. this._onKeyboardObserver = null;
  46428. this._onCanvasBlurObserver = null;
  46429. }
  46430. this._keys = [];
  46431. };
  46432. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46433. if (this._onKeyboardObserver) {
  46434. var camera = this.camera;
  46435. // Keyboard
  46436. for (var index = 0; index < this._keys.length; index++) {
  46437. var keyCode = this._keys[index];
  46438. var speed = camera._computeLocalCameraSpeed();
  46439. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46440. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46441. }
  46442. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46443. camera._localDirection.copyFromFloats(0, 0, speed);
  46444. }
  46445. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46446. camera._localDirection.copyFromFloats(speed, 0, 0);
  46447. }
  46448. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46449. camera._localDirection.copyFromFloats(0, 0, -speed);
  46450. }
  46451. if (camera.getScene().useRightHandedSystem) {
  46452. camera._localDirection.z *= -1;
  46453. }
  46454. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46455. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46456. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46457. }
  46458. }
  46459. };
  46460. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46461. return "FreeCameraKeyboardMoveInput";
  46462. };
  46463. /** @hidden */
  46464. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46465. this._keys = [];
  46466. };
  46467. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46468. return "keyboard";
  46469. };
  46470. __decorate([
  46471. BABYLON.serialize()
  46472. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46473. __decorate([
  46474. BABYLON.serialize()
  46475. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46476. __decorate([
  46477. BABYLON.serialize()
  46478. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46479. __decorate([
  46480. BABYLON.serialize()
  46481. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46482. return FreeCameraKeyboardMoveInput;
  46483. }());
  46484. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46485. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46486. })(BABYLON || (BABYLON = {}));
  46487. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46488. var BABYLON;
  46489. (function (BABYLON) {
  46490. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46491. __extends(FreeCameraInputsManager, _super);
  46492. function FreeCameraInputsManager(camera) {
  46493. return _super.call(this, camera) || this;
  46494. }
  46495. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46496. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46497. return this;
  46498. };
  46499. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46500. if (touchEnabled === void 0) { touchEnabled = true; }
  46501. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46502. return this;
  46503. };
  46504. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46505. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46506. return this;
  46507. };
  46508. FreeCameraInputsManager.prototype.addTouch = function () {
  46509. this.add(new BABYLON.FreeCameraTouchInput());
  46510. return this;
  46511. };
  46512. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46513. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46514. return this;
  46515. };
  46516. return FreeCameraInputsManager;
  46517. }(BABYLON.CameraInputsManager));
  46518. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46519. })(BABYLON || (BABYLON = {}));
  46520. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46521. var BABYLON;
  46522. (function (BABYLON) {
  46523. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46524. // Forcing to use the Universal camera
  46525. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46526. });
  46527. var FreeCamera = /** @class */ (function (_super) {
  46528. __extends(FreeCamera, _super);
  46529. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46530. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46531. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46532. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46533. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46534. _this.checkCollisions = false;
  46535. _this.applyGravity = false;
  46536. _this._needMoveForGravity = false;
  46537. _this._oldPosition = BABYLON.Vector3.Zero();
  46538. _this._diffPosition = BABYLON.Vector3.Zero();
  46539. _this._newPosition = BABYLON.Vector3.Zero();
  46540. // Collisions
  46541. _this._collisionMask = -1;
  46542. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46543. if (collidedMesh === void 0) { collidedMesh = null; }
  46544. //TODO move this to the collision coordinator!
  46545. if (_this.getScene().workerCollisions)
  46546. newPosition.multiplyInPlace(_this._collider._radius);
  46547. var updatePosition = function (newPos) {
  46548. _this._newPosition.copyFrom(newPos);
  46549. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46550. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46551. _this.position.addInPlace(_this._diffPosition);
  46552. if (_this.onCollide && collidedMesh) {
  46553. _this.onCollide(collidedMesh);
  46554. }
  46555. }
  46556. };
  46557. updatePosition(newPosition);
  46558. };
  46559. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46560. _this.inputs.addKeyboard().addMouse();
  46561. return _this;
  46562. }
  46563. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46564. //-- begin properties for backward compatibility for inputs
  46565. /**
  46566. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46567. * Higher values reduce sensitivity.
  46568. */
  46569. get: function () {
  46570. var mouse = this.inputs.attached["mouse"];
  46571. if (mouse)
  46572. return mouse.angularSensibility;
  46573. return 0;
  46574. },
  46575. /**
  46576. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46577. * Higher values reduce sensitivity.
  46578. */
  46579. set: function (value) {
  46580. var mouse = this.inputs.attached["mouse"];
  46581. if (mouse)
  46582. mouse.angularSensibility = value;
  46583. },
  46584. enumerable: true,
  46585. configurable: true
  46586. });
  46587. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46588. get: function () {
  46589. var keyboard = this.inputs.attached["keyboard"];
  46590. if (keyboard)
  46591. return keyboard.keysUp;
  46592. return [];
  46593. },
  46594. set: function (value) {
  46595. var keyboard = this.inputs.attached["keyboard"];
  46596. if (keyboard)
  46597. keyboard.keysUp = value;
  46598. },
  46599. enumerable: true,
  46600. configurable: true
  46601. });
  46602. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46603. get: function () {
  46604. var keyboard = this.inputs.attached["keyboard"];
  46605. if (keyboard)
  46606. return keyboard.keysDown;
  46607. return [];
  46608. },
  46609. set: function (value) {
  46610. var keyboard = this.inputs.attached["keyboard"];
  46611. if (keyboard)
  46612. keyboard.keysDown = value;
  46613. },
  46614. enumerable: true,
  46615. configurable: true
  46616. });
  46617. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46618. get: function () {
  46619. var keyboard = this.inputs.attached["keyboard"];
  46620. if (keyboard)
  46621. return keyboard.keysLeft;
  46622. return [];
  46623. },
  46624. set: function (value) {
  46625. var keyboard = this.inputs.attached["keyboard"];
  46626. if (keyboard)
  46627. keyboard.keysLeft = value;
  46628. },
  46629. enumerable: true,
  46630. configurable: true
  46631. });
  46632. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46633. get: function () {
  46634. var keyboard = this.inputs.attached["keyboard"];
  46635. if (keyboard)
  46636. return keyboard.keysRight;
  46637. return [];
  46638. },
  46639. set: function (value) {
  46640. var keyboard = this.inputs.attached["keyboard"];
  46641. if (keyboard)
  46642. keyboard.keysRight = value;
  46643. },
  46644. enumerable: true,
  46645. configurable: true
  46646. });
  46647. // Controls
  46648. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46649. this.inputs.attachElement(element, noPreventDefault);
  46650. };
  46651. FreeCamera.prototype.detachControl = function (element) {
  46652. this.inputs.detachElement(element);
  46653. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46654. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46655. };
  46656. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46657. get: function () {
  46658. return this._collisionMask;
  46659. },
  46660. set: function (mask) {
  46661. this._collisionMask = !isNaN(mask) ? mask : -1;
  46662. },
  46663. enumerable: true,
  46664. configurable: true
  46665. });
  46666. /** @hidden */
  46667. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46668. var globalPosition;
  46669. if (this.parent) {
  46670. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46671. }
  46672. else {
  46673. globalPosition = this.position;
  46674. }
  46675. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46676. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46677. if (!this._collider) {
  46678. this._collider = new BABYLON.Collider();
  46679. }
  46680. this._collider._radius = this.ellipsoid;
  46681. this._collider.collisionMask = this._collisionMask;
  46682. //no need for clone, as long as gravity is not on.
  46683. var actualDisplacement = displacement;
  46684. //add gravity to the direction to prevent the dual-collision checking
  46685. if (this.applyGravity) {
  46686. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46687. actualDisplacement = displacement.add(this.getScene().gravity);
  46688. }
  46689. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46690. };
  46691. /** @hidden */
  46692. FreeCamera.prototype._checkInputs = function () {
  46693. if (!this._localDirection) {
  46694. this._localDirection = BABYLON.Vector3.Zero();
  46695. this._transformedDirection = BABYLON.Vector3.Zero();
  46696. }
  46697. this.inputs.checkInputs();
  46698. _super.prototype._checkInputs.call(this);
  46699. };
  46700. /** @hidden */
  46701. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46702. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46703. };
  46704. /** @hidden */
  46705. FreeCamera.prototype._updatePosition = function () {
  46706. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46707. this._collideWithWorld(this.cameraDirection);
  46708. }
  46709. else {
  46710. _super.prototype._updatePosition.call(this);
  46711. }
  46712. };
  46713. FreeCamera.prototype.dispose = function () {
  46714. this.inputs.clear();
  46715. _super.prototype.dispose.call(this);
  46716. };
  46717. FreeCamera.prototype.getClassName = function () {
  46718. return "FreeCamera";
  46719. };
  46720. __decorate([
  46721. BABYLON.serializeAsVector3()
  46722. ], FreeCamera.prototype, "ellipsoid", void 0);
  46723. __decorate([
  46724. BABYLON.serializeAsVector3()
  46725. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46726. __decorate([
  46727. BABYLON.serialize()
  46728. ], FreeCamera.prototype, "checkCollisions", void 0);
  46729. __decorate([
  46730. BABYLON.serialize()
  46731. ], FreeCamera.prototype, "applyGravity", void 0);
  46732. return FreeCamera;
  46733. }(BABYLON.TargetCamera));
  46734. BABYLON.FreeCamera = FreeCamera;
  46735. })(BABYLON || (BABYLON = {}));
  46736. //# sourceMappingURL=babylon.freeCamera.js.map
  46737. var BABYLON;
  46738. (function (BABYLON) {
  46739. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46740. function ArcRotateCameraKeyboardMoveInput() {
  46741. this._keys = new Array();
  46742. this.keysUp = [38];
  46743. this.keysDown = [40];
  46744. this.keysLeft = [37];
  46745. this.keysRight = [39];
  46746. this.keysReset = [220];
  46747. this.panningSensibility = 50.0;
  46748. this.zoomingSensibility = 25.0;
  46749. this.useAltToZoom = true;
  46750. }
  46751. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46752. var _this = this;
  46753. if (this._onCanvasBlurObserver) {
  46754. return;
  46755. }
  46756. this._scene = this.camera.getScene();
  46757. this._engine = this._scene.getEngine();
  46758. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46759. _this._keys = [];
  46760. });
  46761. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46762. var evt = info.event;
  46763. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46764. _this._ctrlPressed = evt.ctrlKey;
  46765. _this._altPressed = evt.altKey;
  46766. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46767. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46768. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46769. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46770. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46771. var index = _this._keys.indexOf(evt.keyCode);
  46772. if (index === -1) {
  46773. _this._keys.push(evt.keyCode);
  46774. }
  46775. if (evt.preventDefault) {
  46776. if (!noPreventDefault) {
  46777. evt.preventDefault();
  46778. }
  46779. }
  46780. }
  46781. }
  46782. else {
  46783. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46784. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46785. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46786. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46787. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46788. var index = _this._keys.indexOf(evt.keyCode);
  46789. if (index >= 0) {
  46790. _this._keys.splice(index, 1);
  46791. }
  46792. if (evt.preventDefault) {
  46793. if (!noPreventDefault) {
  46794. evt.preventDefault();
  46795. }
  46796. }
  46797. }
  46798. }
  46799. });
  46800. };
  46801. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46802. if (this._scene) {
  46803. if (this._onKeyboardObserver) {
  46804. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46805. }
  46806. if (this._onCanvasBlurObserver) {
  46807. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46808. }
  46809. this._onKeyboardObserver = null;
  46810. this._onCanvasBlurObserver = null;
  46811. }
  46812. this._keys = [];
  46813. };
  46814. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46815. if (this._onKeyboardObserver) {
  46816. var camera = this.camera;
  46817. for (var index = 0; index < this._keys.length; index++) {
  46818. var keyCode = this._keys[index];
  46819. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46820. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46821. camera.inertialPanningX -= 1 / this.panningSensibility;
  46822. }
  46823. else {
  46824. camera.inertialAlphaOffset -= 0.01;
  46825. }
  46826. }
  46827. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46828. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46829. camera.inertialPanningY += 1 / this.panningSensibility;
  46830. }
  46831. else if (this._altPressed && this.useAltToZoom) {
  46832. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46833. }
  46834. else {
  46835. camera.inertialBetaOffset -= 0.01;
  46836. }
  46837. }
  46838. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46839. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46840. camera.inertialPanningX += 1 / this.panningSensibility;
  46841. }
  46842. else {
  46843. camera.inertialAlphaOffset += 0.01;
  46844. }
  46845. }
  46846. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46847. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46848. camera.inertialPanningY -= 1 / this.panningSensibility;
  46849. }
  46850. else if (this._altPressed && this.useAltToZoom) {
  46851. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46852. }
  46853. else {
  46854. camera.inertialBetaOffset += 0.01;
  46855. }
  46856. }
  46857. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46858. camera.restoreState();
  46859. }
  46860. }
  46861. }
  46862. };
  46863. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46864. return "ArcRotateCameraKeyboardMoveInput";
  46865. };
  46866. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46867. return "keyboard";
  46868. };
  46869. __decorate([
  46870. BABYLON.serialize()
  46871. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46872. __decorate([
  46873. BABYLON.serialize()
  46874. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46875. __decorate([
  46876. BABYLON.serialize()
  46877. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46878. __decorate([
  46879. BABYLON.serialize()
  46880. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46881. __decorate([
  46882. BABYLON.serialize()
  46883. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46884. __decorate([
  46885. BABYLON.serialize()
  46886. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46887. __decorate([
  46888. BABYLON.serialize()
  46889. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46890. __decorate([
  46891. BABYLON.serialize()
  46892. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46893. return ArcRotateCameraKeyboardMoveInput;
  46894. }());
  46895. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46896. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46897. })(BABYLON || (BABYLON = {}));
  46898. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46899. var BABYLON;
  46900. (function (BABYLON) {
  46901. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46902. function ArcRotateCameraMouseWheelInput() {
  46903. this.wheelPrecision = 3.0;
  46904. /**
  46905. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46906. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46907. */
  46908. this.wheelDeltaPercentage = 0;
  46909. }
  46910. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46911. var _this = this;
  46912. this._wheel = function (p, s) {
  46913. //sanity check - this should be a PointerWheel event.
  46914. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46915. return;
  46916. var event = p.event;
  46917. var delta = 0;
  46918. if (event.wheelDelta) {
  46919. if (_this.wheelDeltaPercentage) {
  46920. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  46921. if (event.wheelDelta > 0) {
  46922. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  46923. }
  46924. else {
  46925. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  46926. }
  46927. }
  46928. else {
  46929. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  46930. }
  46931. }
  46932. else if (event.detail) {
  46933. delta = -event.detail / _this.wheelPrecision;
  46934. }
  46935. if (delta)
  46936. _this.camera.inertialRadiusOffset += delta;
  46937. if (event.preventDefault) {
  46938. if (!noPreventDefault) {
  46939. event.preventDefault();
  46940. }
  46941. }
  46942. };
  46943. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  46944. };
  46945. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  46946. if (this._observer && element) {
  46947. this.camera.getScene().onPointerObservable.remove(this._observer);
  46948. this._observer = null;
  46949. this._wheel = null;
  46950. }
  46951. };
  46952. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  46953. return "ArcRotateCameraMouseWheelInput";
  46954. };
  46955. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  46956. return "mousewheel";
  46957. };
  46958. __decorate([
  46959. BABYLON.serialize()
  46960. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  46961. __decorate([
  46962. BABYLON.serialize()
  46963. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  46964. return ArcRotateCameraMouseWheelInput;
  46965. }());
  46966. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  46967. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  46968. })(BABYLON || (BABYLON = {}));
  46969. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  46970. var BABYLON;
  46971. (function (BABYLON) {
  46972. var ArcRotateCameraPointersInput = /** @class */ (function () {
  46973. function ArcRotateCameraPointersInput() {
  46974. this.buttons = [0, 1, 2];
  46975. this.angularSensibilityX = 1000.0;
  46976. this.angularSensibilityY = 1000.0;
  46977. this.pinchPrecision = 12.0;
  46978. /**
  46979. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  46980. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  46981. */
  46982. this.pinchDeltaPercentage = 0;
  46983. this.panningSensibility = 1000.0;
  46984. this.multiTouchPanning = true;
  46985. this.multiTouchPanAndZoom = true;
  46986. this._isPanClick = false;
  46987. this.pinchInwards = true;
  46988. }
  46989. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  46990. var _this = this;
  46991. var engine = this.camera.getEngine();
  46992. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  46993. var pointA = null;
  46994. var pointB = null;
  46995. var previousPinchSquaredDistance = 0;
  46996. var initialDistance = 0;
  46997. var twoFingerActivityCount = 0;
  46998. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  46999. this._pointerInput = function (p, s) {
  47000. var evt = p.event;
  47001. var isTouch = p.event.pointerType === "touch";
  47002. if (engine.isInVRExclusivePointerMode) {
  47003. return;
  47004. }
  47005. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47006. return;
  47007. }
  47008. var srcElement = (evt.srcElement || evt.target);
  47009. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47010. try {
  47011. srcElement.setPointerCapture(evt.pointerId);
  47012. }
  47013. catch (e) {
  47014. //Nothing to do with the error. Execution will continue.
  47015. }
  47016. // Manage panning with pan button click
  47017. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47018. // manage pointers
  47019. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47020. if (pointA === null) {
  47021. pointA = cacheSoloPointer;
  47022. }
  47023. else if (pointB === null) {
  47024. pointB = cacheSoloPointer;
  47025. }
  47026. if (!noPreventDefault) {
  47027. evt.preventDefault();
  47028. element.focus();
  47029. }
  47030. }
  47031. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47032. _this.camera.restoreState();
  47033. }
  47034. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47035. try {
  47036. srcElement.releasePointerCapture(evt.pointerId);
  47037. }
  47038. catch (e) {
  47039. //Nothing to do with the error.
  47040. }
  47041. cacheSoloPointer = null;
  47042. previousPinchSquaredDistance = 0;
  47043. previousMultiTouchPanPosition.isPaning = false;
  47044. previousMultiTouchPanPosition.isPinching = false;
  47045. twoFingerActivityCount = 0;
  47046. initialDistance = 0;
  47047. if (!isTouch) {
  47048. pointB = null; // Mouse and pen are mono pointer
  47049. }
  47050. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47051. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47052. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47053. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47054. if (engine._badOS) {
  47055. pointA = pointB = null;
  47056. }
  47057. else {
  47058. //only remove the impacted pointer in case of multitouch allowing on most
  47059. //platforms switching from rotate to zoom and pan seamlessly.
  47060. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47061. pointA = pointB;
  47062. pointB = null;
  47063. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47064. }
  47065. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47066. pointB = null;
  47067. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47068. }
  47069. else {
  47070. pointA = pointB = null;
  47071. }
  47072. }
  47073. if (!noPreventDefault) {
  47074. evt.preventDefault();
  47075. }
  47076. }
  47077. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47078. if (!noPreventDefault) {
  47079. evt.preventDefault();
  47080. }
  47081. // One button down
  47082. if (pointA && pointB === null && cacheSoloPointer) {
  47083. if (_this.panningSensibility !== 0 &&
  47084. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47085. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47086. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47087. }
  47088. else {
  47089. var offsetX = evt.clientX - cacheSoloPointer.x;
  47090. var offsetY = evt.clientY - cacheSoloPointer.y;
  47091. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47092. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47093. }
  47094. cacheSoloPointer.x = evt.clientX;
  47095. cacheSoloPointer.y = evt.clientY;
  47096. }
  47097. // Two buttons down: pinch/pan
  47098. else if (pointA && pointB) {
  47099. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47100. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47101. ed.x = evt.clientX;
  47102. ed.y = evt.clientY;
  47103. var direction = _this.pinchInwards ? 1 : -1;
  47104. var distX = pointA.x - pointB.x;
  47105. var distY = pointA.y - pointB.y;
  47106. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47107. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47108. if (previousPinchSquaredDistance === 0) {
  47109. initialDistance = pinchDistance;
  47110. previousPinchSquaredDistance = pinchSquaredDistance;
  47111. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47112. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47113. return;
  47114. }
  47115. if (_this.multiTouchPanAndZoom) {
  47116. if (_this.pinchDeltaPercentage) {
  47117. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47118. }
  47119. else {
  47120. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47121. (_this.pinchPrecision *
  47122. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47123. direction);
  47124. }
  47125. if (_this.panningSensibility !== 0) {
  47126. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47127. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47128. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47129. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47130. previousMultiTouchPanPosition.x = pointersCenterX;
  47131. previousMultiTouchPanPosition.y = pointersCenterY;
  47132. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47133. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47134. }
  47135. }
  47136. else {
  47137. twoFingerActivityCount++;
  47138. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47139. if (_this.pinchDeltaPercentage) {
  47140. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47141. }
  47142. else {
  47143. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47144. (_this.pinchPrecision *
  47145. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47146. direction);
  47147. }
  47148. previousMultiTouchPanPosition.isPaning = false;
  47149. previousMultiTouchPanPosition.isPinching = true;
  47150. }
  47151. else {
  47152. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47153. if (!previousMultiTouchPanPosition.isPaning) {
  47154. previousMultiTouchPanPosition.isPaning = true;
  47155. previousMultiTouchPanPosition.isPinching = false;
  47156. previousMultiTouchPanPosition.x = ed.x;
  47157. previousMultiTouchPanPosition.y = ed.y;
  47158. return;
  47159. }
  47160. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47161. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47162. }
  47163. }
  47164. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47165. previousMultiTouchPanPosition.x = ed.x;
  47166. previousMultiTouchPanPosition.y = ed.y;
  47167. }
  47168. }
  47169. previousPinchSquaredDistance = pinchSquaredDistance;
  47170. }
  47171. }
  47172. };
  47173. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47174. this._onContextMenu = function (evt) {
  47175. evt.preventDefault();
  47176. };
  47177. if (!this.camera._useCtrlForPanning) {
  47178. element.addEventListener("contextmenu", this._onContextMenu, false);
  47179. }
  47180. this._onLostFocus = function () {
  47181. //this._keys = [];
  47182. pointA = pointB = null;
  47183. previousPinchSquaredDistance = 0;
  47184. previousMultiTouchPanPosition.isPaning = false;
  47185. previousMultiTouchPanPosition.isPinching = false;
  47186. twoFingerActivityCount = 0;
  47187. cacheSoloPointer = null;
  47188. initialDistance = 0;
  47189. };
  47190. this._onMouseMove = function (evt) {
  47191. if (!engine.isPointerLock) {
  47192. return;
  47193. }
  47194. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47195. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47196. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47197. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47198. if (!noPreventDefault) {
  47199. evt.preventDefault();
  47200. }
  47201. };
  47202. this._onGestureStart = function (e) {
  47203. if (window.MSGesture === undefined) {
  47204. return;
  47205. }
  47206. if (!_this._MSGestureHandler) {
  47207. _this._MSGestureHandler = new MSGesture();
  47208. _this._MSGestureHandler.target = element;
  47209. }
  47210. _this._MSGestureHandler.addPointer(e.pointerId);
  47211. };
  47212. this._onGesture = function (e) {
  47213. _this.camera.radius *= e.scale;
  47214. if (e.preventDefault) {
  47215. if (!noPreventDefault) {
  47216. e.stopPropagation();
  47217. e.preventDefault();
  47218. }
  47219. }
  47220. };
  47221. element.addEventListener("mousemove", this._onMouseMove, false);
  47222. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47223. element.addEventListener("MSGestureChange", this._onGesture, false);
  47224. BABYLON.Tools.RegisterTopRootEvents([
  47225. { name: "blur", handler: this._onLostFocus }
  47226. ]);
  47227. };
  47228. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47229. if (this._onLostFocus) {
  47230. BABYLON.Tools.UnregisterTopRootEvents([
  47231. { name: "blur", handler: this._onLostFocus }
  47232. ]);
  47233. }
  47234. if (element && this._observer) {
  47235. this.camera.getScene().onPointerObservable.remove(this._observer);
  47236. this._observer = null;
  47237. if (this._onContextMenu) {
  47238. element.removeEventListener("contextmenu", this._onContextMenu);
  47239. }
  47240. if (this._onMouseMove) {
  47241. element.removeEventListener("mousemove", this._onMouseMove);
  47242. }
  47243. if (this._onGestureStart) {
  47244. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47245. }
  47246. if (this._onGesture) {
  47247. element.removeEventListener("MSGestureChange", this._onGesture);
  47248. }
  47249. this._isPanClick = false;
  47250. this.pinchInwards = true;
  47251. this._onMouseMove = null;
  47252. this._onGestureStart = null;
  47253. this._onGesture = null;
  47254. this._MSGestureHandler = null;
  47255. this._onLostFocus = null;
  47256. this._onContextMenu = null;
  47257. }
  47258. };
  47259. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47260. return "ArcRotateCameraPointersInput";
  47261. };
  47262. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47263. return "pointers";
  47264. };
  47265. __decorate([
  47266. BABYLON.serialize()
  47267. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47268. __decorate([
  47269. BABYLON.serialize()
  47270. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47271. __decorate([
  47272. BABYLON.serialize()
  47273. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47274. __decorate([
  47275. BABYLON.serialize()
  47276. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47277. __decorate([
  47278. BABYLON.serialize()
  47279. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47280. __decorate([
  47281. BABYLON.serialize()
  47282. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47283. __decorate([
  47284. BABYLON.serialize()
  47285. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47286. __decorate([
  47287. BABYLON.serialize()
  47288. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47289. return ArcRotateCameraPointersInput;
  47290. }());
  47291. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47292. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47293. })(BABYLON || (BABYLON = {}));
  47294. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47295. var BABYLON;
  47296. (function (BABYLON) {
  47297. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47298. __extends(ArcRotateCameraInputsManager, _super);
  47299. function ArcRotateCameraInputsManager(camera) {
  47300. return _super.call(this, camera) || this;
  47301. }
  47302. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47303. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47304. return this;
  47305. };
  47306. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47307. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47308. return this;
  47309. };
  47310. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47311. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47312. return this;
  47313. };
  47314. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47315. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47316. return this;
  47317. };
  47318. return ArcRotateCameraInputsManager;
  47319. }(BABYLON.CameraInputsManager));
  47320. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47321. })(BABYLON || (BABYLON = {}));
  47322. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47323. var BABYLON;
  47324. (function (BABYLON) {
  47325. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47326. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47327. });
  47328. var ArcRotateCamera = /** @class */ (function (_super) {
  47329. __extends(ArcRotateCamera, _super);
  47330. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47331. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47332. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47333. _this.inertialAlphaOffset = 0;
  47334. _this.inertialBetaOffset = 0;
  47335. _this.inertialRadiusOffset = 0;
  47336. _this.lowerAlphaLimit = null;
  47337. _this.upperAlphaLimit = null;
  47338. _this.lowerBetaLimit = 0.01;
  47339. _this.upperBetaLimit = Math.PI;
  47340. _this.lowerRadiusLimit = null;
  47341. _this.upperRadiusLimit = null;
  47342. _this.inertialPanningX = 0;
  47343. _this.inertialPanningY = 0;
  47344. _this.pinchToPanMaxDistance = 20;
  47345. _this.panningDistanceLimit = null;
  47346. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47347. _this.panningInertia = 0.9;
  47348. //-- end properties for backward compatibility for inputs
  47349. _this.zoomOnFactor = 1;
  47350. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47351. _this.allowUpsideDown = true;
  47352. /** @hidden */
  47353. _this._viewMatrix = new BABYLON.Matrix();
  47354. // Panning
  47355. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47356. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47357. _this.checkCollisions = false;
  47358. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47359. _this._previousPosition = BABYLON.Vector3.Zero();
  47360. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47361. _this._newPosition = BABYLON.Vector3.Zero();
  47362. _this._computationVector = BABYLON.Vector3.Zero();
  47363. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47364. if (collidedMesh === void 0) { collidedMesh = null; }
  47365. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47366. newPosition.multiplyInPlace(_this._collider._radius);
  47367. }
  47368. if (!collidedMesh) {
  47369. _this._previousPosition.copyFrom(_this.position);
  47370. }
  47371. else {
  47372. _this.setPosition(newPosition);
  47373. if (_this.onCollide) {
  47374. _this.onCollide(collidedMesh);
  47375. }
  47376. }
  47377. // Recompute because of constraints
  47378. var cosa = Math.cos(_this.alpha);
  47379. var sina = Math.sin(_this.alpha);
  47380. var cosb = Math.cos(_this.beta);
  47381. var sinb = Math.sin(_this.beta);
  47382. if (sinb === 0) {
  47383. sinb = 0.0001;
  47384. }
  47385. var target = _this._getTargetPosition();
  47386. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47387. target.addToRef(_this._computationVector, _this._newPosition);
  47388. _this.position.copyFrom(_this._newPosition);
  47389. var up = _this.upVector;
  47390. if (_this.allowUpsideDown && _this.beta < 0) {
  47391. up = up.clone();
  47392. up = up.negate();
  47393. }
  47394. _this._computeViewMatrix(_this.position, target, up);
  47395. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47396. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47397. _this._collisionTriggered = false;
  47398. };
  47399. _this._target = BABYLON.Vector3.Zero();
  47400. if (target) {
  47401. _this.setTarget(target);
  47402. }
  47403. _this.alpha = alpha;
  47404. _this.beta = beta;
  47405. _this.radius = radius;
  47406. _this.getViewMatrix();
  47407. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47408. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47409. return _this;
  47410. }
  47411. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47412. get: function () {
  47413. return this._target;
  47414. },
  47415. set: function (value) {
  47416. this.setTarget(value);
  47417. },
  47418. enumerable: true,
  47419. configurable: true
  47420. });
  47421. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47422. //-- begin properties for backward compatibility for inputs
  47423. get: function () {
  47424. var pointers = this.inputs.attached["pointers"];
  47425. if (pointers)
  47426. return pointers.angularSensibilityX;
  47427. return 0;
  47428. },
  47429. set: function (value) {
  47430. var pointers = this.inputs.attached["pointers"];
  47431. if (pointers) {
  47432. pointers.angularSensibilityX = value;
  47433. }
  47434. },
  47435. enumerable: true,
  47436. configurable: true
  47437. });
  47438. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47439. get: function () {
  47440. var pointers = this.inputs.attached["pointers"];
  47441. if (pointers)
  47442. return pointers.angularSensibilityY;
  47443. return 0;
  47444. },
  47445. set: function (value) {
  47446. var pointers = this.inputs.attached["pointers"];
  47447. if (pointers) {
  47448. pointers.angularSensibilityY = value;
  47449. }
  47450. },
  47451. enumerable: true,
  47452. configurable: true
  47453. });
  47454. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47455. get: function () {
  47456. var pointers = this.inputs.attached["pointers"];
  47457. if (pointers)
  47458. return pointers.pinchPrecision;
  47459. return 0;
  47460. },
  47461. set: function (value) {
  47462. var pointers = this.inputs.attached["pointers"];
  47463. if (pointers) {
  47464. pointers.pinchPrecision = value;
  47465. }
  47466. },
  47467. enumerable: true,
  47468. configurable: true
  47469. });
  47470. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47471. get: function () {
  47472. var pointers = this.inputs.attached["pointers"];
  47473. if (pointers)
  47474. return pointers.pinchDeltaPercentage;
  47475. return 0;
  47476. },
  47477. set: function (value) {
  47478. var pointers = this.inputs.attached["pointers"];
  47479. if (pointers) {
  47480. pointers.pinchDeltaPercentage = value;
  47481. }
  47482. },
  47483. enumerable: true,
  47484. configurable: true
  47485. });
  47486. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47487. get: function () {
  47488. var pointers = this.inputs.attached["pointers"];
  47489. if (pointers)
  47490. return pointers.panningSensibility;
  47491. return 0;
  47492. },
  47493. set: function (value) {
  47494. var pointers = this.inputs.attached["pointers"];
  47495. if (pointers) {
  47496. pointers.panningSensibility = value;
  47497. }
  47498. },
  47499. enumerable: true,
  47500. configurable: true
  47501. });
  47502. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47503. get: function () {
  47504. var keyboard = this.inputs.attached["keyboard"];
  47505. if (keyboard)
  47506. return keyboard.keysUp;
  47507. return [];
  47508. },
  47509. set: function (value) {
  47510. var keyboard = this.inputs.attached["keyboard"];
  47511. if (keyboard)
  47512. keyboard.keysUp = value;
  47513. },
  47514. enumerable: true,
  47515. configurable: true
  47516. });
  47517. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47518. get: function () {
  47519. var keyboard = this.inputs.attached["keyboard"];
  47520. if (keyboard)
  47521. return keyboard.keysDown;
  47522. return [];
  47523. },
  47524. set: function (value) {
  47525. var keyboard = this.inputs.attached["keyboard"];
  47526. if (keyboard)
  47527. keyboard.keysDown = value;
  47528. },
  47529. enumerable: true,
  47530. configurable: true
  47531. });
  47532. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47533. get: function () {
  47534. var keyboard = this.inputs.attached["keyboard"];
  47535. if (keyboard)
  47536. return keyboard.keysLeft;
  47537. return [];
  47538. },
  47539. set: function (value) {
  47540. var keyboard = this.inputs.attached["keyboard"];
  47541. if (keyboard)
  47542. keyboard.keysLeft = value;
  47543. },
  47544. enumerable: true,
  47545. configurable: true
  47546. });
  47547. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47548. get: function () {
  47549. var keyboard = this.inputs.attached["keyboard"];
  47550. if (keyboard)
  47551. return keyboard.keysRight;
  47552. return [];
  47553. },
  47554. set: function (value) {
  47555. var keyboard = this.inputs.attached["keyboard"];
  47556. if (keyboard)
  47557. keyboard.keysRight = value;
  47558. },
  47559. enumerable: true,
  47560. configurable: true
  47561. });
  47562. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47563. get: function () {
  47564. var mousewheel = this.inputs.attached["mousewheel"];
  47565. if (mousewheel)
  47566. return mousewheel.wheelPrecision;
  47567. return 0;
  47568. },
  47569. set: function (value) {
  47570. var mousewheel = this.inputs.attached["mousewheel"];
  47571. if (mousewheel)
  47572. mousewheel.wheelPrecision = value;
  47573. },
  47574. enumerable: true,
  47575. configurable: true
  47576. });
  47577. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47578. get: function () {
  47579. var mousewheel = this.inputs.attached["mousewheel"];
  47580. if (mousewheel)
  47581. return mousewheel.wheelDeltaPercentage;
  47582. return 0;
  47583. },
  47584. set: function (value) {
  47585. var mousewheel = this.inputs.attached["mousewheel"];
  47586. if (mousewheel)
  47587. mousewheel.wheelDeltaPercentage = value;
  47588. },
  47589. enumerable: true,
  47590. configurable: true
  47591. });
  47592. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47593. get: function () {
  47594. return this._bouncingBehavior;
  47595. },
  47596. enumerable: true,
  47597. configurable: true
  47598. });
  47599. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47600. get: function () {
  47601. return this._bouncingBehavior != null;
  47602. },
  47603. set: function (value) {
  47604. if (value === this.useBouncingBehavior) {
  47605. return;
  47606. }
  47607. if (value) {
  47608. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47609. this.addBehavior(this._bouncingBehavior);
  47610. }
  47611. else if (this._bouncingBehavior) {
  47612. this.removeBehavior(this._bouncingBehavior);
  47613. this._bouncingBehavior = null;
  47614. }
  47615. },
  47616. enumerable: true,
  47617. configurable: true
  47618. });
  47619. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47620. get: function () {
  47621. return this._framingBehavior;
  47622. },
  47623. enumerable: true,
  47624. configurable: true
  47625. });
  47626. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47627. get: function () {
  47628. return this._framingBehavior != null;
  47629. },
  47630. set: function (value) {
  47631. if (value === this.useFramingBehavior) {
  47632. return;
  47633. }
  47634. if (value) {
  47635. this._framingBehavior = new BABYLON.FramingBehavior();
  47636. this.addBehavior(this._framingBehavior);
  47637. }
  47638. else if (this._framingBehavior) {
  47639. this.removeBehavior(this._framingBehavior);
  47640. this._framingBehavior = null;
  47641. }
  47642. },
  47643. enumerable: true,
  47644. configurable: true
  47645. });
  47646. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47647. get: function () {
  47648. return this._autoRotationBehavior;
  47649. },
  47650. enumerable: true,
  47651. configurable: true
  47652. });
  47653. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47654. get: function () {
  47655. return this._autoRotationBehavior != null;
  47656. },
  47657. set: function (value) {
  47658. if (value === this.useAutoRotationBehavior) {
  47659. return;
  47660. }
  47661. if (value) {
  47662. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47663. this.addBehavior(this._autoRotationBehavior);
  47664. }
  47665. else if (this._autoRotationBehavior) {
  47666. this.removeBehavior(this._autoRotationBehavior);
  47667. this._autoRotationBehavior = null;
  47668. }
  47669. },
  47670. enumerable: true,
  47671. configurable: true
  47672. });
  47673. // Cache
  47674. /** @hidden */
  47675. ArcRotateCamera.prototype._initCache = function () {
  47676. _super.prototype._initCache.call(this);
  47677. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47678. this._cache.alpha = undefined;
  47679. this._cache.beta = undefined;
  47680. this._cache.radius = undefined;
  47681. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47682. };
  47683. /** @hidden */
  47684. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47685. if (!ignoreParentClass) {
  47686. _super.prototype._updateCache.call(this);
  47687. }
  47688. this._cache._target.copyFrom(this._getTargetPosition());
  47689. this._cache.alpha = this.alpha;
  47690. this._cache.beta = this.beta;
  47691. this._cache.radius = this.radius;
  47692. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47693. };
  47694. ArcRotateCamera.prototype._getTargetPosition = function () {
  47695. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47696. var pos = this._targetHost.getAbsolutePosition();
  47697. if (this._targetBoundingCenter) {
  47698. pos.addToRef(this._targetBoundingCenter, this._target);
  47699. }
  47700. else {
  47701. this._target.copyFrom(pos);
  47702. }
  47703. }
  47704. var lockedTargetPosition = this._getLockedTargetPosition();
  47705. if (lockedTargetPosition) {
  47706. return lockedTargetPosition;
  47707. }
  47708. return this._target;
  47709. };
  47710. ArcRotateCamera.prototype.storeState = function () {
  47711. this._storedAlpha = this.alpha;
  47712. this._storedBeta = this.beta;
  47713. this._storedRadius = this.radius;
  47714. this._storedTarget = this._getTargetPosition().clone();
  47715. return _super.prototype.storeState.call(this);
  47716. };
  47717. /**
  47718. * @hidden
  47719. * Restored camera state. You must call storeState() first
  47720. */
  47721. ArcRotateCamera.prototype._restoreStateValues = function () {
  47722. if (!_super.prototype._restoreStateValues.call(this)) {
  47723. return false;
  47724. }
  47725. this.alpha = this._storedAlpha;
  47726. this.beta = this._storedBeta;
  47727. this.radius = this._storedRadius;
  47728. this.setTarget(this._storedTarget.clone());
  47729. this.inertialAlphaOffset = 0;
  47730. this.inertialBetaOffset = 0;
  47731. this.inertialRadiusOffset = 0;
  47732. this.inertialPanningX = 0;
  47733. this.inertialPanningY = 0;
  47734. return true;
  47735. };
  47736. // Synchronized
  47737. /** @hidden */
  47738. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47739. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47740. return false;
  47741. return this._cache._target.equals(this._getTargetPosition())
  47742. && this._cache.alpha === this.alpha
  47743. && this._cache.beta === this.beta
  47744. && this._cache.radius === this.radius
  47745. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47746. };
  47747. // Methods
  47748. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47749. var _this = this;
  47750. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47751. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47752. this._useCtrlForPanning = useCtrlForPanning;
  47753. this._panningMouseButton = panningMouseButton;
  47754. this.inputs.attachElement(element, noPreventDefault);
  47755. this._reset = function () {
  47756. _this.inertialAlphaOffset = 0;
  47757. _this.inertialBetaOffset = 0;
  47758. _this.inertialRadiusOffset = 0;
  47759. _this.inertialPanningX = 0;
  47760. _this.inertialPanningY = 0;
  47761. };
  47762. };
  47763. ArcRotateCamera.prototype.detachControl = function (element) {
  47764. this.inputs.detachElement(element);
  47765. if (this._reset) {
  47766. this._reset();
  47767. }
  47768. };
  47769. /** @hidden */
  47770. ArcRotateCamera.prototype._checkInputs = function () {
  47771. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47772. if (this._collisionTriggered) {
  47773. return;
  47774. }
  47775. this.inputs.checkInputs();
  47776. // Inertia
  47777. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47778. var inertialAlphaOffset = this.inertialAlphaOffset;
  47779. if (this.beta <= 0)
  47780. inertialAlphaOffset *= -1;
  47781. if (this.getScene().useRightHandedSystem)
  47782. inertialAlphaOffset *= -1;
  47783. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47784. inertialAlphaOffset *= -1;
  47785. this.alpha += inertialAlphaOffset;
  47786. this.beta += this.inertialBetaOffset;
  47787. this.radius -= this.inertialRadiusOffset;
  47788. this.inertialAlphaOffset *= this.inertia;
  47789. this.inertialBetaOffset *= this.inertia;
  47790. this.inertialRadiusOffset *= this.inertia;
  47791. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47792. this.inertialAlphaOffset = 0;
  47793. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47794. this.inertialBetaOffset = 0;
  47795. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47796. this.inertialRadiusOffset = 0;
  47797. }
  47798. // Panning inertia
  47799. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47800. if (!this._localDirection) {
  47801. this._localDirection = BABYLON.Vector3.Zero();
  47802. this._transformedDirection = BABYLON.Vector3.Zero();
  47803. }
  47804. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47805. this._localDirection.multiplyInPlace(this.panningAxis);
  47806. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47807. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47808. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47809. if (!this.panningAxis.y) {
  47810. this._transformedDirection.y = 0;
  47811. }
  47812. if (!this._targetHost) {
  47813. if (this.panningDistanceLimit) {
  47814. this._transformedDirection.addInPlace(this._target);
  47815. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47816. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47817. this._target.copyFrom(this._transformedDirection);
  47818. }
  47819. }
  47820. else {
  47821. this._target.addInPlace(this._transformedDirection);
  47822. }
  47823. }
  47824. this.inertialPanningX *= this.panningInertia;
  47825. this.inertialPanningY *= this.panningInertia;
  47826. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47827. this.inertialPanningX = 0;
  47828. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47829. this.inertialPanningY = 0;
  47830. }
  47831. // Limits
  47832. this._checkLimits();
  47833. _super.prototype._checkInputs.call(this);
  47834. };
  47835. ArcRotateCamera.prototype._checkLimits = function () {
  47836. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47837. if (this.allowUpsideDown && this.beta > Math.PI) {
  47838. this.beta = this.beta - (2 * Math.PI);
  47839. }
  47840. }
  47841. else {
  47842. if (this.beta < this.lowerBetaLimit) {
  47843. this.beta = this.lowerBetaLimit;
  47844. }
  47845. }
  47846. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47847. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47848. this.beta = this.beta + (2 * Math.PI);
  47849. }
  47850. }
  47851. else {
  47852. if (this.beta > this.upperBetaLimit) {
  47853. this.beta = this.upperBetaLimit;
  47854. }
  47855. }
  47856. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  47857. this.alpha = this.lowerAlphaLimit;
  47858. }
  47859. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  47860. this.alpha = this.upperAlphaLimit;
  47861. }
  47862. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  47863. this.radius = this.lowerRadiusLimit;
  47864. }
  47865. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  47866. this.radius = this.upperRadiusLimit;
  47867. }
  47868. };
  47869. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47870. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47871. this.radius = this._computationVector.length();
  47872. if (this.radius === 0) {
  47873. this.radius = 0.0001; // Just to avoid division by zero
  47874. }
  47875. // Alpha
  47876. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47877. if (this._computationVector.z < 0) {
  47878. this.alpha = 2 * Math.PI - this.alpha;
  47879. }
  47880. // Beta
  47881. this.beta = Math.acos(this._computationVector.y / this.radius);
  47882. this._checkLimits();
  47883. };
  47884. ArcRotateCamera.prototype.setPosition = function (position) {
  47885. if (this.position.equals(position)) {
  47886. return;
  47887. }
  47888. this.position.copyFrom(position);
  47889. this.rebuildAnglesAndRadius();
  47890. };
  47891. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47892. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47893. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47894. if (target.getBoundingInfo) {
  47895. if (toBoundingCenter) {
  47896. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47897. }
  47898. else {
  47899. this._targetBoundingCenter = null;
  47900. }
  47901. this._targetHost = target;
  47902. this._target = this._getTargetPosition();
  47903. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47904. }
  47905. else {
  47906. var newTarget = target;
  47907. var currentTarget = this._getTargetPosition();
  47908. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47909. return;
  47910. }
  47911. this._targetHost = null;
  47912. this._target = newTarget;
  47913. this._targetBoundingCenter = null;
  47914. this.onMeshTargetChangedObservable.notifyObservers(null);
  47915. }
  47916. this.rebuildAnglesAndRadius();
  47917. };
  47918. /** @hidden */
  47919. ArcRotateCamera.prototype._getViewMatrix = function () {
  47920. // Compute
  47921. var cosa = Math.cos(this.alpha);
  47922. var sina = Math.sin(this.alpha);
  47923. var cosb = Math.cos(this.beta);
  47924. var sinb = Math.sin(this.beta);
  47925. if (sinb === 0) {
  47926. sinb = 0.0001;
  47927. }
  47928. var target = this._getTargetPosition();
  47929. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  47930. target.addToRef(this._computationVector, this._newPosition);
  47931. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  47932. if (!this._collider) {
  47933. this._collider = new BABYLON.Collider();
  47934. }
  47935. this._collider._radius = this.collisionRadius;
  47936. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  47937. this._collisionTriggered = true;
  47938. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47939. }
  47940. else {
  47941. this.position.copyFrom(this._newPosition);
  47942. var up = this.upVector;
  47943. if (this.allowUpsideDown && sinb < 0) {
  47944. up = up.clone();
  47945. up = up.negate();
  47946. }
  47947. this._computeViewMatrix(this.position, target, up);
  47948. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  47949. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  47950. }
  47951. this._currentTarget = target;
  47952. return this._viewMatrix;
  47953. };
  47954. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  47955. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47956. meshes = meshes || this.getScene().meshes;
  47957. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  47958. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  47959. this.radius = distance * this.zoomOnFactor;
  47960. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  47961. };
  47962. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  47963. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47964. var meshesOrMinMaxVector;
  47965. var distance;
  47966. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  47967. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  47968. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  47969. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  47970. }
  47971. else { //minMaxVector and distance
  47972. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  47973. meshesOrMinMaxVector = minMaxVectorAndDistance;
  47974. distance = minMaxVectorAndDistance.distance;
  47975. }
  47976. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  47977. if (!doNotUpdateMaxZ) {
  47978. this.maxZ = distance * 2;
  47979. }
  47980. };
  47981. /**
  47982. * @override
  47983. * Override Camera.createRigCamera
  47984. */
  47985. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47986. var alphaShift = 0;
  47987. switch (this.cameraRigMode) {
  47988. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47989. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47990. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47991. case BABYLON.Camera.RIG_MODE_VR:
  47992. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  47993. break;
  47994. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47995. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  47996. break;
  47997. }
  47998. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  47999. rigCam._cameraRigParams = {};
  48000. return rigCam;
  48001. };
  48002. /**
  48003. * @hidden
  48004. * @override
  48005. * Override Camera._updateRigCameras
  48006. */
  48007. ArcRotateCamera.prototype._updateRigCameras = function () {
  48008. var camLeft = this._rigCameras[0];
  48009. var camRight = this._rigCameras[1];
  48010. camLeft.beta = camRight.beta = this.beta;
  48011. camLeft.radius = camRight.radius = this.radius;
  48012. switch (this.cameraRigMode) {
  48013. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48014. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48015. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48016. case BABYLON.Camera.RIG_MODE_VR:
  48017. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48018. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48019. break;
  48020. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48021. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48022. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48023. break;
  48024. }
  48025. _super.prototype._updateRigCameras.call(this);
  48026. };
  48027. ArcRotateCamera.prototype.dispose = function () {
  48028. this.inputs.clear();
  48029. _super.prototype.dispose.call(this);
  48030. };
  48031. ArcRotateCamera.prototype.getClassName = function () {
  48032. return "ArcRotateCamera";
  48033. };
  48034. __decorate([
  48035. BABYLON.serialize()
  48036. ], ArcRotateCamera.prototype, "alpha", void 0);
  48037. __decorate([
  48038. BABYLON.serialize()
  48039. ], ArcRotateCamera.prototype, "beta", void 0);
  48040. __decorate([
  48041. BABYLON.serialize()
  48042. ], ArcRotateCamera.prototype, "radius", void 0);
  48043. __decorate([
  48044. BABYLON.serializeAsVector3("target")
  48045. ], ArcRotateCamera.prototype, "_target", void 0);
  48046. __decorate([
  48047. BABYLON.serialize()
  48048. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48049. __decorate([
  48050. BABYLON.serialize()
  48051. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48052. __decorate([
  48053. BABYLON.serialize()
  48054. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48055. __decorate([
  48056. BABYLON.serialize()
  48057. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48058. __decorate([
  48059. BABYLON.serialize()
  48060. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48061. __decorate([
  48062. BABYLON.serialize()
  48063. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48064. __decorate([
  48065. BABYLON.serialize()
  48066. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48067. __decorate([
  48068. BABYLON.serialize()
  48069. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48070. __decorate([
  48071. BABYLON.serialize()
  48072. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48073. __decorate([
  48074. BABYLON.serialize()
  48075. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48076. __decorate([
  48077. BABYLON.serialize()
  48078. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48079. __decorate([
  48080. BABYLON.serialize()
  48081. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48082. __decorate([
  48083. BABYLON.serialize()
  48084. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48085. __decorate([
  48086. BABYLON.serializeAsVector3()
  48087. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48088. __decorate([
  48089. BABYLON.serialize()
  48090. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48091. __decorate([
  48092. BABYLON.serialize()
  48093. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48094. __decorate([
  48095. BABYLON.serialize()
  48096. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48097. return ArcRotateCamera;
  48098. }(BABYLON.TargetCamera));
  48099. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48100. })(BABYLON || (BABYLON = {}));
  48101. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48102. var BABYLON;
  48103. (function (BABYLON) {
  48104. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48105. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48106. });
  48107. /**
  48108. * The HemisphericLight simulates the ambient environment light,
  48109. * so the passed direction is the light reflection direction, not the incoming direction.
  48110. */
  48111. var HemisphericLight = /** @class */ (function (_super) {
  48112. __extends(HemisphericLight, _super);
  48113. /**
  48114. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48115. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48116. * The HemisphericLight can't cast shadows.
  48117. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48118. * @param name The friendly name of the light
  48119. * @param direction The direction of the light reflection
  48120. * @param scene The scene the light belongs to
  48121. */
  48122. function HemisphericLight(name, direction, scene) {
  48123. var _this = _super.call(this, name, scene) || this;
  48124. /**
  48125. * The groundColor is the light in the opposite direction to the one specified during creation.
  48126. * 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.
  48127. */
  48128. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48129. _this.direction = direction || BABYLON.Vector3.Up();
  48130. return _this;
  48131. }
  48132. HemisphericLight.prototype._buildUniformLayout = function () {
  48133. this._uniformBuffer.addUniform("vLightData", 4);
  48134. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48135. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48136. this._uniformBuffer.addUniform("vLightGround", 3);
  48137. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48138. this._uniformBuffer.addUniform("depthValues", 2);
  48139. this._uniformBuffer.create();
  48140. };
  48141. /**
  48142. * Returns the string "HemisphericLight".
  48143. * @return The class name
  48144. */
  48145. HemisphericLight.prototype.getClassName = function () {
  48146. return "HemisphericLight";
  48147. };
  48148. /**
  48149. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48150. * Returns the updated direction.
  48151. * @param target The target the direction should point to
  48152. * @return The computed direction
  48153. */
  48154. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48155. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48156. return this.direction;
  48157. };
  48158. /**
  48159. * Returns the shadow generator associated to the light.
  48160. * @returns Always null for hemispheric lights because it does not support shadows.
  48161. */
  48162. HemisphericLight.prototype.getShadowGenerator = function () {
  48163. return null;
  48164. };
  48165. /**
  48166. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48167. * @param effect The effect to update
  48168. * @param lightIndex The index of the light in the effect to update
  48169. * @returns The hemispheric light
  48170. */
  48171. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48172. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48173. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48174. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48175. return this;
  48176. };
  48177. /**
  48178. * Computes the world matrix of the node
  48179. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  48180. * @param useWasUpdatedFlag defines a reserved property
  48181. * @returns the world matrix
  48182. */
  48183. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  48184. if (!this._worldMatrix) {
  48185. this._worldMatrix = BABYLON.Matrix.Identity();
  48186. }
  48187. return this._worldMatrix;
  48188. };
  48189. /**
  48190. * Returns the integer 3.
  48191. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48192. */
  48193. HemisphericLight.prototype.getTypeID = function () {
  48194. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48195. };
  48196. /**
  48197. * Prepares the list of defines specific to the light type.
  48198. * @param defines the list of defines
  48199. * @param lightIndex defines the index of the light for the effect
  48200. */
  48201. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48202. defines["HEMILIGHT" + lightIndex] = true;
  48203. };
  48204. __decorate([
  48205. BABYLON.serializeAsColor3()
  48206. ], HemisphericLight.prototype, "groundColor", void 0);
  48207. __decorate([
  48208. BABYLON.serializeAsVector3()
  48209. ], HemisphericLight.prototype, "direction", void 0);
  48210. return HemisphericLight;
  48211. }(BABYLON.Light));
  48212. BABYLON.HemisphericLight = HemisphericLight;
  48213. })(BABYLON || (BABYLON = {}));
  48214. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48215. var BABYLON;
  48216. (function (BABYLON) {
  48217. /**
  48218. * Base implementation IShadowLight
  48219. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48220. */
  48221. var ShadowLight = /** @class */ (function (_super) {
  48222. __extends(ShadowLight, _super);
  48223. function ShadowLight() {
  48224. var _this = _super !== null && _super.apply(this, arguments) || this;
  48225. _this._needProjectionMatrixCompute = true;
  48226. return _this;
  48227. }
  48228. ShadowLight.prototype._setPosition = function (value) {
  48229. this._position = value;
  48230. };
  48231. Object.defineProperty(ShadowLight.prototype, "position", {
  48232. /**
  48233. * Sets the position the shadow will be casted from. Also use as the light position for both
  48234. * point and spot lights.
  48235. */
  48236. get: function () {
  48237. return this._position;
  48238. },
  48239. /**
  48240. * Sets the position the shadow will be casted from. Also use as the light position for both
  48241. * point and spot lights.
  48242. */
  48243. set: function (value) {
  48244. this._setPosition(value);
  48245. },
  48246. enumerable: true,
  48247. configurable: true
  48248. });
  48249. ShadowLight.prototype._setDirection = function (value) {
  48250. this._direction = value;
  48251. };
  48252. Object.defineProperty(ShadowLight.prototype, "direction", {
  48253. /**
  48254. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48255. * Also use as the light direction on spot and directional lights.
  48256. */
  48257. get: function () {
  48258. return this._direction;
  48259. },
  48260. /**
  48261. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48262. * Also use as the light direction on spot and directional lights.
  48263. */
  48264. set: function (value) {
  48265. this._setDirection(value);
  48266. },
  48267. enumerable: true,
  48268. configurable: true
  48269. });
  48270. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48271. /**
  48272. * Gets the shadow projection clipping minimum z value.
  48273. */
  48274. get: function () {
  48275. return this._shadowMinZ;
  48276. },
  48277. /**
  48278. * Sets the shadow projection clipping minimum z value.
  48279. */
  48280. set: function (value) {
  48281. this._shadowMinZ = value;
  48282. this.forceProjectionMatrixCompute();
  48283. },
  48284. enumerable: true,
  48285. configurable: true
  48286. });
  48287. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48288. /**
  48289. * Sets the shadow projection clipping maximum z value.
  48290. */
  48291. get: function () {
  48292. return this._shadowMaxZ;
  48293. },
  48294. /**
  48295. * Gets the shadow projection clipping maximum z value.
  48296. */
  48297. set: function (value) {
  48298. this._shadowMaxZ = value;
  48299. this.forceProjectionMatrixCompute();
  48300. },
  48301. enumerable: true,
  48302. configurable: true
  48303. });
  48304. /**
  48305. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48306. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48307. */
  48308. ShadowLight.prototype.computeTransformedInformation = function () {
  48309. if (this.parent && this.parent.getWorldMatrix) {
  48310. if (!this.transformedPosition) {
  48311. this.transformedPosition = BABYLON.Vector3.Zero();
  48312. }
  48313. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48314. // In case the direction is present.
  48315. if (this.direction) {
  48316. if (!this.transformedDirection) {
  48317. this.transformedDirection = BABYLON.Vector3.Zero();
  48318. }
  48319. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48320. }
  48321. return true;
  48322. }
  48323. return false;
  48324. };
  48325. /**
  48326. * Return the depth scale used for the shadow map.
  48327. * @returns the depth scale.
  48328. */
  48329. ShadowLight.prototype.getDepthScale = function () {
  48330. return 50.0;
  48331. };
  48332. /**
  48333. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48334. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48335. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48336. */
  48337. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48338. return this.transformedDirection ? this.transformedDirection : this.direction;
  48339. };
  48340. /**
  48341. * Returns the ShadowLight absolute position in the World.
  48342. * @returns the position vector in world space
  48343. */
  48344. ShadowLight.prototype.getAbsolutePosition = function () {
  48345. return this.transformedPosition ? this.transformedPosition : this.position;
  48346. };
  48347. /**
  48348. * Sets the ShadowLight direction toward the passed target.
  48349. * @param target The point tot target in local space
  48350. * @returns the updated ShadowLight direction
  48351. */
  48352. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48353. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48354. return this.direction;
  48355. };
  48356. /**
  48357. * Returns the light rotation in euler definition.
  48358. * @returns the x y z rotation in local space.
  48359. */
  48360. ShadowLight.prototype.getRotation = function () {
  48361. this.direction.normalize();
  48362. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48363. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48364. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48365. };
  48366. /**
  48367. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48368. * @returns true if a cube texture needs to be use
  48369. */
  48370. ShadowLight.prototype.needCube = function () {
  48371. return false;
  48372. };
  48373. /**
  48374. * Detects if the projection matrix requires to be recomputed this frame.
  48375. * @returns true if it requires to be recomputed otherwise, false.
  48376. */
  48377. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48378. return this._needProjectionMatrixCompute;
  48379. };
  48380. /**
  48381. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48382. */
  48383. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48384. this._needProjectionMatrixCompute = true;
  48385. };
  48386. /** @hidden */
  48387. ShadowLight.prototype._initCache = function () {
  48388. _super.prototype._initCache.call(this);
  48389. this._cache.position = BABYLON.Vector3.Zero();
  48390. };
  48391. /** @hidden */
  48392. ShadowLight.prototype._isSynchronized = function () {
  48393. if (!this._cache.position.equals(this.position))
  48394. return false;
  48395. return true;
  48396. };
  48397. /**
  48398. * Computes the world matrix of the node
  48399. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  48400. * @returns the world matrix
  48401. */
  48402. ShadowLight.prototype.computeWorldMatrix = function (force) {
  48403. if (!force && this.isSynchronized()) {
  48404. this._currentRenderId = this.getScene().getRenderId();
  48405. return this._worldMatrix;
  48406. }
  48407. this._updateCache();
  48408. this._cache.position.copyFrom(this.position);
  48409. if (!this._worldMatrix) {
  48410. this._worldMatrix = BABYLON.Matrix.Identity();
  48411. }
  48412. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48413. if (this.parent && this.parent.getWorldMatrix) {
  48414. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  48415. this._markSyncedWithParent();
  48416. }
  48417. // Cache the determinant
  48418. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  48419. return this._worldMatrix;
  48420. };
  48421. /**
  48422. * Gets the minZ used for shadow according to both the scene and the light.
  48423. * @param activeCamera The camera we are returning the min for
  48424. * @returns the depth min z
  48425. */
  48426. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48427. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48428. };
  48429. /**
  48430. * Gets the maxZ used for shadow according to both the scene and the light.
  48431. * @param activeCamera The camera we are returning the max for
  48432. * @returns the depth max z
  48433. */
  48434. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48435. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48436. };
  48437. /**
  48438. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48439. * @param matrix The materix to updated with the projection information
  48440. * @param viewMatrix The transform matrix of the light
  48441. * @param renderList The list of mesh to render in the map
  48442. * @returns The current light
  48443. */
  48444. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48445. if (this.customProjectionMatrixBuilder) {
  48446. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48447. }
  48448. else {
  48449. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48450. }
  48451. return this;
  48452. };
  48453. __decorate([
  48454. BABYLON.serializeAsVector3()
  48455. ], ShadowLight.prototype, "position", null);
  48456. __decorate([
  48457. BABYLON.serializeAsVector3()
  48458. ], ShadowLight.prototype, "direction", null);
  48459. __decorate([
  48460. BABYLON.serialize()
  48461. ], ShadowLight.prototype, "shadowMinZ", null);
  48462. __decorate([
  48463. BABYLON.serialize()
  48464. ], ShadowLight.prototype, "shadowMaxZ", null);
  48465. return ShadowLight;
  48466. }(BABYLON.Light));
  48467. BABYLON.ShadowLight = ShadowLight;
  48468. })(BABYLON || (BABYLON = {}));
  48469. //# sourceMappingURL=babylon.shadowLight.js.map
  48470. var BABYLON;
  48471. (function (BABYLON) {
  48472. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48473. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48474. });
  48475. /**
  48476. * A point light is a light defined by an unique point in world space.
  48477. * The light is emitted in every direction from this point.
  48478. * A good example of a point light is a standard light bulb.
  48479. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48480. */
  48481. var PointLight = /** @class */ (function (_super) {
  48482. __extends(PointLight, _super);
  48483. /**
  48484. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48485. * A PointLight emits the light in every direction.
  48486. * It can cast shadows.
  48487. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48488. * ```javascript
  48489. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48490. * ```
  48491. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48492. * @param name The light friendly name
  48493. * @param position The position of the point light in the scene
  48494. * @param scene The scene the lights belongs to
  48495. */
  48496. function PointLight(name, position, scene) {
  48497. var _this = _super.call(this, name, scene) || this;
  48498. _this._shadowAngle = Math.PI / 2;
  48499. _this.position = position;
  48500. return _this;
  48501. }
  48502. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48503. /**
  48504. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48505. * This specifies what angle the shadow will use to be created.
  48506. *
  48507. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48508. */
  48509. get: function () {
  48510. return this._shadowAngle;
  48511. },
  48512. /**
  48513. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48514. * This specifies what angle the shadow will use to be created.
  48515. *
  48516. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48517. */
  48518. set: function (value) {
  48519. this._shadowAngle = value;
  48520. this.forceProjectionMatrixCompute();
  48521. },
  48522. enumerable: true,
  48523. configurable: true
  48524. });
  48525. Object.defineProperty(PointLight.prototype, "direction", {
  48526. /**
  48527. * Gets the direction if it has been set.
  48528. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48529. */
  48530. get: function () {
  48531. return this._direction;
  48532. },
  48533. /**
  48534. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48535. */
  48536. set: function (value) {
  48537. var previousNeedCube = this.needCube();
  48538. this._direction = value;
  48539. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48540. this._shadowGenerator.recreateShadowMap();
  48541. }
  48542. },
  48543. enumerable: true,
  48544. configurable: true
  48545. });
  48546. /**
  48547. * Returns the string "PointLight"
  48548. * @returns the class name
  48549. */
  48550. PointLight.prototype.getClassName = function () {
  48551. return "PointLight";
  48552. };
  48553. /**
  48554. * Returns the integer 0.
  48555. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48556. */
  48557. PointLight.prototype.getTypeID = function () {
  48558. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48559. };
  48560. /**
  48561. * Specifies wether or not the shadowmap should be a cube texture.
  48562. * @returns true if the shadowmap needs to be a cube texture.
  48563. */
  48564. PointLight.prototype.needCube = function () {
  48565. return !this.direction;
  48566. };
  48567. /**
  48568. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48569. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48570. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48571. */
  48572. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48573. if (this.direction) {
  48574. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48575. }
  48576. else {
  48577. switch (faceIndex) {
  48578. case 0:
  48579. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48580. case 1:
  48581. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48582. case 2:
  48583. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48584. case 3:
  48585. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48586. case 4:
  48587. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48588. case 5:
  48589. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48590. }
  48591. }
  48592. return BABYLON.Vector3.Zero();
  48593. };
  48594. /**
  48595. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48596. * - fov = PI / 2
  48597. * - aspect ratio : 1.0
  48598. * - z-near and far equal to the active camera minZ and maxZ.
  48599. * Returns the PointLight.
  48600. */
  48601. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48602. var activeCamera = this.getScene().activeCamera;
  48603. if (!activeCamera) {
  48604. return;
  48605. }
  48606. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48607. };
  48608. PointLight.prototype._buildUniformLayout = function () {
  48609. this._uniformBuffer.addUniform("vLightData", 4);
  48610. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48611. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48612. this._uniformBuffer.addUniform("vLightFalloff", 4);
  48613. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48614. this._uniformBuffer.addUniform("depthValues", 2);
  48615. this._uniformBuffer.create();
  48616. };
  48617. /**
  48618. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48619. * @param effect The effect to update
  48620. * @param lightIndex The index of the light in the effect to update
  48621. * @returns The point light
  48622. */
  48623. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48624. if (this.computeTransformedInformation()) {
  48625. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48626. }
  48627. else {
  48628. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48629. }
  48630. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  48631. return this;
  48632. };
  48633. /**
  48634. * Prepares the list of defines specific to the light type.
  48635. * @param defines the list of defines
  48636. * @param lightIndex defines the index of the light for the effect
  48637. */
  48638. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48639. defines["POINTLIGHT" + lightIndex] = true;
  48640. };
  48641. __decorate([
  48642. BABYLON.serialize()
  48643. ], PointLight.prototype, "shadowAngle", null);
  48644. return PointLight;
  48645. }(BABYLON.ShadowLight));
  48646. BABYLON.PointLight = PointLight;
  48647. })(BABYLON || (BABYLON = {}));
  48648. //# sourceMappingURL=babylon.pointLight.js.map
  48649. var BABYLON;
  48650. (function (BABYLON) {
  48651. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  48652. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  48653. });
  48654. /**
  48655. * A directional light is defined by a direction (what a surprise!).
  48656. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48657. * 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.
  48658. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48659. */
  48660. var DirectionalLight = /** @class */ (function (_super) {
  48661. __extends(DirectionalLight, _super);
  48662. /**
  48663. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48664. * The directional light is emitted from everywhere in the given direction.
  48665. * It can cast shawdows.
  48666. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48667. * @param name The friendly name of the light
  48668. * @param direction The direction of the light
  48669. * @param scene The scene the light belongs to
  48670. */
  48671. function DirectionalLight(name, direction, scene) {
  48672. var _this = _super.call(this, name, scene) || this;
  48673. _this._shadowFrustumSize = 0;
  48674. _this._shadowOrthoScale = 0.1;
  48675. /**
  48676. * Automatically compute the projection matrix to best fit (including all the casters)
  48677. * on each frame.
  48678. */
  48679. _this.autoUpdateExtends = true;
  48680. // Cache
  48681. _this._orthoLeft = Number.MAX_VALUE;
  48682. _this._orthoRight = Number.MIN_VALUE;
  48683. _this._orthoTop = Number.MIN_VALUE;
  48684. _this._orthoBottom = Number.MAX_VALUE;
  48685. _this.position = direction.scale(-1.0);
  48686. _this.direction = direction;
  48687. return _this;
  48688. }
  48689. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48690. /**
  48691. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48692. */
  48693. get: function () {
  48694. return this._shadowFrustumSize;
  48695. },
  48696. /**
  48697. * Specifies a fix frustum size for the shadow generation.
  48698. */
  48699. set: function (value) {
  48700. this._shadowFrustumSize = value;
  48701. this.forceProjectionMatrixCompute();
  48702. },
  48703. enumerable: true,
  48704. configurable: true
  48705. });
  48706. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48707. /**
  48708. * Gets the shadow projection scale against the optimal computed one.
  48709. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48710. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48711. */
  48712. get: function () {
  48713. return this._shadowOrthoScale;
  48714. },
  48715. /**
  48716. * Sets the shadow projection scale against the optimal computed one.
  48717. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48718. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48719. */
  48720. set: function (value) {
  48721. this._shadowOrthoScale = value;
  48722. this.forceProjectionMatrixCompute();
  48723. },
  48724. enumerable: true,
  48725. configurable: true
  48726. });
  48727. /**
  48728. * Returns the string "DirectionalLight".
  48729. * @return The class name
  48730. */
  48731. DirectionalLight.prototype.getClassName = function () {
  48732. return "DirectionalLight";
  48733. };
  48734. /**
  48735. * Returns the integer 1.
  48736. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48737. */
  48738. DirectionalLight.prototype.getTypeID = function () {
  48739. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48740. };
  48741. /**
  48742. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48743. * Returns the DirectionalLight Shadow projection matrix.
  48744. */
  48745. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48746. if (this.shadowFrustumSize > 0) {
  48747. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48748. }
  48749. else {
  48750. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48751. }
  48752. };
  48753. /**
  48754. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48755. * Returns the DirectionalLight Shadow projection matrix.
  48756. */
  48757. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48758. var activeCamera = this.getScene().activeCamera;
  48759. if (!activeCamera) {
  48760. return;
  48761. }
  48762. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48763. };
  48764. /**
  48765. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48766. * Returns the DirectionalLight Shadow projection matrix.
  48767. */
  48768. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48769. var activeCamera = this.getScene().activeCamera;
  48770. if (!activeCamera) {
  48771. return;
  48772. }
  48773. // Check extends
  48774. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48775. var tempVector3 = BABYLON.Vector3.Zero();
  48776. this._orthoLeft = Number.MAX_VALUE;
  48777. this._orthoRight = Number.MIN_VALUE;
  48778. this._orthoTop = Number.MIN_VALUE;
  48779. this._orthoBottom = Number.MAX_VALUE;
  48780. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48781. var mesh = renderList[meshIndex];
  48782. if (!mesh) {
  48783. continue;
  48784. }
  48785. var boundingInfo = mesh.getBoundingInfo();
  48786. var boundingBox = boundingInfo.boundingBox;
  48787. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48788. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48789. if (tempVector3.x < this._orthoLeft)
  48790. this._orthoLeft = tempVector3.x;
  48791. if (tempVector3.y < this._orthoBottom)
  48792. this._orthoBottom = tempVector3.y;
  48793. if (tempVector3.x > this._orthoRight)
  48794. this._orthoRight = tempVector3.x;
  48795. if (tempVector3.y > this._orthoTop)
  48796. this._orthoTop = tempVector3.y;
  48797. }
  48798. }
  48799. }
  48800. var xOffset = this._orthoRight - this._orthoLeft;
  48801. var yOffset = this._orthoTop - this._orthoBottom;
  48802. 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);
  48803. };
  48804. DirectionalLight.prototype._buildUniformLayout = function () {
  48805. this._uniformBuffer.addUniform("vLightData", 4);
  48806. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48807. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48808. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48809. this._uniformBuffer.addUniform("depthValues", 2);
  48810. this._uniformBuffer.create();
  48811. };
  48812. /**
  48813. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48814. * @param effect The effect to update
  48815. * @param lightIndex The index of the light in the effect to update
  48816. * @returns The directional light
  48817. */
  48818. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48819. if (this.computeTransformedInformation()) {
  48820. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48821. return this;
  48822. }
  48823. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48824. return this;
  48825. };
  48826. /**
  48827. * Gets the minZ used for shadow according to both the scene and the light.
  48828. *
  48829. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48830. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48831. * @param activeCamera The camera we are returning the min for
  48832. * @returns the depth min z
  48833. */
  48834. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48835. return 1;
  48836. };
  48837. /**
  48838. * Gets the maxZ used for shadow according to both the scene and the light.
  48839. *
  48840. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48841. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48842. * @param activeCamera The camera we are returning the max for
  48843. * @returns the depth max z
  48844. */
  48845. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48846. return 1;
  48847. };
  48848. /**
  48849. * Prepares the list of defines specific to the light type.
  48850. * @param defines the list of defines
  48851. * @param lightIndex defines the index of the light for the effect
  48852. */
  48853. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48854. defines["DIRLIGHT" + lightIndex] = true;
  48855. };
  48856. __decorate([
  48857. BABYLON.serialize()
  48858. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48859. __decorate([
  48860. BABYLON.serialize()
  48861. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48862. __decorate([
  48863. BABYLON.serialize()
  48864. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48865. return DirectionalLight;
  48866. }(BABYLON.ShadowLight));
  48867. BABYLON.DirectionalLight = DirectionalLight;
  48868. })(BABYLON || (BABYLON = {}));
  48869. //# sourceMappingURL=babylon.directionalLight.js.map
  48870. var BABYLON;
  48871. (function (BABYLON) {
  48872. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  48873. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  48874. });
  48875. /**
  48876. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48877. * These values define a cone of light starting from the position, emitting toward the direction.
  48878. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48879. * and the exponent defines the speed of the decay of the light with distance (reach).
  48880. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48881. */
  48882. var SpotLight = /** @class */ (function (_super) {
  48883. __extends(SpotLight, _super);
  48884. /**
  48885. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48886. * It can cast shadows.
  48887. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48888. * @param name The light friendly name
  48889. * @param position The position of the spot light in the scene
  48890. * @param direction The direction of the light in the scene
  48891. * @param angle The cone angle of the light in Radians
  48892. * @param exponent The light decay speed with the distance from the emission spot
  48893. * @param scene The scene the lights belongs to
  48894. */
  48895. function SpotLight(name, position, direction, angle, exponent, scene) {
  48896. var _this = _super.call(this, name, scene) || this;
  48897. _this._innerAngle = 0;
  48898. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48899. _this._projectionTextureLightNear = 1e-6;
  48900. _this._projectionTextureLightFar = 1000.0;
  48901. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48902. _this._projectionTextureViewLightDirty = true;
  48903. _this._projectionTextureProjectionLightDirty = true;
  48904. _this._projectionTextureDirty = true;
  48905. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48906. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48907. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48908. _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);
  48909. _this.position = position;
  48910. _this.direction = direction;
  48911. _this.angle = angle;
  48912. _this.exponent = exponent;
  48913. return _this;
  48914. }
  48915. Object.defineProperty(SpotLight.prototype, "angle", {
  48916. /**
  48917. * Gets the cone angle of the spot light in Radians.
  48918. */
  48919. get: function () {
  48920. return this._angle;
  48921. },
  48922. /**
  48923. * Sets the cone angle of the spot light in Radians.
  48924. */
  48925. set: function (value) {
  48926. this._angle = value;
  48927. this._cosHalfAngle = Math.cos(value * 0.5);
  48928. this._projectionTextureProjectionLightDirty = true;
  48929. this.forceProjectionMatrixCompute();
  48930. this._computeAngleValues();
  48931. },
  48932. enumerable: true,
  48933. configurable: true
  48934. });
  48935. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  48936. /**
  48937. * Only used in gltf falloff mode, this defines the angle where
  48938. * the directional falloff will start before cutting at angle which could be seen
  48939. * as outer angle.
  48940. */
  48941. get: function () {
  48942. return this._angle;
  48943. },
  48944. /**
  48945. * Only used in gltf falloff mode, this defines the angle where
  48946. * the directional falloff will start before cutting at angle which could be seen
  48947. * as outer angle.
  48948. */
  48949. set: function (value) {
  48950. this._innerAngle = value;
  48951. this._computeAngleValues();
  48952. },
  48953. enumerable: true,
  48954. configurable: true
  48955. });
  48956. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48957. /**
  48958. * Allows scaling the angle of the light for shadow generation only.
  48959. */
  48960. get: function () {
  48961. return this._shadowAngleScale;
  48962. },
  48963. /**
  48964. * Allows scaling the angle of the light for shadow generation only.
  48965. */
  48966. set: function (value) {
  48967. this._shadowAngleScale = value;
  48968. this.forceProjectionMatrixCompute();
  48969. },
  48970. enumerable: true,
  48971. configurable: true
  48972. });
  48973. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48974. /**
  48975. * Allows reading the projecton texture
  48976. */
  48977. get: function () {
  48978. return this._projectionTextureMatrix;
  48979. },
  48980. enumerable: true,
  48981. configurable: true
  48982. });
  48983. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48984. /**
  48985. * Gets the near clip of the Spotlight for texture projection.
  48986. */
  48987. get: function () {
  48988. return this._projectionTextureLightNear;
  48989. },
  48990. /**
  48991. * Sets the near clip of the Spotlight for texture projection.
  48992. */
  48993. set: function (value) {
  48994. this._projectionTextureLightNear = value;
  48995. this._projectionTextureProjectionLightDirty = true;
  48996. },
  48997. enumerable: true,
  48998. configurable: true
  48999. });
  49000. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49001. /**
  49002. * Gets the far clip of the Spotlight for texture projection.
  49003. */
  49004. get: function () {
  49005. return this._projectionTextureLightFar;
  49006. },
  49007. /**
  49008. * Sets the far clip of the Spotlight for texture projection.
  49009. */
  49010. set: function (value) {
  49011. this._projectionTextureLightFar = value;
  49012. this._projectionTextureProjectionLightDirty = true;
  49013. },
  49014. enumerable: true,
  49015. configurable: true
  49016. });
  49017. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49018. /**
  49019. * Gets the Up vector of the Spotlight for texture projection.
  49020. */
  49021. get: function () {
  49022. return this._projectionTextureUpDirection;
  49023. },
  49024. /**
  49025. * Sets the Up vector of the Spotlight for texture projection.
  49026. */
  49027. set: function (value) {
  49028. this._projectionTextureUpDirection = value;
  49029. this._projectionTextureProjectionLightDirty = true;
  49030. },
  49031. enumerable: true,
  49032. configurable: true
  49033. });
  49034. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49035. /**
  49036. * Gets the projection texture of the light.
  49037. */
  49038. get: function () {
  49039. return this._projectionTexture;
  49040. },
  49041. /**
  49042. * Sets the projection texture of the light.
  49043. */
  49044. set: function (value) {
  49045. this._projectionTexture = value;
  49046. this._projectionTextureDirty = true;
  49047. },
  49048. enumerable: true,
  49049. configurable: true
  49050. });
  49051. /**
  49052. * Returns the string "SpotLight".
  49053. * @returns the class name
  49054. */
  49055. SpotLight.prototype.getClassName = function () {
  49056. return "SpotLight";
  49057. };
  49058. /**
  49059. * Returns the integer 2.
  49060. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49061. */
  49062. SpotLight.prototype.getTypeID = function () {
  49063. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49064. };
  49065. /**
  49066. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49067. */
  49068. SpotLight.prototype._setDirection = function (value) {
  49069. _super.prototype._setDirection.call(this, value);
  49070. this._projectionTextureViewLightDirty = true;
  49071. };
  49072. /**
  49073. * Overrides the position setter to recompute the projection texture view light Matrix.
  49074. */
  49075. SpotLight.prototype._setPosition = function (value) {
  49076. _super.prototype._setPosition.call(this, value);
  49077. this._projectionTextureViewLightDirty = true;
  49078. };
  49079. /**
  49080. * 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.
  49081. * Returns the SpotLight.
  49082. */
  49083. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49084. var activeCamera = this.getScene().activeCamera;
  49085. if (!activeCamera) {
  49086. return;
  49087. }
  49088. this._shadowAngleScale = this._shadowAngleScale || 1;
  49089. var angle = this._shadowAngleScale * this._angle;
  49090. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49091. };
  49092. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49093. this._projectionTextureViewLightDirty = false;
  49094. this._projectionTextureDirty = true;
  49095. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49096. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49097. };
  49098. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49099. this._projectionTextureProjectionLightDirty = false;
  49100. this._projectionTextureDirty = true;
  49101. var light_far = this.projectionTextureLightFar;
  49102. var light_near = this.projectionTextureLightNear;
  49103. var P = light_far / (light_far - light_near);
  49104. var Q = -P * light_near;
  49105. var S = 1.0 / Math.tan(this._angle / 2.0);
  49106. var A = 1.0;
  49107. 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);
  49108. };
  49109. /**
  49110. * Main function for light texture projection matrix computing.
  49111. */
  49112. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49113. this._projectionTextureDirty = false;
  49114. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49115. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49116. };
  49117. SpotLight.prototype._buildUniformLayout = function () {
  49118. this._uniformBuffer.addUniform("vLightData", 4);
  49119. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49120. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49121. this._uniformBuffer.addUniform("vLightDirection", 3);
  49122. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49123. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49124. this._uniformBuffer.addUniform("depthValues", 2);
  49125. this._uniformBuffer.create();
  49126. };
  49127. SpotLight.prototype._computeAngleValues = function () {
  49128. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  49129. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  49130. };
  49131. /**
  49132. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49133. * @param effect The effect to update
  49134. * @param lightIndex The index of the light in the effect to update
  49135. * @returns The spot light
  49136. */
  49137. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49138. var normalizeDirection;
  49139. if (this.computeTransformedInformation()) {
  49140. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49141. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49142. }
  49143. else {
  49144. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49145. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49146. }
  49147. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  49148. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  49149. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49150. if (this._projectionTextureViewLightDirty) {
  49151. this._computeProjectionTextureViewLightMatrix();
  49152. }
  49153. if (this._projectionTextureProjectionLightDirty) {
  49154. this._computeProjectionTextureProjectionLightMatrix();
  49155. }
  49156. if (this._projectionTextureDirty) {
  49157. this._computeProjectionTextureMatrix();
  49158. }
  49159. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49160. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49161. }
  49162. return this;
  49163. };
  49164. /**
  49165. * Disposes the light and the associated resources.
  49166. */
  49167. SpotLight.prototype.dispose = function () {
  49168. _super.prototype.dispose.call(this);
  49169. if (this._projectionTexture) {
  49170. this._projectionTexture.dispose();
  49171. }
  49172. };
  49173. /**
  49174. * Prepares the list of defines specific to the light type.
  49175. * @param defines the list of defines
  49176. * @param lightIndex defines the index of the light for the effect
  49177. */
  49178. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49179. defines["SPOTLIGHT" + lightIndex] = true;
  49180. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49181. };
  49182. __decorate([
  49183. BABYLON.serialize()
  49184. ], SpotLight.prototype, "angle", null);
  49185. __decorate([
  49186. BABYLON.serialize()
  49187. ], SpotLight.prototype, "innerAngle", null);
  49188. __decorate([
  49189. BABYLON.serialize()
  49190. ], SpotLight.prototype, "shadowAngleScale", null);
  49191. __decorate([
  49192. BABYLON.serialize()
  49193. ], SpotLight.prototype, "exponent", void 0);
  49194. __decorate([
  49195. BABYLON.serialize()
  49196. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49197. __decorate([
  49198. BABYLON.serialize()
  49199. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49200. __decorate([
  49201. BABYLON.serialize()
  49202. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49203. __decorate([
  49204. BABYLON.serializeAsTexture("projectedLightTexture")
  49205. ], SpotLight.prototype, "_projectionTexture", void 0);
  49206. return SpotLight;
  49207. }(BABYLON.ShadowLight));
  49208. BABYLON.SpotLight = SpotLight;
  49209. })(BABYLON || (BABYLON = {}));
  49210. //# sourceMappingURL=babylon.spotLight.js.map
  49211. var BABYLON;
  49212. (function (BABYLON) {
  49213. /**
  49214. * Class used to override all child animations of a given target
  49215. */
  49216. var AnimationPropertiesOverride = /** @class */ (function () {
  49217. function AnimationPropertiesOverride() {
  49218. /**
  49219. * Gets or sets a value indicating if animation blending must be used
  49220. */
  49221. this.enableBlending = false;
  49222. /**
  49223. * Gets or sets the blending speed to use when enableBlending is true
  49224. */
  49225. this.blendingSpeed = 0.01;
  49226. /**
  49227. * Gets or sets the default loop mode to use
  49228. */
  49229. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49230. }
  49231. return AnimationPropertiesOverride;
  49232. }());
  49233. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49234. })(BABYLON || (BABYLON = {}));
  49235. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49236. var BABYLON;
  49237. (function (BABYLON) {
  49238. /**
  49239. * Represents the range of an animation
  49240. */
  49241. var AnimationRange = /** @class */ (function () {
  49242. /**
  49243. * Initializes the range of an animation
  49244. * @param name The name of the animation range
  49245. * @param from The starting frame of the animation
  49246. * @param to The ending frame of the animation
  49247. */
  49248. function AnimationRange(
  49249. /**The name of the animation range**/
  49250. name,
  49251. /**The starting frame of the animation */
  49252. from,
  49253. /**The ending frame of the animation*/
  49254. to) {
  49255. this.name = name;
  49256. this.from = from;
  49257. this.to = to;
  49258. }
  49259. /**
  49260. * Makes a copy of the animation range
  49261. * @returns A copy of the animation range
  49262. */
  49263. AnimationRange.prototype.clone = function () {
  49264. return new AnimationRange(this.name, this.from, this.to);
  49265. };
  49266. return AnimationRange;
  49267. }());
  49268. BABYLON.AnimationRange = AnimationRange;
  49269. /**
  49270. * Composed of a frame, and an action function
  49271. */
  49272. var AnimationEvent = /** @class */ (function () {
  49273. /**
  49274. * Initializes the animation event
  49275. * @param frame The frame for which the event is triggered
  49276. * @param action The event to perform when triggered
  49277. * @param onlyOnce Specifies if the event should be triggered only once
  49278. */
  49279. function AnimationEvent(
  49280. /** The frame for which the event is triggered **/
  49281. frame,
  49282. /** The event to perform when triggered **/
  49283. action,
  49284. /** Specifies if the event should be triggered only once**/
  49285. onlyOnce) {
  49286. this.frame = frame;
  49287. this.action = action;
  49288. this.onlyOnce = onlyOnce;
  49289. /**
  49290. * Specifies if the animation event is done
  49291. */
  49292. this.isDone = false;
  49293. }
  49294. /** @hidden */
  49295. AnimationEvent.prototype._clone = function () {
  49296. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49297. };
  49298. return AnimationEvent;
  49299. }());
  49300. BABYLON.AnimationEvent = AnimationEvent;
  49301. /**
  49302. * A cursor which tracks a point on a path
  49303. */
  49304. var PathCursor = /** @class */ (function () {
  49305. /**
  49306. * Initializes the path cursor
  49307. * @param path The path to track
  49308. */
  49309. function PathCursor(path) {
  49310. this.path = path;
  49311. /**
  49312. * Stores path cursor callbacks for when an onchange event is triggered
  49313. */
  49314. this._onchange = new Array();
  49315. /**
  49316. * The value of the path cursor
  49317. */
  49318. this.value = 0;
  49319. /**
  49320. * The animation array of the path cursor
  49321. */
  49322. this.animations = new Array();
  49323. }
  49324. /**
  49325. * Gets the cursor point on the path
  49326. * @returns A point on the path cursor at the cursor location
  49327. */
  49328. PathCursor.prototype.getPoint = function () {
  49329. var point = this.path.getPointAtLengthPosition(this.value);
  49330. return new BABYLON.Vector3(point.x, 0, point.y);
  49331. };
  49332. /**
  49333. * Moves the cursor ahead by the step amount
  49334. * @param step The amount to move the cursor forward
  49335. * @returns This path cursor
  49336. */
  49337. PathCursor.prototype.moveAhead = function (step) {
  49338. if (step === void 0) { step = 0.002; }
  49339. this.move(step);
  49340. return this;
  49341. };
  49342. /**
  49343. * Moves the cursor behind by the step amount
  49344. * @param step The amount to move the cursor back
  49345. * @returns This path cursor
  49346. */
  49347. PathCursor.prototype.moveBack = function (step) {
  49348. if (step === void 0) { step = 0.002; }
  49349. this.move(-step);
  49350. return this;
  49351. };
  49352. /**
  49353. * Moves the cursor by the step amount
  49354. * If the step amount is greater than one, an exception is thrown
  49355. * @param step The amount to move the cursor
  49356. * @returns This path cursor
  49357. */
  49358. PathCursor.prototype.move = function (step) {
  49359. if (Math.abs(step) > 1) {
  49360. throw "step size should be less than 1.";
  49361. }
  49362. this.value += step;
  49363. this.ensureLimits();
  49364. this.raiseOnChange();
  49365. return this;
  49366. };
  49367. /**
  49368. * Ensures that the value is limited between zero and one
  49369. * @returns This path cursor
  49370. */
  49371. PathCursor.prototype.ensureLimits = function () {
  49372. while (this.value > 1) {
  49373. this.value -= 1;
  49374. }
  49375. while (this.value < 0) {
  49376. this.value += 1;
  49377. }
  49378. return this;
  49379. };
  49380. /**
  49381. * Runs onchange callbacks on change (used by the animation engine)
  49382. * @returns This path cursor
  49383. */
  49384. PathCursor.prototype.raiseOnChange = function () {
  49385. var _this = this;
  49386. this._onchange.forEach(function (f) { return f(_this); });
  49387. return this;
  49388. };
  49389. /**
  49390. * Executes a function on change
  49391. * @param f A path cursor onchange callback
  49392. * @returns This path cursor
  49393. */
  49394. PathCursor.prototype.onchange = function (f) {
  49395. this._onchange.push(f);
  49396. return this;
  49397. };
  49398. return PathCursor;
  49399. }());
  49400. BABYLON.PathCursor = PathCursor;
  49401. /**
  49402. * Enum for the animation key frame interpolation type
  49403. */
  49404. var AnimationKeyInterpolation;
  49405. (function (AnimationKeyInterpolation) {
  49406. /**
  49407. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49408. */
  49409. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49410. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49411. /**
  49412. * Class used to store any kind of animation
  49413. */
  49414. var Animation = /** @class */ (function () {
  49415. /**
  49416. * Initializes the animation
  49417. * @param name Name of the animation
  49418. * @param targetProperty Property to animate
  49419. * @param framePerSecond The frames per second of the animation
  49420. * @param dataType The data type of the animation
  49421. * @param loopMode The loop mode of the animation
  49422. * @param enableBlendings Specifies if blending should be enabled
  49423. */
  49424. function Animation(
  49425. /**Name of the animation */
  49426. name,
  49427. /**Property to animate */
  49428. targetProperty,
  49429. /**The frames per second of the animation */
  49430. framePerSecond,
  49431. /**The data type of the animation */
  49432. dataType,
  49433. /**The loop mode of the animation */
  49434. loopMode,
  49435. /**Specifies if blending should be enabled */
  49436. enableBlending) {
  49437. this.name = name;
  49438. this.targetProperty = targetProperty;
  49439. this.framePerSecond = framePerSecond;
  49440. this.dataType = dataType;
  49441. this.loopMode = loopMode;
  49442. this.enableBlending = enableBlending;
  49443. /**
  49444. * @hidden Internal use only
  49445. */
  49446. this._runtimeAnimations = new Array();
  49447. /**
  49448. * The set of event that will be linked to this animation
  49449. */
  49450. this._events = new Array();
  49451. /**
  49452. * Stores the blending speed of the animation
  49453. */
  49454. this.blendingSpeed = 0.01;
  49455. /**
  49456. * Stores the animation ranges for the animation
  49457. */
  49458. this._ranges = {};
  49459. this.targetPropertyPath = targetProperty.split(".");
  49460. this.dataType = dataType;
  49461. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49462. }
  49463. /**
  49464. * @hidden Internal use
  49465. */
  49466. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49467. var dataType = undefined;
  49468. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49469. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49470. }
  49471. else if (from instanceof BABYLON.Quaternion) {
  49472. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49473. }
  49474. else if (from instanceof BABYLON.Vector3) {
  49475. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49476. }
  49477. else if (from instanceof BABYLON.Vector2) {
  49478. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49479. }
  49480. else if (from instanceof BABYLON.Color3) {
  49481. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49482. }
  49483. else if (from instanceof BABYLON.Size) {
  49484. dataType = Animation.ANIMATIONTYPE_SIZE;
  49485. }
  49486. if (dataType == undefined) {
  49487. return null;
  49488. }
  49489. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49490. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49491. animation.setKeys(keys);
  49492. if (easingFunction !== undefined) {
  49493. animation.setEasingFunction(easingFunction);
  49494. }
  49495. return animation;
  49496. };
  49497. /**
  49498. * Sets up an animation
  49499. * @param property The property to animate
  49500. * @param animationType The animation type to apply
  49501. * @param framePerSecond The frames per second of the animation
  49502. * @param easingFunction The easing function used in the animation
  49503. * @returns The created animation
  49504. */
  49505. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49506. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49507. animation.setEasingFunction(easingFunction);
  49508. return animation;
  49509. };
  49510. /**
  49511. * Create and start an animation on a node
  49512. * @param name defines the name of the global animation that will be run on all nodes
  49513. * @param node defines the root node where the animation will take place
  49514. * @param targetProperty defines property to animate
  49515. * @param framePerSecond defines the number of frame per second yo use
  49516. * @param totalFrame defines the number of frames in total
  49517. * @param from defines the initial value
  49518. * @param to defines the final value
  49519. * @param loopMode defines which loop mode you want to use (off by default)
  49520. * @param easingFunction defines the easing function to use (linear by default)
  49521. * @param onAnimationEnd defines the callback to call when animation end
  49522. * @returns the animatable created for this animation
  49523. */
  49524. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49525. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49526. if (!animation) {
  49527. return null;
  49528. }
  49529. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49530. };
  49531. /**
  49532. * Create and start an animation on a node and its descendants
  49533. * @param name defines the name of the global animation that will be run on all nodes
  49534. * @param node defines the root node where the animation will take place
  49535. * @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
  49536. * @param targetProperty defines property to animate
  49537. * @param framePerSecond defines the number of frame per second to use
  49538. * @param totalFrame defines the number of frames in total
  49539. * @param from defines the initial value
  49540. * @param to defines the final value
  49541. * @param loopMode defines which loop mode you want to use (off by default)
  49542. * @param easingFunction defines the easing function to use (linear by default)
  49543. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49544. * @returns the list of animatables created for all nodes
  49545. * @example https://www.babylonjs-playground.com/#MH0VLI
  49546. */
  49547. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49548. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49549. if (!animation) {
  49550. return null;
  49551. }
  49552. var scene = node.getScene();
  49553. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49554. };
  49555. /**
  49556. * Creates a new animation, merges it with the existing animations and starts it
  49557. * @param name Name of the animation
  49558. * @param node Node which contains the scene that begins the animations
  49559. * @param targetProperty Specifies which property to animate
  49560. * @param framePerSecond The frames per second of the animation
  49561. * @param totalFrame The total number of frames
  49562. * @param from The frame at the beginning of the animation
  49563. * @param to The frame at the end of the animation
  49564. * @param loopMode Specifies the loop mode of the animation
  49565. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49566. * @param onAnimationEnd Callback to run once the animation is complete
  49567. * @returns Nullable animation
  49568. */
  49569. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49570. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49571. if (!animation) {
  49572. return null;
  49573. }
  49574. node.animations.push(animation);
  49575. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49576. };
  49577. /**
  49578. * Transition property of an host to the target Value
  49579. * @param property The property to transition
  49580. * @param targetValue The target Value of the property
  49581. * @param host The object where the property to animate belongs
  49582. * @param scene Scene used to run the animation
  49583. * @param frameRate Framerate (in frame/s) to use
  49584. * @param transition The transition type we want to use
  49585. * @param duration The duration of the animation, in milliseconds
  49586. * @param onAnimationEnd Callback trigger at the end of the animation
  49587. * @returns Nullable animation
  49588. */
  49589. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49590. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49591. if (duration <= 0) {
  49592. host[property] = targetValue;
  49593. if (onAnimationEnd) {
  49594. onAnimationEnd();
  49595. }
  49596. return null;
  49597. }
  49598. var endFrame = frameRate * (duration / 1000);
  49599. transition.setKeys([{
  49600. frame: 0,
  49601. value: host[property].clone ? host[property].clone() : host[property]
  49602. },
  49603. {
  49604. frame: endFrame,
  49605. value: targetValue
  49606. }]);
  49607. if (!host.animations) {
  49608. host.animations = [];
  49609. }
  49610. host.animations.push(transition);
  49611. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49612. animation.onAnimationEnd = onAnimationEnd;
  49613. return animation;
  49614. };
  49615. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49616. /**
  49617. * Return the array of runtime animations currently using this animation
  49618. */
  49619. get: function () {
  49620. return this._runtimeAnimations;
  49621. },
  49622. enumerable: true,
  49623. configurable: true
  49624. });
  49625. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49626. /**
  49627. * Specifies if any of the runtime animations are currently running
  49628. */
  49629. get: function () {
  49630. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49631. var runtimeAnimation = _a[_i];
  49632. if (!runtimeAnimation.isStopped) {
  49633. return true;
  49634. }
  49635. }
  49636. return false;
  49637. },
  49638. enumerable: true,
  49639. configurable: true
  49640. });
  49641. // Methods
  49642. /**
  49643. * Converts the animation to a string
  49644. * @param fullDetails support for multiple levels of logging within scene loading
  49645. * @returns String form of the animation
  49646. */
  49647. Animation.prototype.toString = function (fullDetails) {
  49648. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49649. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49650. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49651. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49652. if (fullDetails) {
  49653. ret += ", Ranges: {";
  49654. var first = true;
  49655. for (var name in this._ranges) {
  49656. if (first) {
  49657. ret += ", ";
  49658. first = false;
  49659. }
  49660. ret += name;
  49661. }
  49662. ret += "}";
  49663. }
  49664. return ret;
  49665. };
  49666. /**
  49667. * Add an event to this animation
  49668. * @param event Event to add
  49669. */
  49670. Animation.prototype.addEvent = function (event) {
  49671. this._events.push(event);
  49672. };
  49673. /**
  49674. * Remove all events found at the given frame
  49675. * @param frame The frame to remove events from
  49676. */
  49677. Animation.prototype.removeEvents = function (frame) {
  49678. for (var index = 0; index < this._events.length; index++) {
  49679. if (this._events[index].frame === frame) {
  49680. this._events.splice(index, 1);
  49681. index--;
  49682. }
  49683. }
  49684. };
  49685. /**
  49686. * Retrieves all the events from the animation
  49687. * @returns Events from the animation
  49688. */
  49689. Animation.prototype.getEvents = function () {
  49690. return this._events;
  49691. };
  49692. /**
  49693. * Creates an animation range
  49694. * @param name Name of the animation range
  49695. * @param from Starting frame of the animation range
  49696. * @param to Ending frame of the animation
  49697. */
  49698. Animation.prototype.createRange = function (name, from, to) {
  49699. // check name not already in use; could happen for bones after serialized
  49700. if (!this._ranges[name]) {
  49701. this._ranges[name] = new AnimationRange(name, from, to);
  49702. }
  49703. };
  49704. /**
  49705. * Deletes an animation range by name
  49706. * @param name Name of the animation range to delete
  49707. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49708. */
  49709. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49710. if (deleteFrames === void 0) { deleteFrames = true; }
  49711. var range = this._ranges[name];
  49712. if (!range) {
  49713. return;
  49714. }
  49715. if (deleteFrames) {
  49716. var from = range.from;
  49717. var to = range.to;
  49718. // this loop MUST go high to low for multiple splices to work
  49719. for (var key = this._keys.length - 1; key >= 0; key--) {
  49720. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49721. this._keys.splice(key, 1);
  49722. }
  49723. }
  49724. }
  49725. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49726. };
  49727. /**
  49728. * Gets the animation range by name, or null if not defined
  49729. * @param name Name of the animation range
  49730. * @returns Nullable animation range
  49731. */
  49732. Animation.prototype.getRange = function (name) {
  49733. return this._ranges[name];
  49734. };
  49735. /**
  49736. * Gets the key frames from the animation
  49737. * @returns The key frames of the animation
  49738. */
  49739. Animation.prototype.getKeys = function () {
  49740. return this._keys;
  49741. };
  49742. /**
  49743. * Gets the highest frame rate of the animation
  49744. * @returns Highest frame rate of the animation
  49745. */
  49746. Animation.prototype.getHighestFrame = function () {
  49747. var ret = 0;
  49748. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49749. if (ret < this._keys[key].frame) {
  49750. ret = this._keys[key].frame;
  49751. }
  49752. }
  49753. return ret;
  49754. };
  49755. /**
  49756. * Gets the easing function of the animation
  49757. * @returns Easing function of the animation
  49758. */
  49759. Animation.prototype.getEasingFunction = function () {
  49760. return this._easingFunction;
  49761. };
  49762. /**
  49763. * Sets the easing function of the animation
  49764. * @param easingFunction A custom mathematical formula for animation
  49765. */
  49766. Animation.prototype.setEasingFunction = function (easingFunction) {
  49767. this._easingFunction = easingFunction;
  49768. };
  49769. /**
  49770. * Interpolates a scalar linearly
  49771. * @param startValue Start value of the animation curve
  49772. * @param endValue End value of the animation curve
  49773. * @param gradient Scalar amount to interpolate
  49774. * @returns Interpolated scalar value
  49775. */
  49776. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49777. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49778. };
  49779. /**
  49780. * Interpolates a scalar cubically
  49781. * @param startValue Start value of the animation curve
  49782. * @param outTangent End tangent of the animation
  49783. * @param endValue End value of the animation curve
  49784. * @param inTangent Start tangent of the animation curve
  49785. * @param gradient Scalar amount to interpolate
  49786. * @returns Interpolated scalar value
  49787. */
  49788. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49789. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49790. };
  49791. /**
  49792. * Interpolates a quaternion using a spherical linear interpolation
  49793. * @param startValue Start value of the animation curve
  49794. * @param endValue End value of the animation curve
  49795. * @param gradient Scalar amount to interpolate
  49796. * @returns Interpolated quaternion value
  49797. */
  49798. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49799. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49800. };
  49801. /**
  49802. * Interpolates a quaternion cubically
  49803. * @param startValue Start value of the animation curve
  49804. * @param outTangent End tangent of the animation curve
  49805. * @param endValue End value of the animation curve
  49806. * @param inTangent Start tangent of the animation curve
  49807. * @param gradient Scalar amount to interpolate
  49808. * @returns Interpolated quaternion value
  49809. */
  49810. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49811. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49812. };
  49813. /**
  49814. * Interpolates a Vector3 linearl
  49815. * @param startValue Start value of the animation curve
  49816. * @param endValue End value of the animation curve
  49817. * @param gradient Scalar amount to interpolate
  49818. * @returns Interpolated scalar value
  49819. */
  49820. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49821. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49822. };
  49823. /**
  49824. * Interpolates a Vector3 cubically
  49825. * @param startValue Start value of the animation curve
  49826. * @param outTangent End tangent of the animation
  49827. * @param endValue End value of the animation curve
  49828. * @param inTangent Start tangent of the animation curve
  49829. * @param gradient Scalar amount to interpolate
  49830. * @returns InterpolatedVector3 value
  49831. */
  49832. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49833. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49834. };
  49835. /**
  49836. * Interpolates a Vector2 linearly
  49837. * @param startValue Start value of the animation curve
  49838. * @param endValue End value of the animation curve
  49839. * @param gradient Scalar amount to interpolate
  49840. * @returns Interpolated Vector2 value
  49841. */
  49842. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49843. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49844. };
  49845. /**
  49846. * Interpolates a Vector2 cubically
  49847. * @param startValue Start value of the animation curve
  49848. * @param outTangent End tangent of the animation
  49849. * @param endValue End value of the animation curve
  49850. * @param inTangent Start tangent of the animation curve
  49851. * @param gradient Scalar amount to interpolate
  49852. * @returns Interpolated Vector2 value
  49853. */
  49854. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49855. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49856. };
  49857. /**
  49858. * Interpolates a size linearly
  49859. * @param startValue Start value of the animation curve
  49860. * @param endValue End value of the animation curve
  49861. * @param gradient Scalar amount to interpolate
  49862. * @returns Interpolated Size value
  49863. */
  49864. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49865. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49866. };
  49867. /**
  49868. * Interpolates a Color3 linearly
  49869. * @param startValue Start value of the animation curve
  49870. * @param endValue End value of the animation curve
  49871. * @param gradient Scalar amount to interpolate
  49872. * @returns Interpolated Color3 value
  49873. */
  49874. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49875. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49876. };
  49877. /**
  49878. * @hidden Internal use only
  49879. */
  49880. Animation.prototype._getKeyValue = function (value) {
  49881. if (typeof value === "function") {
  49882. return value();
  49883. }
  49884. return value;
  49885. };
  49886. /**
  49887. * @hidden Internal use only
  49888. */
  49889. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49890. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49891. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49892. }
  49893. var keys = this.getKeys();
  49894. // Try to get a hash to find the right key
  49895. 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));
  49896. if (keys[startKeyIndex].frame >= currentFrame) {
  49897. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49898. startKeyIndex--;
  49899. }
  49900. }
  49901. for (var key = startKeyIndex; key < keys.length; key++) {
  49902. var endKey = keys[key + 1];
  49903. if (endKey.frame >= currentFrame) {
  49904. var startKey = keys[key];
  49905. var startValue = this._getKeyValue(startKey.value);
  49906. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49907. return startValue;
  49908. }
  49909. var endValue = this._getKeyValue(endKey.value);
  49910. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49911. var frameDelta = endKey.frame - startKey.frame;
  49912. // gradient : percent of currentFrame between the frame inf and the frame sup
  49913. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49914. // check for easingFunction and correction of gradient
  49915. var easingFunction = this.getEasingFunction();
  49916. if (easingFunction != null) {
  49917. gradient = easingFunction.ease(gradient);
  49918. }
  49919. switch (this.dataType) {
  49920. // Float
  49921. case Animation.ANIMATIONTYPE_FLOAT:
  49922. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49923. switch (loopMode) {
  49924. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49925. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49926. return floatValue;
  49927. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49928. return offsetValue * repeatCount + floatValue;
  49929. }
  49930. break;
  49931. // Quaternion
  49932. case Animation.ANIMATIONTYPE_QUATERNION:
  49933. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49934. switch (loopMode) {
  49935. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49936. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49937. return quatValue;
  49938. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49939. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49940. }
  49941. return quatValue;
  49942. // Vector3
  49943. case Animation.ANIMATIONTYPE_VECTOR3:
  49944. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49945. switch (loopMode) {
  49946. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49947. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49948. return vec3Value;
  49949. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49950. return vec3Value.add(offsetValue.scale(repeatCount));
  49951. }
  49952. // Vector2
  49953. case Animation.ANIMATIONTYPE_VECTOR2:
  49954. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49955. switch (loopMode) {
  49956. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49957. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49958. return vec2Value;
  49959. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49960. return vec2Value.add(offsetValue.scale(repeatCount));
  49961. }
  49962. // Size
  49963. case Animation.ANIMATIONTYPE_SIZE:
  49964. switch (loopMode) {
  49965. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49966. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49967. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49968. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49969. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49970. }
  49971. // Color3
  49972. case Animation.ANIMATIONTYPE_COLOR3:
  49973. switch (loopMode) {
  49974. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49975. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49976. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49977. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49978. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49979. }
  49980. // Matrix
  49981. case Animation.ANIMATIONTYPE_MATRIX:
  49982. switch (loopMode) {
  49983. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49984. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49985. if (Animation.AllowMatricesInterpolation) {
  49986. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49987. }
  49988. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49989. return startValue;
  49990. }
  49991. default:
  49992. break;
  49993. }
  49994. break;
  49995. }
  49996. }
  49997. return this._getKeyValue(keys[keys.length - 1].value);
  49998. };
  49999. /**
  50000. * Defines the function to use to interpolate matrices
  50001. * @param startValue defines the start matrix
  50002. * @param endValue defines the end matrix
  50003. * @param gradient defines the gradient between both matrices
  50004. * @param result defines an optional target matrix where to store the interpolation
  50005. * @returns the interpolated matrix
  50006. */
  50007. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50008. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50009. if (result) {
  50010. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50011. return result;
  50012. }
  50013. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50014. }
  50015. if (result) {
  50016. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50017. return result;
  50018. }
  50019. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50020. };
  50021. /**
  50022. * Makes a copy of the animation
  50023. * @returns Cloned animation
  50024. */
  50025. Animation.prototype.clone = function () {
  50026. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50027. clone.enableBlending = this.enableBlending;
  50028. clone.blendingSpeed = this.blendingSpeed;
  50029. if (this._keys) {
  50030. clone.setKeys(this._keys);
  50031. }
  50032. if (this._ranges) {
  50033. clone._ranges = {};
  50034. for (var name in this._ranges) {
  50035. var range = this._ranges[name];
  50036. if (!range) {
  50037. continue;
  50038. }
  50039. clone._ranges[name] = range.clone();
  50040. }
  50041. }
  50042. return clone;
  50043. };
  50044. /**
  50045. * Sets the key frames of the animation
  50046. * @param values The animation key frames to set
  50047. */
  50048. Animation.prototype.setKeys = function (values) {
  50049. this._keys = values.slice(0);
  50050. };
  50051. /**
  50052. * Serializes the animation to an object
  50053. * @returns Serialized object
  50054. */
  50055. Animation.prototype.serialize = function () {
  50056. var serializationObject = {};
  50057. serializationObject.name = this.name;
  50058. serializationObject.property = this.targetProperty;
  50059. serializationObject.framePerSecond = this.framePerSecond;
  50060. serializationObject.dataType = this.dataType;
  50061. serializationObject.loopBehavior = this.loopMode;
  50062. serializationObject.enableBlending = this.enableBlending;
  50063. serializationObject.blendingSpeed = this.blendingSpeed;
  50064. var dataType = this.dataType;
  50065. serializationObject.keys = [];
  50066. var keys = this.getKeys();
  50067. for (var index = 0; index < keys.length; index++) {
  50068. var animationKey = keys[index];
  50069. var key = {};
  50070. key.frame = animationKey.frame;
  50071. switch (dataType) {
  50072. case Animation.ANIMATIONTYPE_FLOAT:
  50073. key.values = [animationKey.value];
  50074. break;
  50075. case Animation.ANIMATIONTYPE_QUATERNION:
  50076. case Animation.ANIMATIONTYPE_MATRIX:
  50077. case Animation.ANIMATIONTYPE_VECTOR3:
  50078. case Animation.ANIMATIONTYPE_COLOR3:
  50079. key.values = animationKey.value.asArray();
  50080. break;
  50081. }
  50082. serializationObject.keys.push(key);
  50083. }
  50084. serializationObject.ranges = [];
  50085. for (var name in this._ranges) {
  50086. var source = this._ranges[name];
  50087. if (!source) {
  50088. continue;
  50089. }
  50090. var range = {};
  50091. range.name = name;
  50092. range.from = source.from;
  50093. range.to = source.to;
  50094. serializationObject.ranges.push(range);
  50095. }
  50096. return serializationObject;
  50097. };
  50098. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50099. /**
  50100. * Get the float animation type
  50101. */
  50102. get: function () {
  50103. return Animation._ANIMATIONTYPE_FLOAT;
  50104. },
  50105. enumerable: true,
  50106. configurable: true
  50107. });
  50108. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50109. /**
  50110. * Get the Vector3 animation type
  50111. */
  50112. get: function () {
  50113. return Animation._ANIMATIONTYPE_VECTOR3;
  50114. },
  50115. enumerable: true,
  50116. configurable: true
  50117. });
  50118. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50119. /**
  50120. * Get the Vector2 animation type
  50121. */
  50122. get: function () {
  50123. return Animation._ANIMATIONTYPE_VECTOR2;
  50124. },
  50125. enumerable: true,
  50126. configurable: true
  50127. });
  50128. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50129. /**
  50130. * Get the Size animation type
  50131. */
  50132. get: function () {
  50133. return Animation._ANIMATIONTYPE_SIZE;
  50134. },
  50135. enumerable: true,
  50136. configurable: true
  50137. });
  50138. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50139. /**
  50140. * Get the Quaternion animation type
  50141. */
  50142. get: function () {
  50143. return Animation._ANIMATIONTYPE_QUATERNION;
  50144. },
  50145. enumerable: true,
  50146. configurable: true
  50147. });
  50148. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50149. /**
  50150. * Get the Matrix animation type
  50151. */
  50152. get: function () {
  50153. return Animation._ANIMATIONTYPE_MATRIX;
  50154. },
  50155. enumerable: true,
  50156. configurable: true
  50157. });
  50158. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50159. /**
  50160. * Get the Color3 animation type
  50161. */
  50162. get: function () {
  50163. return Animation._ANIMATIONTYPE_COLOR3;
  50164. },
  50165. enumerable: true,
  50166. configurable: true
  50167. });
  50168. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50169. /**
  50170. * Get the Relative Loop Mode
  50171. */
  50172. get: function () {
  50173. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50174. },
  50175. enumerable: true,
  50176. configurable: true
  50177. });
  50178. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50179. /**
  50180. * Get the Cycle Loop Mode
  50181. */
  50182. get: function () {
  50183. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50184. },
  50185. enumerable: true,
  50186. configurable: true
  50187. });
  50188. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50189. /**
  50190. * Get the Constant Loop Mode
  50191. */
  50192. get: function () {
  50193. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50194. },
  50195. enumerable: true,
  50196. configurable: true
  50197. });
  50198. /** @hidden */
  50199. Animation._UniversalLerp = function (left, right, amount) {
  50200. var constructor = left.constructor;
  50201. if (constructor.Lerp) { // Lerp supported
  50202. return constructor.Lerp(left, right, amount);
  50203. }
  50204. else if (constructor.Slerp) { // Slerp supported
  50205. return constructor.Slerp(left, right, amount);
  50206. }
  50207. else if (left.toFixed) { // Number
  50208. return left * (1.0 - amount) + amount * right;
  50209. }
  50210. else { // Blending not supported
  50211. return right;
  50212. }
  50213. };
  50214. /**
  50215. * Parses an animation object and creates an animation
  50216. * @param parsedAnimation Parsed animation object
  50217. * @returns Animation object
  50218. */
  50219. Animation.Parse = function (parsedAnimation) {
  50220. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50221. var dataType = parsedAnimation.dataType;
  50222. var keys = [];
  50223. var data;
  50224. var index;
  50225. if (parsedAnimation.enableBlending) {
  50226. animation.enableBlending = parsedAnimation.enableBlending;
  50227. }
  50228. if (parsedAnimation.blendingSpeed) {
  50229. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50230. }
  50231. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50232. var key = parsedAnimation.keys[index];
  50233. var inTangent;
  50234. var outTangent;
  50235. switch (dataType) {
  50236. case Animation.ANIMATIONTYPE_FLOAT:
  50237. data = key.values[0];
  50238. if (key.values.length >= 1) {
  50239. inTangent = key.values[1];
  50240. }
  50241. if (key.values.length >= 2) {
  50242. outTangent = key.values[2];
  50243. }
  50244. break;
  50245. case Animation.ANIMATIONTYPE_QUATERNION:
  50246. data = BABYLON.Quaternion.FromArray(key.values);
  50247. if (key.values.length >= 8) {
  50248. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50249. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50250. inTangent = _inTangent;
  50251. }
  50252. }
  50253. if (key.values.length >= 12) {
  50254. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50255. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50256. outTangent = _outTangent;
  50257. }
  50258. }
  50259. break;
  50260. case Animation.ANIMATIONTYPE_MATRIX:
  50261. data = BABYLON.Matrix.FromArray(key.values);
  50262. break;
  50263. case Animation.ANIMATIONTYPE_COLOR3:
  50264. data = BABYLON.Color3.FromArray(key.values);
  50265. break;
  50266. case Animation.ANIMATIONTYPE_VECTOR3:
  50267. default:
  50268. data = BABYLON.Vector3.FromArray(key.values);
  50269. break;
  50270. }
  50271. var keyData = {};
  50272. keyData.frame = key.frame;
  50273. keyData.value = data;
  50274. if (inTangent != undefined) {
  50275. keyData.inTangent = inTangent;
  50276. }
  50277. if (outTangent != undefined) {
  50278. keyData.outTangent = outTangent;
  50279. }
  50280. keys.push(keyData);
  50281. }
  50282. animation.setKeys(keys);
  50283. if (parsedAnimation.ranges) {
  50284. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50285. data = parsedAnimation.ranges[index];
  50286. animation.createRange(data.name, data.from, data.to);
  50287. }
  50288. }
  50289. return animation;
  50290. };
  50291. /**
  50292. * Appends the serialized animations from the source animations
  50293. * @param source Source containing the animations
  50294. * @param destination Target to store the animations
  50295. */
  50296. Animation.AppendSerializedAnimations = function (source, destination) {
  50297. if (source.animations) {
  50298. destination.animations = [];
  50299. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50300. var animation = source.animations[animationIndex];
  50301. destination.animations.push(animation.serialize());
  50302. }
  50303. }
  50304. };
  50305. /**
  50306. * Use matrix interpolation instead of using direct key value when animating matrices
  50307. */
  50308. Animation.AllowMatricesInterpolation = false;
  50309. /**
  50310. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50311. */
  50312. Animation.AllowMatrixDecomposeForInterpolation = true;
  50313. // Statics
  50314. /**
  50315. * Float animation type
  50316. */
  50317. Animation._ANIMATIONTYPE_FLOAT = 0;
  50318. /**
  50319. * Vector3 animation type
  50320. */
  50321. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50322. /**
  50323. * Quaternion animation type
  50324. */
  50325. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50326. /**
  50327. * Matrix animation type
  50328. */
  50329. Animation._ANIMATIONTYPE_MATRIX = 3;
  50330. /**
  50331. * Color3 animation type
  50332. */
  50333. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50334. /**
  50335. * Vector2 animation type
  50336. */
  50337. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50338. /**
  50339. * Size animation type
  50340. */
  50341. Animation._ANIMATIONTYPE_SIZE = 6;
  50342. /**
  50343. * Relative Loop Mode
  50344. */
  50345. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50346. /**
  50347. * Cycle Loop Mode
  50348. */
  50349. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50350. /**
  50351. * Constant Loop Mode
  50352. */
  50353. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50354. return Animation;
  50355. }());
  50356. BABYLON.Animation = Animation;
  50357. })(BABYLON || (BABYLON = {}));
  50358. //# sourceMappingURL=babylon.animation.js.map
  50359. var BABYLON;
  50360. (function (BABYLON) {
  50361. /**
  50362. * This class defines the direct association between an animation and a target
  50363. */
  50364. var TargetedAnimation = /** @class */ (function () {
  50365. function TargetedAnimation() {
  50366. }
  50367. return TargetedAnimation;
  50368. }());
  50369. BABYLON.TargetedAnimation = TargetedAnimation;
  50370. /**
  50371. * Use this class to create coordinated animations on multiple targets
  50372. */
  50373. var AnimationGroup = /** @class */ (function () {
  50374. function AnimationGroup(name, scene) {
  50375. if (scene === void 0) { scene = null; }
  50376. this.name = name;
  50377. this._targetedAnimations = new Array();
  50378. this._animatables = new Array();
  50379. this._from = Number.MAX_VALUE;
  50380. this._to = -Number.MAX_VALUE;
  50381. this._speedRatio = 1;
  50382. this.onAnimationEndObservable = new BABYLON.Observable();
  50383. /**
  50384. * This observable will notify when all animations have ended.
  50385. */
  50386. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50387. /**
  50388. * This observable will notify when all animations have paused.
  50389. */
  50390. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  50391. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50392. this._scene.animationGroups.push(this);
  50393. }
  50394. Object.defineProperty(AnimationGroup.prototype, "from", {
  50395. /**
  50396. * Gets the first frame
  50397. */
  50398. get: function () {
  50399. return this._from;
  50400. },
  50401. enumerable: true,
  50402. configurable: true
  50403. });
  50404. Object.defineProperty(AnimationGroup.prototype, "to", {
  50405. /**
  50406. * Gets the last frame
  50407. */
  50408. get: function () {
  50409. return this._to;
  50410. },
  50411. enumerable: true,
  50412. configurable: true
  50413. });
  50414. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50415. /**
  50416. * Define if the animations are started
  50417. */
  50418. get: function () {
  50419. return this._isStarted;
  50420. },
  50421. enumerable: true,
  50422. configurable: true
  50423. });
  50424. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50425. /**
  50426. * Gets or sets the speed ratio to use for all animations
  50427. */
  50428. get: function () {
  50429. return this._speedRatio;
  50430. },
  50431. /**
  50432. * Gets or sets the speed ratio to use for all animations
  50433. */
  50434. set: function (value) {
  50435. if (this._speedRatio === value) {
  50436. return;
  50437. }
  50438. this._speedRatio = value;
  50439. for (var index = 0; index < this._animatables.length; index++) {
  50440. var animatable = this._animatables[index];
  50441. animatable.speedRatio = this._speedRatio;
  50442. }
  50443. },
  50444. enumerable: true,
  50445. configurable: true
  50446. });
  50447. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50448. /**
  50449. * Gets the targeted animations for this animation group
  50450. */
  50451. get: function () {
  50452. return this._targetedAnimations;
  50453. },
  50454. enumerable: true,
  50455. configurable: true
  50456. });
  50457. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50458. /**
  50459. * returning the list of animatables controlled by this animation group.
  50460. */
  50461. get: function () {
  50462. return this._animatables;
  50463. },
  50464. enumerable: true,
  50465. configurable: true
  50466. });
  50467. /**
  50468. * Add an animation (with its target) in the group
  50469. * @param animation defines the animation we want to add
  50470. * @param target defines the target of the animation
  50471. * @returns the {BABYLON.TargetedAnimation} object
  50472. */
  50473. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50474. var targetedAnimation = {
  50475. animation: animation,
  50476. target: target
  50477. };
  50478. var keys = animation.getKeys();
  50479. if (this._from > keys[0].frame) {
  50480. this._from = keys[0].frame;
  50481. }
  50482. if (this._to < keys[keys.length - 1].frame) {
  50483. this._to = keys[keys.length - 1].frame;
  50484. }
  50485. this._targetedAnimations.push(targetedAnimation);
  50486. return targetedAnimation;
  50487. };
  50488. /**
  50489. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50490. * It can add constant keys at begin or end
  50491. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50492. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50493. */
  50494. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50495. if (beginFrame === void 0) { beginFrame = null; }
  50496. if (endFrame === void 0) { endFrame = null; }
  50497. if (beginFrame == null)
  50498. beginFrame = this._from;
  50499. if (endFrame == null)
  50500. endFrame = this._to;
  50501. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50502. var targetedAnimation = this._targetedAnimations[index];
  50503. var keys = targetedAnimation.animation.getKeys();
  50504. var startKey = keys[0];
  50505. var endKey = keys[keys.length - 1];
  50506. if (startKey.frame > beginFrame) {
  50507. var newKey = {
  50508. frame: beginFrame,
  50509. value: startKey.value,
  50510. inTangent: startKey.inTangent,
  50511. outTangent: startKey.outTangent,
  50512. interpolation: startKey.interpolation
  50513. };
  50514. keys.splice(0, 0, newKey);
  50515. }
  50516. if (endKey.frame < endFrame) {
  50517. var newKey = {
  50518. frame: endFrame,
  50519. value: endKey.value,
  50520. inTangent: endKey.outTangent,
  50521. outTangent: endKey.outTangent,
  50522. interpolation: endKey.interpolation
  50523. };
  50524. keys.push(newKey);
  50525. }
  50526. }
  50527. this._from = beginFrame;
  50528. this._to = endFrame;
  50529. return this;
  50530. };
  50531. /**
  50532. * Start all animations on given targets
  50533. * @param loop defines if animations must loop
  50534. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50535. * @param from defines the from key (optional)
  50536. * @param to defines the to key (optional)
  50537. * @returns the current animation group
  50538. */
  50539. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50540. var _this = this;
  50541. if (loop === void 0) { loop = false; }
  50542. if (speedRatio === void 0) { speedRatio = 1; }
  50543. if (this._isStarted || this._targetedAnimations.length === 0) {
  50544. return this;
  50545. }
  50546. var _loop_1 = function (targetedAnimation) {
  50547. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50548. animatable.onAnimationEnd = function () {
  50549. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50550. _this._checkAnimationGroupEnded(animatable);
  50551. };
  50552. this_1._animatables.push(animatable);
  50553. };
  50554. var this_1 = this;
  50555. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50556. var targetedAnimation = _a[_i];
  50557. _loop_1(targetedAnimation);
  50558. }
  50559. this._speedRatio = speedRatio;
  50560. this._isStarted = true;
  50561. return this;
  50562. };
  50563. /**
  50564. * Pause all animations
  50565. */
  50566. AnimationGroup.prototype.pause = function () {
  50567. if (!this._isStarted) {
  50568. return this;
  50569. }
  50570. for (var index = 0; index < this._animatables.length; index++) {
  50571. var animatable = this._animatables[index];
  50572. animatable.pause();
  50573. }
  50574. this.onAnimationGroupPauseObservable.notifyObservers(this);
  50575. return this;
  50576. };
  50577. /**
  50578. * Play all animations to initial state
  50579. * This function will start() the animations if they were not started or will restart() them if they were paused
  50580. * @param loop defines if animations must loop
  50581. */
  50582. AnimationGroup.prototype.play = function (loop) {
  50583. // only if all animatables are ready and exist
  50584. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50585. if (loop !== undefined) {
  50586. for (var index = 0; index < this._animatables.length; index++) {
  50587. var animatable = this._animatables[index];
  50588. animatable.loopAnimation = loop;
  50589. }
  50590. }
  50591. this.restart();
  50592. }
  50593. else {
  50594. this.stop();
  50595. this.start(loop, this._speedRatio);
  50596. }
  50597. return this;
  50598. };
  50599. /**
  50600. * Reset all animations to initial state
  50601. */
  50602. AnimationGroup.prototype.reset = function () {
  50603. if (!this._isStarted) {
  50604. return this;
  50605. }
  50606. for (var index = 0; index < this._animatables.length; index++) {
  50607. var animatable = this._animatables[index];
  50608. animatable.reset();
  50609. }
  50610. return this;
  50611. };
  50612. /**
  50613. * Restart animations from key 0
  50614. */
  50615. AnimationGroup.prototype.restart = function () {
  50616. if (!this._isStarted) {
  50617. return this;
  50618. }
  50619. for (var index = 0; index < this._animatables.length; index++) {
  50620. var animatable = this._animatables[index];
  50621. animatable.restart();
  50622. }
  50623. return this;
  50624. };
  50625. /**
  50626. * Stop all animations
  50627. */
  50628. AnimationGroup.prototype.stop = function () {
  50629. if (!this._isStarted) {
  50630. return this;
  50631. }
  50632. var list = this._animatables.slice();
  50633. for (var index = 0; index < list.length; index++) {
  50634. list[index].stop();
  50635. }
  50636. this._isStarted = false;
  50637. return this;
  50638. };
  50639. /**
  50640. * Set animation weight for all animatables
  50641. * @param weight defines the weight to use
  50642. * @return the animationGroup
  50643. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50644. */
  50645. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50646. for (var index = 0; index < this._animatables.length; index++) {
  50647. var animatable = this._animatables[index];
  50648. animatable.weight = weight;
  50649. }
  50650. return this;
  50651. };
  50652. /**
  50653. * Synchronize and normalize all animatables with a source animatable
  50654. * @param root defines the root animatable to synchronize with
  50655. * @return the animationGroup
  50656. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50657. */
  50658. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50659. for (var index = 0; index < this._animatables.length; index++) {
  50660. var animatable = this._animatables[index];
  50661. animatable.syncWith(root);
  50662. }
  50663. return this;
  50664. };
  50665. /**
  50666. * Goes to a specific frame in this animation group
  50667. * @param frame the frame number to go to
  50668. * @return the animationGroup
  50669. */
  50670. AnimationGroup.prototype.goToFrame = function (frame) {
  50671. if (!this._isStarted) {
  50672. return this;
  50673. }
  50674. for (var index = 0; index < this._animatables.length; index++) {
  50675. var animatable = this._animatables[index];
  50676. animatable.goToFrame(frame);
  50677. }
  50678. return this;
  50679. };
  50680. /**
  50681. * Dispose all associated resources
  50682. */
  50683. AnimationGroup.prototype.dispose = function () {
  50684. this._targetedAnimations = [];
  50685. this._animatables = [];
  50686. var index = this._scene.animationGroups.indexOf(this);
  50687. if (index > -1) {
  50688. this._scene.animationGroups.splice(index, 1);
  50689. }
  50690. };
  50691. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50692. // animatable should be taken out of the array
  50693. var idx = this._animatables.indexOf(animatable);
  50694. if (idx > -1) {
  50695. this._animatables.splice(idx, 1);
  50696. }
  50697. // all animatables were removed? animation group ended!
  50698. if (this._animatables.length === 0) {
  50699. this._isStarted = false;
  50700. this.onAnimationGroupEndObservable.notifyObservers(this);
  50701. }
  50702. };
  50703. // Statics
  50704. /**
  50705. * Returns a new AnimationGroup object parsed from the source provided.
  50706. * @param parsedAnimationGroup defines the source
  50707. * @param scene defines the scene that will receive the animationGroup
  50708. * @returns a new AnimationGroup
  50709. */
  50710. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  50711. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  50712. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  50713. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  50714. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  50715. var id = targetedAnimation.targetId;
  50716. var targetNode = scene.getNodeByID(id);
  50717. if (targetNode != null)
  50718. animationGroup.addTargetedAnimation(animation, targetNode);
  50719. }
  50720. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  50721. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  50722. return animationGroup;
  50723. };
  50724. /**
  50725. * Returns the string "AnimationGroup"
  50726. * @returns "AnimationGroup"
  50727. */
  50728. AnimationGroup.prototype.getClassName = function () {
  50729. return "AnimationGroup";
  50730. };
  50731. /**
  50732. * Creates a detailled string about the object
  50733. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  50734. * @returns a string representing the object
  50735. */
  50736. AnimationGroup.prototype.toString = function (fullDetails) {
  50737. var ret = "Name: " + this.name;
  50738. ret += ", type: " + this.getClassName();
  50739. if (fullDetails) {
  50740. ret += ", from: " + this._from;
  50741. ret += ", to: " + this._to;
  50742. ret += ", isStarted: " + this._isStarted;
  50743. ret += ", speedRatio: " + this._speedRatio;
  50744. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  50745. ret += ", animatables length: " + this._animatables;
  50746. }
  50747. return ret;
  50748. };
  50749. return AnimationGroup;
  50750. }());
  50751. BABYLON.AnimationGroup = AnimationGroup;
  50752. })(BABYLON || (BABYLON = {}));
  50753. //# sourceMappingURL=babylon.animationGroup.js.map
  50754. var BABYLON;
  50755. (function (BABYLON) {
  50756. // Static values to help the garbage collector
  50757. // Quaternion
  50758. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  50759. // Vector3
  50760. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  50761. // Vector2
  50762. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  50763. // Size
  50764. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  50765. // Color3
  50766. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  50767. /**
  50768. * Defines a runtime animation
  50769. */
  50770. var RuntimeAnimation = /** @class */ (function () {
  50771. /**
  50772. * Create a new RuntimeAnimation object
  50773. * @param target defines the target of the animation
  50774. * @param animation defines the source animation object
  50775. * @param scene defines the hosting scene
  50776. * @param host defines the initiating Animatable
  50777. */
  50778. function RuntimeAnimation(target, animation, scene, host) {
  50779. var _this = this;
  50780. this._events = new Array();
  50781. /**
  50782. * The current frame of the runtime animation
  50783. */
  50784. this._currentFrame = 0;
  50785. /**
  50786. * The original value of the runtime animation
  50787. */
  50788. this._originalValue = new Array();
  50789. /**
  50790. * The offsets cache of the runtime animation
  50791. */
  50792. this._offsetsCache = {};
  50793. /**
  50794. * The high limits cache of the runtime animation
  50795. */
  50796. this._highLimitsCache = {};
  50797. /**
  50798. * Specifies if the runtime animation has been stopped
  50799. */
  50800. this._stopped = false;
  50801. /**
  50802. * The blending factor of the runtime animation
  50803. */
  50804. this._blendingFactor = 0;
  50805. /**
  50806. * The target path of the runtime animation
  50807. */
  50808. this._targetPath = "";
  50809. /**
  50810. * The weight of the runtime animation
  50811. */
  50812. this._weight = 1.0;
  50813. /**
  50814. * The ratio offset of the runtime animation
  50815. */
  50816. this._ratioOffset = 0;
  50817. /**
  50818. * The previous delay of the runtime animation
  50819. */
  50820. this._previousDelay = 0;
  50821. /**
  50822. * The previous ratio of the runtime animation
  50823. */
  50824. this._previousRatio = 0;
  50825. this._animation = animation;
  50826. this._target = target;
  50827. this._scene = scene;
  50828. this._host = host;
  50829. animation._runtimeAnimations.push(this);
  50830. // Cloning events locally
  50831. var events = animation.getEvents();
  50832. if (events && events.length > 0) {
  50833. events.forEach(function (e) {
  50834. _this._events.push(e._clone());
  50835. });
  50836. }
  50837. }
  50838. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50839. /**
  50840. * Gets the current frame of the runtime animation
  50841. */
  50842. get: function () {
  50843. return this._currentFrame;
  50844. },
  50845. enumerable: true,
  50846. configurable: true
  50847. });
  50848. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50849. /**
  50850. * Gets the weight of the runtime animation
  50851. */
  50852. get: function () {
  50853. return this._weight;
  50854. },
  50855. enumerable: true,
  50856. configurable: true
  50857. });
  50858. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50859. /**
  50860. * Gets the current value of the runtime animation
  50861. */
  50862. get: function () {
  50863. return this._currentValue;
  50864. },
  50865. enumerable: true,
  50866. configurable: true
  50867. });
  50868. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50869. /**
  50870. * Gets the target path of the runtime animation
  50871. */
  50872. get: function () {
  50873. return this._targetPath;
  50874. },
  50875. enumerable: true,
  50876. configurable: true
  50877. });
  50878. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50879. /**
  50880. * Gets the actual target of the runtime animation
  50881. */
  50882. get: function () {
  50883. return this._activeTarget;
  50884. },
  50885. enumerable: true,
  50886. configurable: true
  50887. });
  50888. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50889. /**
  50890. * Gets the animation from the runtime animation
  50891. */
  50892. get: function () {
  50893. return this._animation;
  50894. },
  50895. enumerable: true,
  50896. configurable: true
  50897. });
  50898. /**
  50899. * Resets the runtime animation to the beginning
  50900. * @param restoreOriginal defines whether to restore the target property to the original value
  50901. */
  50902. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50903. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50904. if (restoreOriginal) {
  50905. if (this._target instanceof Array) {
  50906. var index = 0;
  50907. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50908. var target = _a[_i];
  50909. if (this._originalValue[index] !== undefined) {
  50910. this._setValue(target, this._originalValue[index], -1);
  50911. }
  50912. index++;
  50913. }
  50914. }
  50915. else {
  50916. if (this._originalValue[0] !== undefined) {
  50917. this._setValue(this._target, this._originalValue[0], -1);
  50918. }
  50919. }
  50920. }
  50921. this._offsetsCache = {};
  50922. this._highLimitsCache = {};
  50923. this._currentFrame = 0;
  50924. this._blendingFactor = 0;
  50925. this._originalValue = new Array();
  50926. // Events
  50927. for (var index = 0; index < this._events.length; index++) {
  50928. this._events[index].isDone = false;
  50929. }
  50930. };
  50931. /**
  50932. * Specifies if the runtime animation is stopped
  50933. * @returns Boolean specifying if the runtime animation is stopped
  50934. */
  50935. RuntimeAnimation.prototype.isStopped = function () {
  50936. return this._stopped;
  50937. };
  50938. /**
  50939. * Disposes of the runtime animation
  50940. */
  50941. RuntimeAnimation.prototype.dispose = function () {
  50942. var index = this._animation.runtimeAnimations.indexOf(this);
  50943. if (index > -1) {
  50944. this._animation.runtimeAnimations.splice(index, 1);
  50945. }
  50946. };
  50947. /**
  50948. * Interpolates the animation from the current frame
  50949. * @param currentFrame The frame to interpolate the animation to
  50950. * @param repeatCount The number of times that the animation should loop
  50951. * @param loopMode The type of looping mode to use
  50952. * @param offsetValue Animation offset value
  50953. * @param highLimitValue The high limit value
  50954. * @returns The interpolated value
  50955. */
  50956. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50957. this._currentFrame = currentFrame;
  50958. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50959. this._workValue = BABYLON.Matrix.Zero();
  50960. }
  50961. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50962. };
  50963. /**
  50964. * Apply the interpolated value to the target
  50965. * @param currentValue defines the value computed by the animation
  50966. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50967. */
  50968. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50969. if (weight === void 0) { weight = 1.0; }
  50970. if (this._target instanceof Array) {
  50971. var index = 0;
  50972. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50973. var target = _a[_i];
  50974. this._setValue(target, currentValue, weight, index);
  50975. index++;
  50976. }
  50977. }
  50978. else {
  50979. this._setValue(this._target, currentValue, weight);
  50980. }
  50981. };
  50982. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50983. if (targetIndex === void 0) { targetIndex = 0; }
  50984. // Set value
  50985. var path;
  50986. var destination;
  50987. var targetPropertyPath = this._animation.targetPropertyPath;
  50988. if (targetPropertyPath.length > 1) {
  50989. var property = target[targetPropertyPath[0]];
  50990. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50991. property = property[targetPropertyPath[index]];
  50992. }
  50993. path = targetPropertyPath[targetPropertyPath.length - 1];
  50994. destination = property;
  50995. }
  50996. else {
  50997. path = targetPropertyPath[0];
  50998. destination = target;
  50999. }
  51000. this._targetPath = path;
  51001. this._activeTarget = destination;
  51002. this._weight = weight;
  51003. if (this._originalValue[targetIndex] === undefined) {
  51004. var originalValue = void 0;
  51005. if (destination.getRestPose && path === "_matrix") { // For bones
  51006. originalValue = destination.getRestPose();
  51007. }
  51008. else {
  51009. originalValue = destination[path];
  51010. }
  51011. if (originalValue && originalValue.clone) {
  51012. this._originalValue[targetIndex] = originalValue.clone();
  51013. }
  51014. else {
  51015. this._originalValue[targetIndex] = originalValue;
  51016. }
  51017. }
  51018. // Blending
  51019. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51020. if (enableBlending && this._blendingFactor <= 1.0) {
  51021. if (!this._originalBlendValue) {
  51022. var originalValue = destination[path];
  51023. if (originalValue.clone) {
  51024. this._originalBlendValue = originalValue.clone();
  51025. }
  51026. else {
  51027. this._originalBlendValue = originalValue;
  51028. }
  51029. }
  51030. if (this._originalBlendValue.m) { // Matrix
  51031. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51032. if (this._currentValue) {
  51033. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51034. }
  51035. else {
  51036. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51037. }
  51038. }
  51039. else {
  51040. if (this._currentValue) {
  51041. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51042. }
  51043. else {
  51044. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51045. }
  51046. }
  51047. }
  51048. else {
  51049. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51050. }
  51051. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51052. this._blendingFactor += blendingSpeed;
  51053. }
  51054. else {
  51055. this._currentValue = currentValue;
  51056. }
  51057. if (weight !== -1.0) {
  51058. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51059. }
  51060. else {
  51061. destination[path] = this._currentValue;
  51062. }
  51063. if (target.markAsDirty) {
  51064. target.markAsDirty(this._animation.targetProperty);
  51065. }
  51066. };
  51067. /**
  51068. * Gets the loop pmode of the runtime animation
  51069. * @returns Loop Mode
  51070. */
  51071. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51072. if (this._target && this._target.animationPropertiesOverride) {
  51073. return this._target.animationPropertiesOverride.loopMode;
  51074. }
  51075. return this._animation.loopMode;
  51076. };
  51077. /**
  51078. * Move the current animation to a given frame
  51079. * @param frame defines the frame to move to
  51080. */
  51081. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51082. var keys = this._animation.getKeys();
  51083. if (frame < keys[0].frame) {
  51084. frame = keys[0].frame;
  51085. }
  51086. else if (frame > keys[keys.length - 1].frame) {
  51087. frame = keys[keys.length - 1].frame;
  51088. }
  51089. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51090. this.setValue(currentValue, -1);
  51091. };
  51092. /**
  51093. * @hidden Internal use only
  51094. */
  51095. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51096. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51097. this._ratioOffset = this._previousRatio - newRatio;
  51098. };
  51099. /**
  51100. * Execute the current animation
  51101. * @param delay defines the delay to add to the current frame
  51102. * @param from defines the lower bound of the animation range
  51103. * @param to defines the upper bound of the animation range
  51104. * @param loop defines if the current animation must loop
  51105. * @param speedRatio defines the current speed ratio
  51106. * @param weight defines the weight of the animation (default is -1 so no weight)
  51107. * @returns a boolean indicating if the animation is running
  51108. */
  51109. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51110. if (weight === void 0) { weight = -1.0; }
  51111. var targetPropertyPath = this._animation.targetPropertyPath;
  51112. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51113. this._stopped = true;
  51114. return false;
  51115. }
  51116. var returnValue = true;
  51117. var keys = this._animation.getKeys();
  51118. // Adding a start key at frame 0 if missing
  51119. if (keys[0].frame !== 0) {
  51120. var newKey = { frame: 0, value: keys[0].value };
  51121. keys.splice(0, 0, newKey);
  51122. }
  51123. // Adding a duplicate key when there is only one key at frame zero
  51124. else if (keys.length === 1) {
  51125. var newKey = { frame: 0.001, value: keys[0].value };
  51126. keys.push(newKey);
  51127. }
  51128. // Check limits
  51129. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51130. from = keys[0].frame;
  51131. }
  51132. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51133. to = keys[keys.length - 1].frame;
  51134. }
  51135. //to and from cannot be the same key
  51136. if (from === to) {
  51137. if (from > keys[0].frame) {
  51138. from--;
  51139. }
  51140. else if (to < keys[keys.length - 1].frame) {
  51141. to++;
  51142. }
  51143. }
  51144. // Compute ratio
  51145. var range = to - from;
  51146. var offsetValue;
  51147. // ratio represents the frame delta between from and to
  51148. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51149. var highLimitValue = 0;
  51150. this._previousDelay = delay;
  51151. this._previousRatio = ratio;
  51152. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51153. returnValue = false;
  51154. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51155. }
  51156. else {
  51157. // Get max value if required
  51158. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51159. var keyOffset = to.toString() + from.toString();
  51160. if (!this._offsetsCache[keyOffset]) {
  51161. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51162. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51163. switch (this._animation.dataType) {
  51164. // Float
  51165. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51166. this._offsetsCache[keyOffset] = toValue - fromValue;
  51167. break;
  51168. // Quaternion
  51169. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51170. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51171. break;
  51172. // Vector3
  51173. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51174. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51175. // Vector2
  51176. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51177. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51178. // Size
  51179. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51180. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51181. // Color3
  51182. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51183. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51184. default:
  51185. break;
  51186. }
  51187. this._highLimitsCache[keyOffset] = toValue;
  51188. }
  51189. highLimitValue = this._highLimitsCache[keyOffset];
  51190. offsetValue = this._offsetsCache[keyOffset];
  51191. }
  51192. }
  51193. if (offsetValue === undefined) {
  51194. switch (this._animation.dataType) {
  51195. // Float
  51196. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51197. offsetValue = 0;
  51198. break;
  51199. // Quaternion
  51200. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51201. offsetValue = _staticOffsetValueQuaternion;
  51202. break;
  51203. // Vector3
  51204. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51205. offsetValue = _staticOffsetValueVector3;
  51206. break;
  51207. // Vector2
  51208. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51209. offsetValue = _staticOffsetValueVector2;
  51210. break;
  51211. // Size
  51212. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51213. offsetValue = _staticOffsetValueSize;
  51214. break;
  51215. // Color3
  51216. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51217. offsetValue = _staticOffsetValueColor3;
  51218. }
  51219. }
  51220. // Compute value
  51221. var repeatCount = (ratio / range) >> 0;
  51222. var currentFrame = returnValue ? from + ratio % range : to;
  51223. // Need to normalize?
  51224. if (this._host && this._host.syncRoot) {
  51225. var syncRoot = this._host.syncRoot;
  51226. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51227. currentFrame = from + (to - from) * hostNormalizedFrame;
  51228. }
  51229. // Reset events if looping
  51230. var events = this._events;
  51231. if (range > 0 && this.currentFrame > currentFrame ||
  51232. range < 0 && this.currentFrame < currentFrame) {
  51233. // Need to reset animation events
  51234. for (var index = 0; index < events.length; index++) {
  51235. if (!events[index].onlyOnce) {
  51236. // reset event, the animation is looping
  51237. events[index].isDone = false;
  51238. }
  51239. }
  51240. }
  51241. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51242. // Set value
  51243. this.setValue(currentValue, weight);
  51244. // Check events
  51245. for (var index = 0; index < events.length; index++) {
  51246. // Make sure current frame has passed event frame and that event frame is within the current range
  51247. // Also, handle both forward and reverse animations
  51248. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51249. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51250. var event = events[index];
  51251. if (!event.isDone) {
  51252. // If event should be done only once, remove it.
  51253. if (event.onlyOnce) {
  51254. events.splice(index, 1);
  51255. index--;
  51256. }
  51257. event.isDone = true;
  51258. event.action(currentFrame);
  51259. } // Don't do anything if the event has already be done.
  51260. }
  51261. }
  51262. if (!returnValue) {
  51263. this._stopped = true;
  51264. }
  51265. return returnValue;
  51266. };
  51267. return RuntimeAnimation;
  51268. }());
  51269. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51270. })(BABYLON || (BABYLON = {}));
  51271. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51272. var BABYLON;
  51273. (function (BABYLON) {
  51274. /**
  51275. * Class used to store an actual running animation
  51276. */
  51277. var Animatable = /** @class */ (function () {
  51278. /**
  51279. * Creates a new Animatable
  51280. * @param scene defines the hosting scene
  51281. * @param target defines the target object
  51282. * @param fromFrame defines the starting frame number (default is 0)
  51283. * @param toFrame defines the ending frame number (default is 100)
  51284. * @param loopAnimation defines if the animation must loop (default is false)
  51285. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51286. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51287. * @param animations defines a group of animation to add to the new Animatable
  51288. */
  51289. function Animatable(scene,
  51290. /** defines the target object */
  51291. target,
  51292. /** defines the starting frame number (default is 0) */
  51293. fromFrame,
  51294. /** defines the ending frame number (default is 100) */
  51295. toFrame,
  51296. /** defines if the animation must loop (default is false) */
  51297. loopAnimation, speedRatio,
  51298. /** defines a callback to call when animation ends if it is not looping */
  51299. onAnimationEnd, animations) {
  51300. if (fromFrame === void 0) { fromFrame = 0; }
  51301. if (toFrame === void 0) { toFrame = 100; }
  51302. if (loopAnimation === void 0) { loopAnimation = false; }
  51303. if (speedRatio === void 0) { speedRatio = 1.0; }
  51304. this.target = target;
  51305. this.fromFrame = fromFrame;
  51306. this.toFrame = toFrame;
  51307. this.loopAnimation = loopAnimation;
  51308. this.onAnimationEnd = onAnimationEnd;
  51309. this._localDelayOffset = null;
  51310. this._pausedDelay = null;
  51311. this._runtimeAnimations = new Array();
  51312. this._paused = false;
  51313. this._speedRatio = 1;
  51314. this._weight = -1.0;
  51315. /**
  51316. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51317. * This will only apply for non looping animation (default is true)
  51318. */
  51319. this.disposeOnEnd = true;
  51320. /**
  51321. * Gets a boolean indicating if the animation has started
  51322. */
  51323. this.animationStarted = false;
  51324. /**
  51325. * Observer raised when the animation ends
  51326. */
  51327. this.onAnimationEndObservable = new BABYLON.Observable();
  51328. this._scene = scene;
  51329. if (animations) {
  51330. this.appendAnimations(target, animations);
  51331. }
  51332. this._speedRatio = speedRatio;
  51333. scene._activeAnimatables.push(this);
  51334. }
  51335. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51336. /**
  51337. * Gets the root Animatable used to synchronize and normalize animations
  51338. */
  51339. get: function () {
  51340. return this._syncRoot;
  51341. },
  51342. enumerable: true,
  51343. configurable: true
  51344. });
  51345. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51346. /**
  51347. * Gets the current frame of the first RuntimeAnimation
  51348. * Used to synchronize Animatables
  51349. */
  51350. get: function () {
  51351. if (this._runtimeAnimations.length === 0) {
  51352. return 0;
  51353. }
  51354. return this._runtimeAnimations[0].currentFrame;
  51355. },
  51356. enumerable: true,
  51357. configurable: true
  51358. });
  51359. Object.defineProperty(Animatable.prototype, "weight", {
  51360. /**
  51361. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51362. */
  51363. get: function () {
  51364. return this._weight;
  51365. },
  51366. set: function (value) {
  51367. if (value === -1) { // -1 is ok and means no weight
  51368. this._weight = -1;
  51369. return;
  51370. }
  51371. // Else weight must be in [0, 1] range
  51372. this._weight = Math.min(Math.max(value, 0), 1.0);
  51373. },
  51374. enumerable: true,
  51375. configurable: true
  51376. });
  51377. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51378. /**
  51379. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51380. */
  51381. get: function () {
  51382. return this._speedRatio;
  51383. },
  51384. set: function (value) {
  51385. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51386. var animation = this._runtimeAnimations[index];
  51387. animation._prepareForSpeedRatioChange(value);
  51388. }
  51389. this._speedRatio = value;
  51390. },
  51391. enumerable: true,
  51392. configurable: true
  51393. });
  51394. // Methods
  51395. /**
  51396. * Synchronize and normalize current Animatable with a source Animatable
  51397. * This is useful when using animation weights and when animations are not of the same length
  51398. * @param root defines the root Animatable to synchronize with
  51399. * @returns the current Animatable
  51400. */
  51401. Animatable.prototype.syncWith = function (root) {
  51402. this._syncRoot = root;
  51403. if (root) {
  51404. // Make sure this animatable will animate after the root
  51405. var index = this._scene._activeAnimatables.indexOf(this);
  51406. if (index > -1) {
  51407. this._scene._activeAnimatables.splice(index, 1);
  51408. this._scene._activeAnimatables.push(this);
  51409. }
  51410. }
  51411. return this;
  51412. };
  51413. /**
  51414. * Gets the list of runtime animations
  51415. * @returns an array of RuntimeAnimation
  51416. */
  51417. Animatable.prototype.getAnimations = function () {
  51418. return this._runtimeAnimations;
  51419. };
  51420. /**
  51421. * Adds more animations to the current animatable
  51422. * @param target defines the target of the animations
  51423. * @param animations defines the new animations to add
  51424. */
  51425. Animatable.prototype.appendAnimations = function (target, animations) {
  51426. for (var index = 0; index < animations.length; index++) {
  51427. var animation = animations[index];
  51428. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51429. }
  51430. };
  51431. /**
  51432. * Gets the source animation for a specific property
  51433. * @param property defines the propertyu to look for
  51434. * @returns null or the source animation for the given property
  51435. */
  51436. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51437. var runtimeAnimations = this._runtimeAnimations;
  51438. for (var index = 0; index < runtimeAnimations.length; index++) {
  51439. if (runtimeAnimations[index].animation.targetProperty === property) {
  51440. return runtimeAnimations[index].animation;
  51441. }
  51442. }
  51443. return null;
  51444. };
  51445. /**
  51446. * Gets the runtime animation for a specific property
  51447. * @param property defines the propertyu to look for
  51448. * @returns null or the runtime animation for the given property
  51449. */
  51450. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51451. var runtimeAnimations = this._runtimeAnimations;
  51452. for (var index = 0; index < runtimeAnimations.length; index++) {
  51453. if (runtimeAnimations[index].animation.targetProperty === property) {
  51454. return runtimeAnimations[index];
  51455. }
  51456. }
  51457. return null;
  51458. };
  51459. /**
  51460. * Resets the animatable to its original state
  51461. */
  51462. Animatable.prototype.reset = function () {
  51463. var runtimeAnimations = this._runtimeAnimations;
  51464. for (var index = 0; index < runtimeAnimations.length; index++) {
  51465. runtimeAnimations[index].reset(true);
  51466. }
  51467. this._localDelayOffset = null;
  51468. this._pausedDelay = null;
  51469. };
  51470. /**
  51471. * Allows the animatable to blend with current running animations
  51472. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51473. * @param blendingSpeed defines the blending speed to use
  51474. */
  51475. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51476. var runtimeAnimations = this._runtimeAnimations;
  51477. for (var index = 0; index < runtimeAnimations.length; index++) {
  51478. runtimeAnimations[index].animation.enableBlending = true;
  51479. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51480. }
  51481. };
  51482. /**
  51483. * Disable animation blending
  51484. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51485. */
  51486. Animatable.prototype.disableBlending = function () {
  51487. var runtimeAnimations = this._runtimeAnimations;
  51488. for (var index = 0; index < runtimeAnimations.length; index++) {
  51489. runtimeAnimations[index].animation.enableBlending = false;
  51490. }
  51491. };
  51492. /**
  51493. * Jump directly to a given frame
  51494. * @param frame defines the frame to jump to
  51495. */
  51496. Animatable.prototype.goToFrame = function (frame) {
  51497. var runtimeAnimations = this._runtimeAnimations;
  51498. if (runtimeAnimations[0]) {
  51499. var fps = runtimeAnimations[0].animation.framePerSecond;
  51500. var currentFrame = runtimeAnimations[0].currentFrame;
  51501. var adjustTime = frame - currentFrame;
  51502. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51503. if (this._localDelayOffset === null) {
  51504. this._localDelayOffset = 0;
  51505. }
  51506. this._localDelayOffset -= delay;
  51507. }
  51508. for (var index = 0; index < runtimeAnimations.length; index++) {
  51509. runtimeAnimations[index].goToFrame(frame);
  51510. }
  51511. };
  51512. /**
  51513. * Pause the animation
  51514. */
  51515. Animatable.prototype.pause = function () {
  51516. if (this._paused) {
  51517. return;
  51518. }
  51519. this._paused = true;
  51520. };
  51521. /**
  51522. * Restart the animation
  51523. */
  51524. Animatable.prototype.restart = function () {
  51525. this._paused = false;
  51526. };
  51527. Animatable.prototype._raiseOnAnimationEnd = function () {
  51528. if (this.onAnimationEnd) {
  51529. this.onAnimationEnd();
  51530. }
  51531. this.onAnimationEndObservable.notifyObservers(this);
  51532. };
  51533. /**
  51534. * Stop and delete the current animation
  51535. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51536. * @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)
  51537. */
  51538. Animatable.prototype.stop = function (animationName, targetMask) {
  51539. if (animationName || targetMask) {
  51540. var idx = this._scene._activeAnimatables.indexOf(this);
  51541. if (idx > -1) {
  51542. var runtimeAnimations = this._runtimeAnimations;
  51543. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51544. var runtimeAnimation = runtimeAnimations[index];
  51545. if (animationName && runtimeAnimation.animation.name != animationName) {
  51546. continue;
  51547. }
  51548. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51549. continue;
  51550. }
  51551. runtimeAnimation.dispose();
  51552. runtimeAnimations.splice(index, 1);
  51553. }
  51554. if (runtimeAnimations.length == 0) {
  51555. this._scene._activeAnimatables.splice(idx, 1);
  51556. this._raiseOnAnimationEnd();
  51557. }
  51558. }
  51559. }
  51560. else {
  51561. var index = this._scene._activeAnimatables.indexOf(this);
  51562. if (index > -1) {
  51563. this._scene._activeAnimatables.splice(index, 1);
  51564. var runtimeAnimations = this._runtimeAnimations;
  51565. for (var index = 0; index < runtimeAnimations.length; index++) {
  51566. runtimeAnimations[index].dispose();
  51567. }
  51568. this._raiseOnAnimationEnd();
  51569. }
  51570. }
  51571. };
  51572. /**
  51573. * Wait asynchronously for the animation to end
  51574. * @returns a promise which will be fullfilled when the animation ends
  51575. */
  51576. Animatable.prototype.waitAsync = function () {
  51577. var _this = this;
  51578. return new Promise(function (resolve, reject) {
  51579. _this.onAnimationEndObservable.add(function () {
  51580. resolve(_this);
  51581. }, undefined, undefined, _this, true);
  51582. });
  51583. };
  51584. /** @hidden */
  51585. Animatable.prototype._animate = function (delay) {
  51586. if (this._paused) {
  51587. this.animationStarted = false;
  51588. if (this._pausedDelay === null) {
  51589. this._pausedDelay = delay;
  51590. }
  51591. return true;
  51592. }
  51593. if (this._localDelayOffset === null) {
  51594. this._localDelayOffset = delay;
  51595. this._pausedDelay = null;
  51596. }
  51597. else if (this._pausedDelay !== null) {
  51598. this._localDelayOffset += delay - this._pausedDelay;
  51599. this._pausedDelay = null;
  51600. }
  51601. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51602. return true;
  51603. }
  51604. // Animating
  51605. var running = false;
  51606. var runtimeAnimations = this._runtimeAnimations;
  51607. var index;
  51608. for (index = 0; index < runtimeAnimations.length; index++) {
  51609. var animation = runtimeAnimations[index];
  51610. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51611. running = running || isRunning;
  51612. }
  51613. this.animationStarted = running;
  51614. if (!running) {
  51615. if (this.disposeOnEnd) {
  51616. // Remove from active animatables
  51617. index = this._scene._activeAnimatables.indexOf(this);
  51618. this._scene._activeAnimatables.splice(index, 1);
  51619. // Dispose all runtime animations
  51620. for (index = 0; index < runtimeAnimations.length; index++) {
  51621. runtimeAnimations[index].dispose();
  51622. }
  51623. }
  51624. this._raiseOnAnimationEnd();
  51625. if (this.disposeOnEnd) {
  51626. this.onAnimationEnd = null;
  51627. this.onAnimationEndObservable.clear();
  51628. }
  51629. }
  51630. return running;
  51631. };
  51632. return Animatable;
  51633. }());
  51634. BABYLON.Animatable = Animatable;
  51635. })(BABYLON || (BABYLON = {}));
  51636. //# sourceMappingURL=babylon.animatable.js.map
  51637. var BABYLON;
  51638. (function (BABYLON) {
  51639. var EasingFunction = /** @class */ (function () {
  51640. function EasingFunction() {
  51641. // Properties
  51642. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51643. }
  51644. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51645. get: function () {
  51646. return EasingFunction._EASINGMODE_EASEIN;
  51647. },
  51648. enumerable: true,
  51649. configurable: true
  51650. });
  51651. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51652. get: function () {
  51653. return EasingFunction._EASINGMODE_EASEOUT;
  51654. },
  51655. enumerable: true,
  51656. configurable: true
  51657. });
  51658. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51659. get: function () {
  51660. return EasingFunction._EASINGMODE_EASEINOUT;
  51661. },
  51662. enumerable: true,
  51663. configurable: true
  51664. });
  51665. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51666. var n = Math.min(Math.max(easingMode, 0), 2);
  51667. this._easingMode = n;
  51668. };
  51669. EasingFunction.prototype.getEasingMode = function () {
  51670. return this._easingMode;
  51671. };
  51672. EasingFunction.prototype.easeInCore = function (gradient) {
  51673. throw new Error('You must implement this method');
  51674. };
  51675. EasingFunction.prototype.ease = function (gradient) {
  51676. switch (this._easingMode) {
  51677. case EasingFunction.EASINGMODE_EASEIN:
  51678. return this.easeInCore(gradient);
  51679. case EasingFunction.EASINGMODE_EASEOUT:
  51680. return (1 - this.easeInCore(1 - gradient));
  51681. }
  51682. if (gradient >= 0.5) {
  51683. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51684. }
  51685. return (this.easeInCore(gradient * 2) * 0.5);
  51686. };
  51687. //Statics
  51688. EasingFunction._EASINGMODE_EASEIN = 0;
  51689. EasingFunction._EASINGMODE_EASEOUT = 1;
  51690. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51691. return EasingFunction;
  51692. }());
  51693. BABYLON.EasingFunction = EasingFunction;
  51694. var CircleEase = /** @class */ (function (_super) {
  51695. __extends(CircleEase, _super);
  51696. function CircleEase() {
  51697. return _super !== null && _super.apply(this, arguments) || this;
  51698. }
  51699. CircleEase.prototype.easeInCore = function (gradient) {
  51700. gradient = Math.max(0, Math.min(1, gradient));
  51701. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51702. };
  51703. return CircleEase;
  51704. }(EasingFunction));
  51705. BABYLON.CircleEase = CircleEase;
  51706. var BackEase = /** @class */ (function (_super) {
  51707. __extends(BackEase, _super);
  51708. function BackEase(amplitude) {
  51709. if (amplitude === void 0) { amplitude = 1; }
  51710. var _this = _super.call(this) || this;
  51711. _this.amplitude = amplitude;
  51712. return _this;
  51713. }
  51714. BackEase.prototype.easeInCore = function (gradient) {
  51715. var num = Math.max(0, this.amplitude);
  51716. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51717. };
  51718. return BackEase;
  51719. }(EasingFunction));
  51720. BABYLON.BackEase = BackEase;
  51721. var BounceEase = /** @class */ (function (_super) {
  51722. __extends(BounceEase, _super);
  51723. function BounceEase(bounces, bounciness) {
  51724. if (bounces === void 0) { bounces = 3; }
  51725. if (bounciness === void 0) { bounciness = 2; }
  51726. var _this = _super.call(this) || this;
  51727. _this.bounces = bounces;
  51728. _this.bounciness = bounciness;
  51729. return _this;
  51730. }
  51731. BounceEase.prototype.easeInCore = function (gradient) {
  51732. var y = Math.max(0.0, this.bounces);
  51733. var bounciness = this.bounciness;
  51734. if (bounciness <= 1.0) {
  51735. bounciness = 1.001;
  51736. }
  51737. var num9 = Math.pow(bounciness, y);
  51738. var num5 = 1.0 - bounciness;
  51739. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51740. var num15 = gradient * num4;
  51741. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51742. var num3 = Math.floor(num65);
  51743. var num13 = num3 + 1.0;
  51744. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51745. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51746. var num7 = (num8 + num12) * 0.5;
  51747. var num6 = gradient - num7;
  51748. var num2 = num7 - num8;
  51749. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51750. };
  51751. return BounceEase;
  51752. }(EasingFunction));
  51753. BABYLON.BounceEase = BounceEase;
  51754. var CubicEase = /** @class */ (function (_super) {
  51755. __extends(CubicEase, _super);
  51756. function CubicEase() {
  51757. return _super !== null && _super.apply(this, arguments) || this;
  51758. }
  51759. CubicEase.prototype.easeInCore = function (gradient) {
  51760. return (gradient * gradient * gradient);
  51761. };
  51762. return CubicEase;
  51763. }(EasingFunction));
  51764. BABYLON.CubicEase = CubicEase;
  51765. var ElasticEase = /** @class */ (function (_super) {
  51766. __extends(ElasticEase, _super);
  51767. function ElasticEase(oscillations, springiness) {
  51768. if (oscillations === void 0) { oscillations = 3; }
  51769. if (springiness === void 0) { springiness = 3; }
  51770. var _this = _super.call(this) || this;
  51771. _this.oscillations = oscillations;
  51772. _this.springiness = springiness;
  51773. return _this;
  51774. }
  51775. ElasticEase.prototype.easeInCore = function (gradient) {
  51776. var num2;
  51777. var num3 = Math.max(0.0, this.oscillations);
  51778. var num = Math.max(0.0, this.springiness);
  51779. if (num == 0) {
  51780. num2 = gradient;
  51781. }
  51782. else {
  51783. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51784. }
  51785. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51786. };
  51787. return ElasticEase;
  51788. }(EasingFunction));
  51789. BABYLON.ElasticEase = ElasticEase;
  51790. var ExponentialEase = /** @class */ (function (_super) {
  51791. __extends(ExponentialEase, _super);
  51792. function ExponentialEase(exponent) {
  51793. if (exponent === void 0) { exponent = 2; }
  51794. var _this = _super.call(this) || this;
  51795. _this.exponent = exponent;
  51796. return _this;
  51797. }
  51798. ExponentialEase.prototype.easeInCore = function (gradient) {
  51799. if (this.exponent <= 0) {
  51800. return gradient;
  51801. }
  51802. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51803. };
  51804. return ExponentialEase;
  51805. }(EasingFunction));
  51806. BABYLON.ExponentialEase = ExponentialEase;
  51807. var PowerEase = /** @class */ (function (_super) {
  51808. __extends(PowerEase, _super);
  51809. function PowerEase(power) {
  51810. if (power === void 0) { power = 2; }
  51811. var _this = _super.call(this) || this;
  51812. _this.power = power;
  51813. return _this;
  51814. }
  51815. PowerEase.prototype.easeInCore = function (gradient) {
  51816. var y = Math.max(0.0, this.power);
  51817. return Math.pow(gradient, y);
  51818. };
  51819. return PowerEase;
  51820. }(EasingFunction));
  51821. BABYLON.PowerEase = PowerEase;
  51822. var QuadraticEase = /** @class */ (function (_super) {
  51823. __extends(QuadraticEase, _super);
  51824. function QuadraticEase() {
  51825. return _super !== null && _super.apply(this, arguments) || this;
  51826. }
  51827. QuadraticEase.prototype.easeInCore = function (gradient) {
  51828. return (gradient * gradient);
  51829. };
  51830. return QuadraticEase;
  51831. }(EasingFunction));
  51832. BABYLON.QuadraticEase = QuadraticEase;
  51833. var QuarticEase = /** @class */ (function (_super) {
  51834. __extends(QuarticEase, _super);
  51835. function QuarticEase() {
  51836. return _super !== null && _super.apply(this, arguments) || this;
  51837. }
  51838. QuarticEase.prototype.easeInCore = function (gradient) {
  51839. return (gradient * gradient * gradient * gradient);
  51840. };
  51841. return QuarticEase;
  51842. }(EasingFunction));
  51843. BABYLON.QuarticEase = QuarticEase;
  51844. var QuinticEase = /** @class */ (function (_super) {
  51845. __extends(QuinticEase, _super);
  51846. function QuinticEase() {
  51847. return _super !== null && _super.apply(this, arguments) || this;
  51848. }
  51849. QuinticEase.prototype.easeInCore = function (gradient) {
  51850. return (gradient * gradient * gradient * gradient * gradient);
  51851. };
  51852. return QuinticEase;
  51853. }(EasingFunction));
  51854. BABYLON.QuinticEase = QuinticEase;
  51855. var SineEase = /** @class */ (function (_super) {
  51856. __extends(SineEase, _super);
  51857. function SineEase() {
  51858. return _super !== null && _super.apply(this, arguments) || this;
  51859. }
  51860. SineEase.prototype.easeInCore = function (gradient) {
  51861. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51862. };
  51863. return SineEase;
  51864. }(EasingFunction));
  51865. BABYLON.SineEase = SineEase;
  51866. var BezierCurveEase = /** @class */ (function (_super) {
  51867. __extends(BezierCurveEase, _super);
  51868. function BezierCurveEase(x1, y1, x2, y2) {
  51869. if (x1 === void 0) { x1 = 0; }
  51870. if (y1 === void 0) { y1 = 0; }
  51871. if (x2 === void 0) { x2 = 1; }
  51872. if (y2 === void 0) { y2 = 1; }
  51873. var _this = _super.call(this) || this;
  51874. _this.x1 = x1;
  51875. _this.y1 = y1;
  51876. _this.x2 = x2;
  51877. _this.y2 = y2;
  51878. return _this;
  51879. }
  51880. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51881. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51882. };
  51883. return BezierCurveEase;
  51884. }(EasingFunction));
  51885. BABYLON.BezierCurveEase = BezierCurveEase;
  51886. })(BABYLON || (BABYLON = {}));
  51887. //# sourceMappingURL=babylon.easing.js.map
  51888. var BABYLON;
  51889. (function (BABYLON) {
  51890. /**
  51891. * A Condition applied to an Action
  51892. */
  51893. var Condition = /** @class */ (function () {
  51894. /**
  51895. * Creates a new Condition
  51896. * @param actionManager the manager of the action the condition is applied to
  51897. */
  51898. function Condition(actionManager) {
  51899. this._actionManager = actionManager;
  51900. }
  51901. /**
  51902. * Check if the current condition is valid
  51903. * @returns a boolean
  51904. */
  51905. Condition.prototype.isValid = function () {
  51906. return true;
  51907. };
  51908. /**
  51909. * Internal only
  51910. * @hidden
  51911. */
  51912. Condition.prototype._getProperty = function (propertyPath) {
  51913. return this._actionManager._getProperty(propertyPath);
  51914. };
  51915. /**
  51916. * Internal only
  51917. * @hidden
  51918. */
  51919. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51920. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51921. };
  51922. /**
  51923. * Serialize placeholder for child classes
  51924. * @returns the serialized object
  51925. */
  51926. Condition.prototype.serialize = function () {
  51927. };
  51928. /**
  51929. * Internal only
  51930. * @hidden
  51931. */
  51932. Condition.prototype._serialize = function (serializedCondition) {
  51933. return {
  51934. type: 2,
  51935. children: [],
  51936. name: serializedCondition.name,
  51937. properties: serializedCondition.properties
  51938. };
  51939. };
  51940. return Condition;
  51941. }());
  51942. BABYLON.Condition = Condition;
  51943. /**
  51944. * Defines specific conditional operators as extensions of Condition
  51945. */
  51946. var ValueCondition = /** @class */ (function (_super) {
  51947. __extends(ValueCondition, _super);
  51948. /**
  51949. * Creates a new ValueCondition
  51950. * @param actionManager manager for the action the condition applies to
  51951. * @param target for the action
  51952. * @param propertyPath path to specify the property of the target the conditional operator uses
  51953. * @param value the value compared by the conditional operator against the current value of the property
  51954. * @param operator the conditional operator, default ValueCondition.IsEqual
  51955. */
  51956. function ValueCondition(actionManager, target,
  51957. /** path to specify the property of the target the conditional operator uses */
  51958. propertyPath,
  51959. /** the value compared by the conditional operator against the current value of the property */
  51960. value,
  51961. /** the conditional operator, default ValueCondition.IsEqual */
  51962. operator) {
  51963. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51964. var _this = _super.call(this, actionManager) || this;
  51965. _this.propertyPath = propertyPath;
  51966. _this.value = value;
  51967. _this.operator = operator;
  51968. _this._target = target;
  51969. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51970. _this._property = _this._getProperty(_this.propertyPath);
  51971. return _this;
  51972. }
  51973. Object.defineProperty(ValueCondition, "IsEqual", {
  51974. /**
  51975. * returns the number for IsEqual
  51976. */
  51977. get: function () {
  51978. return ValueCondition._IsEqual;
  51979. },
  51980. enumerable: true,
  51981. configurable: true
  51982. });
  51983. Object.defineProperty(ValueCondition, "IsDifferent", {
  51984. /**
  51985. * Returns the number for IsDifferent
  51986. */
  51987. get: function () {
  51988. return ValueCondition._IsDifferent;
  51989. },
  51990. enumerable: true,
  51991. configurable: true
  51992. });
  51993. Object.defineProperty(ValueCondition, "IsGreater", {
  51994. /**
  51995. * Returns the number for IsGreater
  51996. */
  51997. get: function () {
  51998. return ValueCondition._IsGreater;
  51999. },
  52000. enumerable: true,
  52001. configurable: true
  52002. });
  52003. Object.defineProperty(ValueCondition, "IsLesser", {
  52004. /**
  52005. * Returns the number for IsLesser
  52006. */
  52007. get: function () {
  52008. return ValueCondition._IsLesser;
  52009. },
  52010. enumerable: true,
  52011. configurable: true
  52012. });
  52013. /**
  52014. * Compares the given value with the property value for the specified conditional operator
  52015. * @returns the result of the comparison
  52016. */
  52017. ValueCondition.prototype.isValid = function () {
  52018. switch (this.operator) {
  52019. case ValueCondition.IsGreater:
  52020. return this._effectiveTarget[this._property] > this.value;
  52021. case ValueCondition.IsLesser:
  52022. return this._effectiveTarget[this._property] < this.value;
  52023. case ValueCondition.IsEqual:
  52024. case ValueCondition.IsDifferent:
  52025. var check;
  52026. if (this.value.equals) {
  52027. check = this.value.equals(this._effectiveTarget[this._property]);
  52028. }
  52029. else {
  52030. check = this.value === this._effectiveTarget[this._property];
  52031. }
  52032. return this.operator === ValueCondition.IsEqual ? check : !check;
  52033. }
  52034. return false;
  52035. };
  52036. /**
  52037. * Serialize the ValueCondition into a JSON compatible object
  52038. * @returns serialization object
  52039. */
  52040. ValueCondition.prototype.serialize = function () {
  52041. return this._serialize({
  52042. name: "ValueCondition",
  52043. properties: [
  52044. BABYLON.Action._GetTargetProperty(this._target),
  52045. { name: "propertyPath", value: this.propertyPath },
  52046. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52047. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52048. ]
  52049. });
  52050. };
  52051. /**
  52052. * Gets the name of the conditional operator for the ValueCondition
  52053. * @param operator the conditional operator
  52054. * @returns the name
  52055. */
  52056. ValueCondition.GetOperatorName = function (operator) {
  52057. switch (operator) {
  52058. case ValueCondition._IsEqual: return "IsEqual";
  52059. case ValueCondition._IsDifferent: return "IsDifferent";
  52060. case ValueCondition._IsGreater: return "IsGreater";
  52061. case ValueCondition._IsLesser: return "IsLesser";
  52062. default: return "";
  52063. }
  52064. };
  52065. /**
  52066. * Internal only
  52067. * @hidden
  52068. */
  52069. ValueCondition._IsEqual = 0;
  52070. /**
  52071. * Internal only
  52072. * @hidden
  52073. */
  52074. ValueCondition._IsDifferent = 1;
  52075. /**
  52076. * Internal only
  52077. * @hidden
  52078. */
  52079. ValueCondition._IsGreater = 2;
  52080. /**
  52081. * Internal only
  52082. * @hidden
  52083. */
  52084. ValueCondition._IsLesser = 3;
  52085. return ValueCondition;
  52086. }(Condition));
  52087. BABYLON.ValueCondition = ValueCondition;
  52088. /**
  52089. * Defines a predicate condition as an extension of Condition
  52090. */
  52091. var PredicateCondition = /** @class */ (function (_super) {
  52092. __extends(PredicateCondition, _super);
  52093. /**
  52094. * Creates a new PredicateCondition
  52095. * @param actionManager manager for the action the condition applies to
  52096. * @param predicate defines the predicate function used to validate the condition
  52097. */
  52098. function PredicateCondition(actionManager,
  52099. /** defines the predicate function used to validate the condition */
  52100. predicate) {
  52101. var _this = _super.call(this, actionManager) || this;
  52102. _this.predicate = predicate;
  52103. return _this;
  52104. }
  52105. /**
  52106. * @returns the validity of the predicate condition
  52107. */
  52108. PredicateCondition.prototype.isValid = function () {
  52109. return this.predicate();
  52110. };
  52111. return PredicateCondition;
  52112. }(Condition));
  52113. BABYLON.PredicateCondition = PredicateCondition;
  52114. /**
  52115. * Defines a state condition as an extension of Condition
  52116. */
  52117. var StateCondition = /** @class */ (function (_super) {
  52118. __extends(StateCondition, _super);
  52119. /**
  52120. * Creates a new StateCondition
  52121. * @param actionManager manager for the action the condition applies to
  52122. * @param target of the condition
  52123. * @param value to compare with target state
  52124. */
  52125. function StateCondition(actionManager, target, value) {
  52126. var _this = _super.call(this, actionManager) || this;
  52127. _this.value = value;
  52128. _this._target = target;
  52129. return _this;
  52130. }
  52131. /**
  52132. * @returns the validity of the state
  52133. */
  52134. StateCondition.prototype.isValid = function () {
  52135. return this._target.state === this.value;
  52136. };
  52137. /**
  52138. * Serialize the StateCondition into a JSON compatible object
  52139. * @returns serialization object
  52140. */
  52141. StateCondition.prototype.serialize = function () {
  52142. return this._serialize({
  52143. name: "StateCondition",
  52144. properties: [
  52145. BABYLON.Action._GetTargetProperty(this._target),
  52146. { name: "value", value: this.value }
  52147. ]
  52148. });
  52149. };
  52150. return StateCondition;
  52151. }(Condition));
  52152. BABYLON.StateCondition = StateCondition;
  52153. })(BABYLON || (BABYLON = {}));
  52154. //# sourceMappingURL=babylon.condition.js.map
  52155. var BABYLON;
  52156. (function (BABYLON) {
  52157. /**
  52158. * The action to be carried out following a trigger
  52159. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52160. */
  52161. var Action = /** @class */ (function () {
  52162. /**
  52163. * Creates a new Action
  52164. * @param triggerOptions the trigger, with or without parameters, for the action
  52165. * @param condition an optional determinant of action
  52166. */
  52167. function Action(
  52168. /** the trigger, with or without parameters, for the action */
  52169. triggerOptions, condition) {
  52170. this.triggerOptions = triggerOptions;
  52171. /**
  52172. * An event triggered prior to action being executed.
  52173. */
  52174. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52175. if (triggerOptions.parameter) {
  52176. this.trigger = triggerOptions.trigger;
  52177. this._triggerParameter = triggerOptions.parameter;
  52178. }
  52179. else if (triggerOptions.trigger) {
  52180. this.trigger = triggerOptions.trigger;
  52181. }
  52182. else {
  52183. this.trigger = triggerOptions;
  52184. }
  52185. this._nextActiveAction = this;
  52186. this._condition = condition;
  52187. }
  52188. /**
  52189. * Internal only
  52190. * @hidden
  52191. */
  52192. Action.prototype._prepare = function () {
  52193. };
  52194. /**
  52195. * Gets the trigger parameters
  52196. * @returns the trigger parameters
  52197. */
  52198. Action.prototype.getTriggerParameter = function () {
  52199. return this._triggerParameter;
  52200. };
  52201. /**
  52202. * Internal only - executes current action event
  52203. * @hidden
  52204. */
  52205. Action.prototype._executeCurrent = function (evt) {
  52206. if (this._nextActiveAction._condition) {
  52207. var condition = this._nextActiveAction._condition;
  52208. var currentRenderId = this._actionManager.getScene().getRenderId();
  52209. // We cache the current evaluation for the current frame
  52210. if (condition._evaluationId === currentRenderId) {
  52211. if (!condition._currentResult) {
  52212. return;
  52213. }
  52214. }
  52215. else {
  52216. condition._evaluationId = currentRenderId;
  52217. if (!condition.isValid()) {
  52218. condition._currentResult = false;
  52219. return;
  52220. }
  52221. condition._currentResult = true;
  52222. }
  52223. }
  52224. this.onBeforeExecuteObservable.notifyObservers(this);
  52225. this._nextActiveAction.execute(evt);
  52226. this.skipToNextActiveAction();
  52227. };
  52228. /**
  52229. * Execute placeholder for child classes
  52230. * @param evt optional action event
  52231. */
  52232. Action.prototype.execute = function (evt) {
  52233. };
  52234. /**
  52235. * Skips to next active action
  52236. */
  52237. Action.prototype.skipToNextActiveAction = function () {
  52238. if (this._nextActiveAction._child) {
  52239. if (!this._nextActiveAction._child._actionManager) {
  52240. this._nextActiveAction._child._actionManager = this._actionManager;
  52241. }
  52242. this._nextActiveAction = this._nextActiveAction._child;
  52243. }
  52244. else {
  52245. this._nextActiveAction = this;
  52246. }
  52247. };
  52248. /**
  52249. * Adds action to chain of actions, may be a DoNothingAction
  52250. * @param action defines the next action to execute
  52251. * @returns The action passed in
  52252. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52253. */
  52254. Action.prototype.then = function (action) {
  52255. this._child = action;
  52256. action._actionManager = this._actionManager;
  52257. action._prepare();
  52258. return action;
  52259. };
  52260. /**
  52261. * Internal only
  52262. * @hidden
  52263. */
  52264. Action.prototype._getProperty = function (propertyPath) {
  52265. return this._actionManager._getProperty(propertyPath);
  52266. };
  52267. /**
  52268. * Internal only
  52269. * @hidden
  52270. */
  52271. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52272. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52273. };
  52274. /**
  52275. * Serialize placeholder for child classes
  52276. * @param parent of child
  52277. * @returns the serialized object
  52278. */
  52279. Action.prototype.serialize = function (parent) {
  52280. };
  52281. /**
  52282. * Internal only called by serialize
  52283. * @hidden
  52284. */
  52285. Action.prototype._serialize = function (serializedAction, parent) {
  52286. var serializationObject = {
  52287. type: 1,
  52288. children: [],
  52289. name: serializedAction.name,
  52290. properties: serializedAction.properties || []
  52291. };
  52292. // Serialize child
  52293. if (this._child) {
  52294. this._child.serialize(serializationObject);
  52295. }
  52296. // Check if "this" has a condition
  52297. if (this._condition) {
  52298. var serializedCondition = this._condition.serialize();
  52299. serializedCondition.children.push(serializationObject);
  52300. if (parent) {
  52301. parent.children.push(serializedCondition);
  52302. }
  52303. return serializedCondition;
  52304. }
  52305. if (parent) {
  52306. parent.children.push(serializationObject);
  52307. }
  52308. return serializationObject;
  52309. };
  52310. /**
  52311. * Internal only
  52312. * @hidden
  52313. */
  52314. Action._SerializeValueAsString = function (value) {
  52315. if (typeof value === "number") {
  52316. return value.toString();
  52317. }
  52318. if (typeof value === "boolean") {
  52319. return value ? "true" : "false";
  52320. }
  52321. if (value instanceof BABYLON.Vector2) {
  52322. return value.x + ", " + value.y;
  52323. }
  52324. if (value instanceof BABYLON.Vector3) {
  52325. return value.x + ", " + value.y + ", " + value.z;
  52326. }
  52327. if (value instanceof BABYLON.Color3) {
  52328. return value.r + ", " + value.g + ", " + value.b;
  52329. }
  52330. if (value instanceof BABYLON.Color4) {
  52331. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52332. }
  52333. return value; // string
  52334. };
  52335. /**
  52336. * Internal only
  52337. * @hidden
  52338. */
  52339. Action._GetTargetProperty = function (target) {
  52340. return {
  52341. name: "target",
  52342. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52343. : target instanceof BABYLON.Light ? "LightProperties"
  52344. : target instanceof BABYLON.Camera ? "CameraProperties"
  52345. : "SceneProperties",
  52346. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52347. };
  52348. };
  52349. return Action;
  52350. }());
  52351. BABYLON.Action = Action;
  52352. })(BABYLON || (BABYLON = {}));
  52353. //# sourceMappingURL=babylon.action.js.map
  52354. var BABYLON;
  52355. (function (BABYLON) {
  52356. /**
  52357. * ActionEvent is the event being sent when an action is triggered.
  52358. */
  52359. var ActionEvent = /** @class */ (function () {
  52360. /**
  52361. * Creates a new ActionEvent
  52362. * @param source The mesh or sprite that triggered the action
  52363. * @param pointerX The X mouse cursor position at the time of the event
  52364. * @param pointerY The Y mouse cursor position at the time of the event
  52365. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52366. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52367. * @param additionalData additional data for the event
  52368. */
  52369. function ActionEvent(
  52370. /** The mesh or sprite that triggered the action */
  52371. source,
  52372. /** The X mouse cursor position at the time of the event */
  52373. pointerX,
  52374. /** The Y mouse cursor position at the time of the event */
  52375. pointerY,
  52376. /** The mesh that is currently pointed at (can be null) */
  52377. meshUnderPointer,
  52378. /** the original (browser) event that triggered the ActionEvent */
  52379. sourceEvent,
  52380. /** additional data for the event */
  52381. additionalData) {
  52382. this.source = source;
  52383. this.pointerX = pointerX;
  52384. this.pointerY = pointerY;
  52385. this.meshUnderPointer = meshUnderPointer;
  52386. this.sourceEvent = sourceEvent;
  52387. this.additionalData = additionalData;
  52388. }
  52389. /**
  52390. * Helper function to auto-create an ActionEvent from a source mesh.
  52391. * @param source The source mesh that triggered the event
  52392. * @param evt The original (browser) event
  52393. * @param additionalData additional data for the event
  52394. * @returns the new ActionEvent
  52395. */
  52396. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52397. var scene = source.getScene();
  52398. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52399. };
  52400. /**
  52401. * Helper function to auto-create an ActionEvent from a source sprite
  52402. * @param source The source sprite that triggered the event
  52403. * @param scene Scene associated with the sprite
  52404. * @param evt The original (browser) event
  52405. * @param additionalData additional data for the event
  52406. * @returns the new ActionEvent
  52407. */
  52408. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52409. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52410. };
  52411. /**
  52412. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52413. * @param scene the scene where the event occurred
  52414. * @param evt The original (browser) event
  52415. * @returns the new ActionEvent
  52416. */
  52417. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52418. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52419. };
  52420. /**
  52421. * Helper function to auto-create an ActionEvent from a primitive
  52422. * @param prim defines the target primitive
  52423. * @param pointerPos defines the pointer position
  52424. * @param evt The original (browser) event
  52425. * @param additionalData additional data for the event
  52426. * @returns the new ActionEvent
  52427. */
  52428. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52429. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52430. };
  52431. return ActionEvent;
  52432. }());
  52433. BABYLON.ActionEvent = ActionEvent;
  52434. /**
  52435. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52436. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52437. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52438. */
  52439. var ActionManager = /** @class */ (function () {
  52440. /**
  52441. * Creates a new action manager
  52442. * @param scene defines the hosting scene
  52443. */
  52444. function ActionManager(scene) {
  52445. // Members
  52446. /** Gets the list of actions */
  52447. this.actions = new Array();
  52448. /** Gets the cursor to use when hovering items */
  52449. this.hoverCursor = '';
  52450. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52451. scene.actionManagers.push(this);
  52452. }
  52453. Object.defineProperty(ActionManager, "NothingTrigger", {
  52454. /**
  52455. * Nothing
  52456. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52457. */
  52458. get: function () {
  52459. return ActionManager._NothingTrigger;
  52460. },
  52461. enumerable: true,
  52462. configurable: true
  52463. });
  52464. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52465. /**
  52466. * On pick
  52467. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52468. */
  52469. get: function () {
  52470. return ActionManager._OnPickTrigger;
  52471. },
  52472. enumerable: true,
  52473. configurable: true
  52474. });
  52475. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52476. /**
  52477. * On left pick
  52478. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52479. */
  52480. get: function () {
  52481. return ActionManager._OnLeftPickTrigger;
  52482. },
  52483. enumerable: true,
  52484. configurable: true
  52485. });
  52486. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52487. /**
  52488. * On right pick
  52489. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52490. */
  52491. get: function () {
  52492. return ActionManager._OnRightPickTrigger;
  52493. },
  52494. enumerable: true,
  52495. configurable: true
  52496. });
  52497. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52498. /**
  52499. * On center pick
  52500. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52501. */
  52502. get: function () {
  52503. return ActionManager._OnCenterPickTrigger;
  52504. },
  52505. enumerable: true,
  52506. configurable: true
  52507. });
  52508. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52509. /**
  52510. * On pick down
  52511. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52512. */
  52513. get: function () {
  52514. return ActionManager._OnPickDownTrigger;
  52515. },
  52516. enumerable: true,
  52517. configurable: true
  52518. });
  52519. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52520. /**
  52521. * On double pick
  52522. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52523. */
  52524. get: function () {
  52525. return ActionManager._OnDoublePickTrigger;
  52526. },
  52527. enumerable: true,
  52528. configurable: true
  52529. });
  52530. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52531. /**
  52532. * On pick up
  52533. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52534. */
  52535. get: function () {
  52536. return ActionManager._OnPickUpTrigger;
  52537. },
  52538. enumerable: true,
  52539. configurable: true
  52540. });
  52541. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52542. /**
  52543. * On pick out.
  52544. * This trigger will only be raised if you also declared a OnPickDown
  52545. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52546. */
  52547. get: function () {
  52548. return ActionManager._OnPickOutTrigger;
  52549. },
  52550. enumerable: true,
  52551. configurable: true
  52552. });
  52553. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52554. /**
  52555. * On long press
  52556. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52557. */
  52558. get: function () {
  52559. return ActionManager._OnLongPressTrigger;
  52560. },
  52561. enumerable: true,
  52562. configurable: true
  52563. });
  52564. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52565. /**
  52566. * On pointer over
  52567. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52568. */
  52569. get: function () {
  52570. return ActionManager._OnPointerOverTrigger;
  52571. },
  52572. enumerable: true,
  52573. configurable: true
  52574. });
  52575. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52576. /**
  52577. * On pointer out
  52578. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52579. */
  52580. get: function () {
  52581. return ActionManager._OnPointerOutTrigger;
  52582. },
  52583. enumerable: true,
  52584. configurable: true
  52585. });
  52586. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52587. /**
  52588. * On every frame
  52589. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52590. */
  52591. get: function () {
  52592. return ActionManager._OnEveryFrameTrigger;
  52593. },
  52594. enumerable: true,
  52595. configurable: true
  52596. });
  52597. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52598. /**
  52599. * On intersection enter
  52600. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52601. */
  52602. get: function () {
  52603. return ActionManager._OnIntersectionEnterTrigger;
  52604. },
  52605. enumerable: true,
  52606. configurable: true
  52607. });
  52608. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52609. /**
  52610. * On intersection exit
  52611. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52612. */
  52613. get: function () {
  52614. return ActionManager._OnIntersectionExitTrigger;
  52615. },
  52616. enumerable: true,
  52617. configurable: true
  52618. });
  52619. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52620. /**
  52621. * On key down
  52622. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52623. */
  52624. get: function () {
  52625. return ActionManager._OnKeyDownTrigger;
  52626. },
  52627. enumerable: true,
  52628. configurable: true
  52629. });
  52630. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52631. /**
  52632. * On key up
  52633. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52634. */
  52635. get: function () {
  52636. return ActionManager._OnKeyUpTrigger;
  52637. },
  52638. enumerable: true,
  52639. configurable: true
  52640. });
  52641. // Methods
  52642. /**
  52643. * Releases all associated resources
  52644. */
  52645. ActionManager.prototype.dispose = function () {
  52646. var index = this._scene.actionManagers.indexOf(this);
  52647. for (var i = 0; i < this.actions.length; i++) {
  52648. var action = this.actions[i];
  52649. ActionManager.Triggers[action.trigger]--;
  52650. if (ActionManager.Triggers[action.trigger] === 0) {
  52651. delete ActionManager.Triggers[action.trigger];
  52652. }
  52653. }
  52654. if (index > -1) {
  52655. this._scene.actionManagers.splice(index, 1);
  52656. }
  52657. };
  52658. /**
  52659. * Gets hosting scene
  52660. * @returns the hosting scene
  52661. */
  52662. ActionManager.prototype.getScene = function () {
  52663. return this._scene;
  52664. };
  52665. /**
  52666. * Does this action manager handles actions of any of the given triggers
  52667. * @param triggers defines the triggers to be tested
  52668. * @return a boolean indicating whether one (or more) of the triggers is handled
  52669. */
  52670. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52671. for (var index = 0; index < this.actions.length; index++) {
  52672. var action = this.actions[index];
  52673. if (triggers.indexOf(action.trigger) > -1) {
  52674. return true;
  52675. }
  52676. }
  52677. return false;
  52678. };
  52679. /**
  52680. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  52681. * speed.
  52682. * @param triggerA defines the trigger to be tested
  52683. * @param triggerB defines the trigger to be tested
  52684. * @return a boolean indicating whether one (or more) of the triggers is handled
  52685. */
  52686. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  52687. for (var index = 0; index < this.actions.length; index++) {
  52688. var action = this.actions[index];
  52689. if (triggerA == action.trigger || triggerB == action.trigger) {
  52690. return true;
  52691. }
  52692. }
  52693. return false;
  52694. };
  52695. /**
  52696. * Does this action manager handles actions of a given trigger
  52697. * @param trigger defines the trigger to be tested
  52698. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52699. * @return whether the trigger is handled
  52700. */
  52701. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52702. for (var index = 0; index < this.actions.length; index++) {
  52703. var action = this.actions[index];
  52704. if (action.trigger === trigger) {
  52705. if (parameterPredicate) {
  52706. if (parameterPredicate(action.getTriggerParameter())) {
  52707. return true;
  52708. }
  52709. }
  52710. else {
  52711. return true;
  52712. }
  52713. }
  52714. }
  52715. return false;
  52716. };
  52717. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52718. /**
  52719. * Does this action manager has pointer triggers
  52720. */
  52721. get: function () {
  52722. for (var index = 0; index < this.actions.length; index++) {
  52723. var action = this.actions[index];
  52724. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52725. return true;
  52726. }
  52727. }
  52728. return false;
  52729. },
  52730. enumerable: true,
  52731. configurable: true
  52732. });
  52733. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52734. /**
  52735. * Does this action manager has pick triggers
  52736. */
  52737. get: function () {
  52738. for (var index = 0; index < this.actions.length; index++) {
  52739. var action = this.actions[index];
  52740. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52741. return true;
  52742. }
  52743. }
  52744. return false;
  52745. },
  52746. enumerable: true,
  52747. configurable: true
  52748. });
  52749. Object.defineProperty(ActionManager, "HasTriggers", {
  52750. /**
  52751. * Does exist one action manager with at least one trigger
  52752. **/
  52753. get: function () {
  52754. for (var t in ActionManager.Triggers) {
  52755. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52756. return true;
  52757. }
  52758. }
  52759. return false;
  52760. },
  52761. enumerable: true,
  52762. configurable: true
  52763. });
  52764. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52765. /**
  52766. * Does exist one action manager with at least one pick trigger
  52767. **/
  52768. get: function () {
  52769. for (var t in ActionManager.Triggers) {
  52770. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52771. var t_int = parseInt(t);
  52772. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52773. return true;
  52774. }
  52775. }
  52776. }
  52777. return false;
  52778. },
  52779. enumerable: true,
  52780. configurable: true
  52781. });
  52782. /**
  52783. * Does exist one action manager that handles actions of a given trigger
  52784. * @param trigger defines the trigger to be tested
  52785. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52786. **/
  52787. ActionManager.HasSpecificTrigger = function (trigger) {
  52788. for (var t in ActionManager.Triggers) {
  52789. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52790. var t_int = parseInt(t);
  52791. if (t_int === trigger) {
  52792. return true;
  52793. }
  52794. }
  52795. }
  52796. return false;
  52797. };
  52798. /**
  52799. * Registers an action to this action manager
  52800. * @param action defines the action to be registered
  52801. * @return the action amended (prepared) after registration
  52802. */
  52803. ActionManager.prototype.registerAction = function (action) {
  52804. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52805. if (this.getScene().actionManager !== this) {
  52806. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52807. return null;
  52808. }
  52809. }
  52810. this.actions.push(action);
  52811. if (ActionManager.Triggers[action.trigger]) {
  52812. ActionManager.Triggers[action.trigger]++;
  52813. }
  52814. else {
  52815. ActionManager.Triggers[action.trigger] = 1;
  52816. }
  52817. action._actionManager = this;
  52818. action._prepare();
  52819. return action;
  52820. };
  52821. /**
  52822. * Unregisters an action to this action manager
  52823. * @param action defines the action to be unregistered
  52824. * @return a boolean indicating whether the action has been unregistered
  52825. */
  52826. ActionManager.prototype.unregisterAction = function (action) {
  52827. var index = this.actions.indexOf(action);
  52828. if (index !== -1) {
  52829. this.actions.splice(index, 1);
  52830. ActionManager.Triggers[action.trigger] -= 1;
  52831. if (ActionManager.Triggers[action.trigger] === 0) {
  52832. delete ActionManager.Triggers[action.trigger];
  52833. }
  52834. delete action._actionManager;
  52835. return true;
  52836. }
  52837. return false;
  52838. };
  52839. /**
  52840. * Process a specific trigger
  52841. * @param trigger defines the trigger to process
  52842. * @param evt defines the event details to be processed
  52843. */
  52844. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52845. for (var index = 0; index < this.actions.length; index++) {
  52846. var action = this.actions[index];
  52847. if (action.trigger === trigger) {
  52848. if (evt) {
  52849. if (trigger === ActionManager.OnKeyUpTrigger
  52850. || trigger === ActionManager.OnKeyDownTrigger) {
  52851. var parameter = action.getTriggerParameter();
  52852. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52853. if (!parameter.toLowerCase) {
  52854. continue;
  52855. }
  52856. var lowerCase = parameter.toLowerCase();
  52857. if (lowerCase !== evt.sourceEvent.key) {
  52858. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52859. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52860. if (actualkey !== lowerCase) {
  52861. continue;
  52862. }
  52863. }
  52864. }
  52865. }
  52866. }
  52867. action._executeCurrent(evt);
  52868. }
  52869. }
  52870. };
  52871. /** @hidden */
  52872. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52873. var properties = propertyPath.split(".");
  52874. for (var index = 0; index < properties.length - 1; index++) {
  52875. target = target[properties[index]];
  52876. }
  52877. return target;
  52878. };
  52879. /** @hidden */
  52880. ActionManager.prototype._getProperty = function (propertyPath) {
  52881. var properties = propertyPath.split(".");
  52882. return properties[properties.length - 1];
  52883. };
  52884. /**
  52885. * Serialize this manager to a JSON object
  52886. * @param name defines the property name to store this manager
  52887. * @returns a JSON representation of this manager
  52888. */
  52889. ActionManager.prototype.serialize = function (name) {
  52890. var root = {
  52891. children: new Array(),
  52892. name: name,
  52893. type: 3,
  52894. properties: new Array() // Empty for root but required
  52895. };
  52896. for (var i = 0; i < this.actions.length; i++) {
  52897. var triggerObject = {
  52898. type: 0,
  52899. children: new Array(),
  52900. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52901. properties: new Array()
  52902. };
  52903. var triggerOptions = this.actions[i].triggerOptions;
  52904. if (triggerOptions && typeof triggerOptions !== "number") {
  52905. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52906. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52907. }
  52908. else {
  52909. var parameter = {};
  52910. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52911. if (triggerOptions.parameter.mesh) {
  52912. parameter._meshId = triggerOptions.parameter.mesh.id;
  52913. }
  52914. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52915. }
  52916. }
  52917. // Serialize child action, recursively
  52918. this.actions[i].serialize(triggerObject);
  52919. // Add serialized trigger
  52920. root.children.push(triggerObject);
  52921. }
  52922. return root;
  52923. };
  52924. /**
  52925. * Creates a new ActionManager from a JSON data
  52926. * @param parsedActions defines the JSON data to read from
  52927. * @param object defines the hosting mesh
  52928. * @param scene defines the hosting scene
  52929. */
  52930. ActionManager.Parse = function (parsedActions, object, scene) {
  52931. var actionManager = new ActionManager(scene);
  52932. if (object === null)
  52933. scene.actionManager = actionManager;
  52934. else
  52935. object.actionManager = actionManager;
  52936. // instanciate a new object
  52937. var instanciate = function (name, params) {
  52938. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52939. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52940. newInstance.constructor.apply(newInstance, params);
  52941. return newInstance;
  52942. };
  52943. var parseParameter = function (name, value, target, propertyPath) {
  52944. if (propertyPath === null) {
  52945. // String, boolean or float
  52946. var floatValue = parseFloat(value);
  52947. if (value === "true" || value === "false")
  52948. return value === "true";
  52949. else
  52950. return isNaN(floatValue) ? value : floatValue;
  52951. }
  52952. var effectiveTarget = propertyPath.split(".");
  52953. var values = value.split(",");
  52954. // Get effective Target
  52955. for (var i = 0; i < effectiveTarget.length; i++) {
  52956. target = target[effectiveTarget[i]];
  52957. }
  52958. // Return appropriate value with its type
  52959. if (typeof (target) === "boolean")
  52960. return values[0] === "true";
  52961. if (typeof (target) === "string")
  52962. return values[0];
  52963. // Parameters with multiple values such as Vector3 etc.
  52964. var split = new Array();
  52965. for (var i = 0; i < values.length; i++)
  52966. split.push(parseFloat(values[i]));
  52967. if (target instanceof BABYLON.Vector3)
  52968. return BABYLON.Vector3.FromArray(split);
  52969. if (target instanceof BABYLON.Vector4)
  52970. return BABYLON.Vector4.FromArray(split);
  52971. if (target instanceof BABYLON.Color3)
  52972. return BABYLON.Color3.FromArray(split);
  52973. if (target instanceof BABYLON.Color4)
  52974. return BABYLON.Color4.FromArray(split);
  52975. return parseFloat(values[0]);
  52976. };
  52977. // traverse graph per trigger
  52978. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52979. if (combineArray === void 0) { combineArray = null; }
  52980. if (parsedAction.detached)
  52981. return;
  52982. var parameters = new Array();
  52983. var target = null;
  52984. var propertyPath = null;
  52985. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52986. // Parameters
  52987. if (parsedAction.type === 2)
  52988. parameters.push(actionManager);
  52989. else
  52990. parameters.push(trigger);
  52991. if (combine) {
  52992. var actions = new Array();
  52993. for (var j = 0; j < parsedAction.combine.length; j++) {
  52994. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52995. }
  52996. parameters.push(actions);
  52997. }
  52998. else {
  52999. for (var i = 0; i < parsedAction.properties.length; i++) {
  53000. var value = parsedAction.properties[i].value;
  53001. var name = parsedAction.properties[i].name;
  53002. var targetType = parsedAction.properties[i].targetType;
  53003. if (name === "target")
  53004. if (targetType !== null && targetType === "SceneProperties")
  53005. value = target = scene;
  53006. else
  53007. value = target = scene.getNodeByName(value);
  53008. else if (name === "parent")
  53009. value = scene.getNodeByName(value);
  53010. else if (name === "sound") {
  53011. // Can not externalize to component, so only checks for the presence off the API.
  53012. if (scene.getSoundByName) {
  53013. value = scene.getSoundByName(value);
  53014. }
  53015. }
  53016. else if (name !== "propertyPath") {
  53017. if (parsedAction.type === 2 && name === "operator")
  53018. value = BABYLON.ValueCondition[value];
  53019. else
  53020. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53021. }
  53022. else {
  53023. propertyPath = value;
  53024. }
  53025. parameters.push(value);
  53026. }
  53027. }
  53028. if (combineArray === null) {
  53029. parameters.push(condition);
  53030. }
  53031. else {
  53032. parameters.push(null);
  53033. }
  53034. // If interpolate value action
  53035. if (parsedAction.name === "InterpolateValueAction") {
  53036. var param = parameters[parameters.length - 2];
  53037. parameters[parameters.length - 1] = param;
  53038. parameters[parameters.length - 2] = condition;
  53039. }
  53040. // Action or condition(s) and not CombineAction
  53041. var newAction = instanciate(parsedAction.name, parameters);
  53042. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53043. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53044. if (action)
  53045. action.then(nothing);
  53046. else
  53047. actionManager.registerAction(nothing);
  53048. action = nothing;
  53049. }
  53050. if (combineArray === null) {
  53051. if (newAction instanceof BABYLON.Condition) {
  53052. condition = newAction;
  53053. newAction = action;
  53054. }
  53055. else {
  53056. condition = null;
  53057. if (action)
  53058. action.then(newAction);
  53059. else
  53060. actionManager.registerAction(newAction);
  53061. }
  53062. }
  53063. else {
  53064. combineArray.push(newAction);
  53065. }
  53066. for (var i = 0; i < parsedAction.children.length; i++)
  53067. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53068. };
  53069. // triggers
  53070. for (var i = 0; i < parsedActions.children.length; i++) {
  53071. var triggerParams;
  53072. var trigger = parsedActions.children[i];
  53073. if (trigger.properties.length > 0) {
  53074. var param = trigger.properties[0].value;
  53075. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53076. if (value._meshId) {
  53077. value.mesh = scene.getMeshByID(value._meshId);
  53078. }
  53079. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53080. }
  53081. else
  53082. triggerParams = ActionManager[trigger.name];
  53083. for (var j = 0; j < trigger.children.length; j++) {
  53084. if (!trigger.detached)
  53085. traverse(trigger.children[j], triggerParams, null, null);
  53086. }
  53087. }
  53088. };
  53089. /**
  53090. * Get a trigger name by index
  53091. * @param trigger defines the trigger index
  53092. * @returns a trigger name
  53093. */
  53094. ActionManager.GetTriggerName = function (trigger) {
  53095. switch (trigger) {
  53096. case 0: return "NothingTrigger";
  53097. case 1: return "OnPickTrigger";
  53098. case 2: return "OnLeftPickTrigger";
  53099. case 3: return "OnRightPickTrigger";
  53100. case 4: return "OnCenterPickTrigger";
  53101. case 5: return "OnPickDownTrigger";
  53102. case 6: return "OnPickUpTrigger";
  53103. case 7: return "OnLongPressTrigger";
  53104. case 8: return "OnPointerOverTrigger";
  53105. case 9: return "OnPointerOutTrigger";
  53106. case 10: return "OnEveryFrameTrigger";
  53107. case 11: return "OnIntersectionEnterTrigger";
  53108. case 12: return "OnIntersectionExitTrigger";
  53109. case 13: return "OnKeyDownTrigger";
  53110. case 14: return "OnKeyUpTrigger";
  53111. case 15: return "OnPickOutTrigger";
  53112. default: return "";
  53113. }
  53114. };
  53115. // Statics
  53116. ActionManager._NothingTrigger = 0;
  53117. ActionManager._OnPickTrigger = 1;
  53118. ActionManager._OnLeftPickTrigger = 2;
  53119. ActionManager._OnRightPickTrigger = 3;
  53120. ActionManager._OnCenterPickTrigger = 4;
  53121. ActionManager._OnPickDownTrigger = 5;
  53122. ActionManager._OnDoublePickTrigger = 6;
  53123. ActionManager._OnPickUpTrigger = 7;
  53124. ActionManager._OnLongPressTrigger = 8;
  53125. ActionManager._OnPointerOverTrigger = 9;
  53126. ActionManager._OnPointerOutTrigger = 10;
  53127. ActionManager._OnEveryFrameTrigger = 11;
  53128. ActionManager._OnIntersectionEnterTrigger = 12;
  53129. ActionManager._OnIntersectionExitTrigger = 13;
  53130. ActionManager._OnKeyDownTrigger = 14;
  53131. ActionManager._OnKeyUpTrigger = 15;
  53132. ActionManager._OnPickOutTrigger = 16;
  53133. /** Gets the list of active triggers */
  53134. ActionManager.Triggers = {};
  53135. return ActionManager;
  53136. }());
  53137. BABYLON.ActionManager = ActionManager;
  53138. })(BABYLON || (BABYLON = {}));
  53139. //# sourceMappingURL=babylon.actionManager.js.map
  53140. var BABYLON;
  53141. (function (BABYLON) {
  53142. var InterpolateValueAction = /** @class */ (function (_super) {
  53143. __extends(InterpolateValueAction, _super);
  53144. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53145. if (duration === void 0) { duration = 1000; }
  53146. var _this = _super.call(this, triggerOptions, condition) || this;
  53147. _this.propertyPath = propertyPath;
  53148. _this.value = value;
  53149. _this.duration = duration;
  53150. _this.stopOtherAnimations = stopOtherAnimations;
  53151. _this.onInterpolationDone = onInterpolationDone;
  53152. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53153. _this._target = _this._effectiveTarget = target;
  53154. return _this;
  53155. }
  53156. /** @hidden */
  53157. InterpolateValueAction.prototype._prepare = function () {
  53158. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53159. this._property = this._getProperty(this.propertyPath);
  53160. };
  53161. InterpolateValueAction.prototype.execute = function () {
  53162. var _this = this;
  53163. var scene = this._actionManager.getScene();
  53164. var keys = [
  53165. {
  53166. frame: 0,
  53167. value: this._effectiveTarget[this._property]
  53168. }, {
  53169. frame: 100,
  53170. value: this.value
  53171. }
  53172. ];
  53173. var dataType;
  53174. if (typeof this.value === "number") {
  53175. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53176. }
  53177. else if (this.value instanceof BABYLON.Color3) {
  53178. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53179. }
  53180. else if (this.value instanceof BABYLON.Vector3) {
  53181. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53182. }
  53183. else if (this.value instanceof BABYLON.Matrix) {
  53184. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53185. }
  53186. else if (this.value instanceof BABYLON.Quaternion) {
  53187. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53188. }
  53189. else {
  53190. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53191. return;
  53192. }
  53193. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53194. animation.setKeys(keys);
  53195. if (this.stopOtherAnimations) {
  53196. scene.stopAnimation(this._effectiveTarget);
  53197. }
  53198. var wrapper = function () {
  53199. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53200. if (_this.onInterpolationDone) {
  53201. _this.onInterpolationDone();
  53202. }
  53203. };
  53204. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53205. };
  53206. InterpolateValueAction.prototype.serialize = function (parent) {
  53207. return _super.prototype._serialize.call(this, {
  53208. name: "InterpolateValueAction",
  53209. properties: [
  53210. BABYLON.Action._GetTargetProperty(this._target),
  53211. { name: "propertyPath", value: this.propertyPath },
  53212. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53213. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53214. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53215. ]
  53216. }, parent);
  53217. };
  53218. return InterpolateValueAction;
  53219. }(BABYLON.Action));
  53220. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53221. })(BABYLON || (BABYLON = {}));
  53222. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53223. var BABYLON;
  53224. (function (BABYLON) {
  53225. var SwitchBooleanAction = /** @class */ (function (_super) {
  53226. __extends(SwitchBooleanAction, _super);
  53227. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53228. var _this = _super.call(this, triggerOptions, condition) || this;
  53229. _this.propertyPath = propertyPath;
  53230. _this._target = _this._effectiveTarget = target;
  53231. return _this;
  53232. }
  53233. /** @hidden */
  53234. SwitchBooleanAction.prototype._prepare = function () {
  53235. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53236. this._property = this._getProperty(this.propertyPath);
  53237. };
  53238. SwitchBooleanAction.prototype.execute = function () {
  53239. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53240. };
  53241. SwitchBooleanAction.prototype.serialize = function (parent) {
  53242. return _super.prototype._serialize.call(this, {
  53243. name: "SwitchBooleanAction",
  53244. properties: [
  53245. BABYLON.Action._GetTargetProperty(this._target),
  53246. { name: "propertyPath", value: this.propertyPath }
  53247. ]
  53248. }, parent);
  53249. };
  53250. return SwitchBooleanAction;
  53251. }(BABYLON.Action));
  53252. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53253. var SetStateAction = /** @class */ (function (_super) {
  53254. __extends(SetStateAction, _super);
  53255. function SetStateAction(triggerOptions, target, value, condition) {
  53256. var _this = _super.call(this, triggerOptions, condition) || this;
  53257. _this.value = value;
  53258. _this._target = target;
  53259. return _this;
  53260. }
  53261. SetStateAction.prototype.execute = function () {
  53262. this._target.state = this.value;
  53263. };
  53264. SetStateAction.prototype.serialize = function (parent) {
  53265. return _super.prototype._serialize.call(this, {
  53266. name: "SetStateAction",
  53267. properties: [
  53268. BABYLON.Action._GetTargetProperty(this._target),
  53269. { name: "value", value: this.value }
  53270. ]
  53271. }, parent);
  53272. };
  53273. return SetStateAction;
  53274. }(BABYLON.Action));
  53275. BABYLON.SetStateAction = SetStateAction;
  53276. var SetValueAction = /** @class */ (function (_super) {
  53277. __extends(SetValueAction, _super);
  53278. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53279. var _this = _super.call(this, triggerOptions, condition) || this;
  53280. _this.propertyPath = propertyPath;
  53281. _this.value = value;
  53282. _this._target = _this._effectiveTarget = target;
  53283. return _this;
  53284. }
  53285. /** @hidden */
  53286. SetValueAction.prototype._prepare = function () {
  53287. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53288. this._property = this._getProperty(this.propertyPath);
  53289. };
  53290. SetValueAction.prototype.execute = function () {
  53291. this._effectiveTarget[this._property] = this.value;
  53292. if (this._target.markAsDirty) {
  53293. this._target.markAsDirty(this._property);
  53294. }
  53295. };
  53296. SetValueAction.prototype.serialize = function (parent) {
  53297. return _super.prototype._serialize.call(this, {
  53298. name: "SetValueAction",
  53299. properties: [
  53300. BABYLON.Action._GetTargetProperty(this._target),
  53301. { name: "propertyPath", value: this.propertyPath },
  53302. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53303. ]
  53304. }, parent);
  53305. };
  53306. return SetValueAction;
  53307. }(BABYLON.Action));
  53308. BABYLON.SetValueAction = SetValueAction;
  53309. var IncrementValueAction = /** @class */ (function (_super) {
  53310. __extends(IncrementValueAction, _super);
  53311. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53312. var _this = _super.call(this, triggerOptions, condition) || this;
  53313. _this.propertyPath = propertyPath;
  53314. _this.value = value;
  53315. _this._target = _this._effectiveTarget = target;
  53316. return _this;
  53317. }
  53318. /** @hidden */
  53319. IncrementValueAction.prototype._prepare = function () {
  53320. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53321. this._property = this._getProperty(this.propertyPath);
  53322. if (typeof this._effectiveTarget[this._property] !== "number") {
  53323. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53324. }
  53325. };
  53326. IncrementValueAction.prototype.execute = function () {
  53327. this._effectiveTarget[this._property] += this.value;
  53328. if (this._target.markAsDirty) {
  53329. this._target.markAsDirty(this._property);
  53330. }
  53331. };
  53332. IncrementValueAction.prototype.serialize = function (parent) {
  53333. return _super.prototype._serialize.call(this, {
  53334. name: "IncrementValueAction",
  53335. properties: [
  53336. BABYLON.Action._GetTargetProperty(this._target),
  53337. { name: "propertyPath", value: this.propertyPath },
  53338. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53339. ]
  53340. }, parent);
  53341. };
  53342. return IncrementValueAction;
  53343. }(BABYLON.Action));
  53344. BABYLON.IncrementValueAction = IncrementValueAction;
  53345. var PlayAnimationAction = /** @class */ (function (_super) {
  53346. __extends(PlayAnimationAction, _super);
  53347. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53348. var _this = _super.call(this, triggerOptions, condition) || this;
  53349. _this.from = from;
  53350. _this.to = to;
  53351. _this.loop = loop;
  53352. _this._target = target;
  53353. return _this;
  53354. }
  53355. /** @hidden */
  53356. PlayAnimationAction.prototype._prepare = function () {
  53357. };
  53358. PlayAnimationAction.prototype.execute = function () {
  53359. var scene = this._actionManager.getScene();
  53360. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53361. };
  53362. PlayAnimationAction.prototype.serialize = function (parent) {
  53363. return _super.prototype._serialize.call(this, {
  53364. name: "PlayAnimationAction",
  53365. properties: [
  53366. BABYLON.Action._GetTargetProperty(this._target),
  53367. { name: "from", value: String(this.from) },
  53368. { name: "to", value: String(this.to) },
  53369. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53370. ]
  53371. }, parent);
  53372. };
  53373. return PlayAnimationAction;
  53374. }(BABYLON.Action));
  53375. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53376. var StopAnimationAction = /** @class */ (function (_super) {
  53377. __extends(StopAnimationAction, _super);
  53378. function StopAnimationAction(triggerOptions, target, condition) {
  53379. var _this = _super.call(this, triggerOptions, condition) || this;
  53380. _this._target = target;
  53381. return _this;
  53382. }
  53383. /** @hidden */
  53384. StopAnimationAction.prototype._prepare = function () {
  53385. };
  53386. StopAnimationAction.prototype.execute = function () {
  53387. var scene = this._actionManager.getScene();
  53388. scene.stopAnimation(this._target);
  53389. };
  53390. StopAnimationAction.prototype.serialize = function (parent) {
  53391. return _super.prototype._serialize.call(this, {
  53392. name: "StopAnimationAction",
  53393. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53394. }, parent);
  53395. };
  53396. return StopAnimationAction;
  53397. }(BABYLON.Action));
  53398. BABYLON.StopAnimationAction = StopAnimationAction;
  53399. var DoNothingAction = /** @class */ (function (_super) {
  53400. __extends(DoNothingAction, _super);
  53401. function DoNothingAction(triggerOptions, condition) {
  53402. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53403. return _super.call(this, triggerOptions, condition) || this;
  53404. }
  53405. DoNothingAction.prototype.execute = function () {
  53406. };
  53407. DoNothingAction.prototype.serialize = function (parent) {
  53408. return _super.prototype._serialize.call(this, {
  53409. name: "DoNothingAction",
  53410. properties: []
  53411. }, parent);
  53412. };
  53413. return DoNothingAction;
  53414. }(BABYLON.Action));
  53415. BABYLON.DoNothingAction = DoNothingAction;
  53416. var CombineAction = /** @class */ (function (_super) {
  53417. __extends(CombineAction, _super);
  53418. function CombineAction(triggerOptions, children, condition) {
  53419. var _this = _super.call(this, triggerOptions, condition) || this;
  53420. _this.children = children;
  53421. return _this;
  53422. }
  53423. /** @hidden */
  53424. CombineAction.prototype._prepare = function () {
  53425. for (var index = 0; index < this.children.length; index++) {
  53426. this.children[index]._actionManager = this._actionManager;
  53427. this.children[index]._prepare();
  53428. }
  53429. };
  53430. CombineAction.prototype.execute = function (evt) {
  53431. for (var index = 0; index < this.children.length; index++) {
  53432. this.children[index].execute(evt);
  53433. }
  53434. };
  53435. CombineAction.prototype.serialize = function (parent) {
  53436. var serializationObject = _super.prototype._serialize.call(this, {
  53437. name: "CombineAction",
  53438. properties: [],
  53439. combine: []
  53440. }, parent);
  53441. for (var i = 0; i < this.children.length; i++) {
  53442. serializationObject.combine.push(this.children[i].serialize(null));
  53443. }
  53444. return serializationObject;
  53445. };
  53446. return CombineAction;
  53447. }(BABYLON.Action));
  53448. BABYLON.CombineAction = CombineAction;
  53449. var ExecuteCodeAction = /** @class */ (function (_super) {
  53450. __extends(ExecuteCodeAction, _super);
  53451. function ExecuteCodeAction(triggerOptions, func, condition) {
  53452. var _this = _super.call(this, triggerOptions, condition) || this;
  53453. _this.func = func;
  53454. return _this;
  53455. }
  53456. ExecuteCodeAction.prototype.execute = function (evt) {
  53457. this.func(evt);
  53458. };
  53459. return ExecuteCodeAction;
  53460. }(BABYLON.Action));
  53461. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53462. var SetParentAction = /** @class */ (function (_super) {
  53463. __extends(SetParentAction, _super);
  53464. function SetParentAction(triggerOptions, target, parent, condition) {
  53465. var _this = _super.call(this, triggerOptions, condition) || this;
  53466. _this._target = target;
  53467. _this._parent = parent;
  53468. return _this;
  53469. }
  53470. /** @hidden */
  53471. SetParentAction.prototype._prepare = function () {
  53472. };
  53473. SetParentAction.prototype.execute = function () {
  53474. if (this._target.parent === this._parent) {
  53475. return;
  53476. }
  53477. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53478. invertParentWorldMatrix.invert();
  53479. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53480. this._target.parent = this._parent;
  53481. };
  53482. SetParentAction.prototype.serialize = function (parent) {
  53483. return _super.prototype._serialize.call(this, {
  53484. name: "SetParentAction",
  53485. properties: [
  53486. BABYLON.Action._GetTargetProperty(this._target),
  53487. BABYLON.Action._GetTargetProperty(this._parent),
  53488. ]
  53489. }, parent);
  53490. };
  53491. return SetParentAction;
  53492. }(BABYLON.Action));
  53493. BABYLON.SetParentAction = SetParentAction;
  53494. })(BABYLON || (BABYLON = {}));
  53495. //# sourceMappingURL=babylon.directActions.js.map
  53496. var BABYLON;
  53497. (function (BABYLON) {
  53498. var SpriteManager = /** @class */ (function () {
  53499. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53500. if (epsilon === void 0) { epsilon = 0.01; }
  53501. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53502. this.name = name;
  53503. this.sprites = new Array();
  53504. this.renderingGroupId = 0;
  53505. this.layerMask = 0x0FFFFFFF;
  53506. this.fogEnabled = true;
  53507. this.isPickable = false;
  53508. /**
  53509. * An event triggered when the manager is disposed.
  53510. */
  53511. this.onDisposeObservable = new BABYLON.Observable();
  53512. this._vertexBuffers = {};
  53513. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  53514. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  53515. }
  53516. this._capacity = capacity;
  53517. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53518. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53519. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53520. if (cellSize.width && cellSize.height) {
  53521. this.cellWidth = cellSize.width;
  53522. this.cellHeight = cellSize.height;
  53523. }
  53524. else if (cellSize !== undefined) {
  53525. this.cellWidth = cellSize;
  53526. this.cellHeight = cellSize;
  53527. }
  53528. else {
  53529. return;
  53530. }
  53531. this._epsilon = epsilon;
  53532. this._scene = scene;
  53533. this._scene.spriteManagers.push(this);
  53534. var indices = [];
  53535. var index = 0;
  53536. for (var count = 0; count < capacity; count++) {
  53537. indices.push(index);
  53538. indices.push(index + 1);
  53539. indices.push(index + 2);
  53540. indices.push(index);
  53541. indices.push(index + 2);
  53542. indices.push(index + 3);
  53543. index += 4;
  53544. }
  53545. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53546. // VBO
  53547. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53548. this._vertexData = new Float32Array(capacity * 16 * 4);
  53549. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53550. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53551. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53552. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53553. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53554. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53555. this._vertexBuffers["options"] = options;
  53556. this._vertexBuffers["cellInfo"] = cellInfo;
  53557. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53558. // Effects
  53559. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53560. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53561. }
  53562. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53563. set: function (callback) {
  53564. if (this._onDisposeObserver) {
  53565. this.onDisposeObservable.remove(this._onDisposeObserver);
  53566. }
  53567. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53568. },
  53569. enumerable: true,
  53570. configurable: true
  53571. });
  53572. Object.defineProperty(SpriteManager.prototype, "texture", {
  53573. get: function () {
  53574. return this._spriteTexture;
  53575. },
  53576. set: function (value) {
  53577. this._spriteTexture = value;
  53578. },
  53579. enumerable: true,
  53580. configurable: true
  53581. });
  53582. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53583. var arrayOffset = index * 16;
  53584. if (offsetX === 0)
  53585. offsetX = this._epsilon;
  53586. else if (offsetX === 1)
  53587. offsetX = 1 - this._epsilon;
  53588. if (offsetY === 0)
  53589. offsetY = this._epsilon;
  53590. else if (offsetY === 1)
  53591. offsetY = 1 - this._epsilon;
  53592. this._vertexData[arrayOffset] = sprite.position.x;
  53593. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53594. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53595. this._vertexData[arrayOffset + 3] = sprite.angle;
  53596. this._vertexData[arrayOffset + 4] = sprite.width;
  53597. this._vertexData[arrayOffset + 5] = sprite.height;
  53598. this._vertexData[arrayOffset + 6] = offsetX;
  53599. this._vertexData[arrayOffset + 7] = offsetY;
  53600. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53601. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53602. var offset = (sprite.cellIndex / rowSize) >> 0;
  53603. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53604. this._vertexData[arrayOffset + 11] = offset;
  53605. // Color
  53606. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53607. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53608. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53609. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53610. };
  53611. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53612. var count = Math.min(this._capacity, this.sprites.length);
  53613. var min = BABYLON.Vector3.Zero();
  53614. var max = BABYLON.Vector3.Zero();
  53615. var distance = Number.MAX_VALUE;
  53616. var currentSprite = null;
  53617. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53618. var cameraView = camera.getViewMatrix();
  53619. for (var index = 0; index < count; index++) {
  53620. var sprite = this.sprites[index];
  53621. if (!sprite) {
  53622. continue;
  53623. }
  53624. if (predicate) {
  53625. if (!predicate(sprite)) {
  53626. continue;
  53627. }
  53628. }
  53629. else if (!sprite.isPickable) {
  53630. continue;
  53631. }
  53632. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53633. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53634. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53635. if (ray.intersectsBoxMinMax(min, max)) {
  53636. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53637. if (distance > currentDistance) {
  53638. distance = currentDistance;
  53639. currentSprite = sprite;
  53640. if (fastCheck) {
  53641. break;
  53642. }
  53643. }
  53644. }
  53645. }
  53646. if (currentSprite) {
  53647. var result = new BABYLON.PickingInfo();
  53648. result.hit = true;
  53649. result.pickedSprite = currentSprite;
  53650. result.distance = distance;
  53651. return result;
  53652. }
  53653. return null;
  53654. };
  53655. SpriteManager.prototype.render = function () {
  53656. // Check
  53657. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53658. return;
  53659. var engine = this._scene.getEngine();
  53660. var baseSize = this._spriteTexture.getBaseSize();
  53661. // Sprites
  53662. var deltaTime = engine.getDeltaTime();
  53663. var max = Math.min(this._capacity, this.sprites.length);
  53664. var rowSize = baseSize.width / this.cellWidth;
  53665. var offset = 0;
  53666. for (var index = 0; index < max; index++) {
  53667. var sprite = this.sprites[index];
  53668. if (!sprite || !sprite.isVisible) {
  53669. continue;
  53670. }
  53671. sprite._animate(deltaTime);
  53672. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53673. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53674. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53675. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53676. }
  53677. this._buffer.update(this._vertexData);
  53678. // Render
  53679. var effect = this._effectBase;
  53680. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53681. effect = this._effectFog;
  53682. }
  53683. engine.enableEffect(effect);
  53684. var viewMatrix = this._scene.getViewMatrix();
  53685. effect.setTexture("diffuseSampler", this._spriteTexture);
  53686. effect.setMatrix("view", viewMatrix);
  53687. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53688. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53689. // Fog
  53690. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53691. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53692. effect.setColor3("vFogColor", this._scene.fogColor);
  53693. }
  53694. // VBOs
  53695. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53696. // Draw order
  53697. engine.setDepthFunctionToLessOrEqual();
  53698. effect.setBool("alphaTest", true);
  53699. engine.setColorWrite(false);
  53700. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53701. engine.setColorWrite(true);
  53702. effect.setBool("alphaTest", false);
  53703. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53704. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53705. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53706. };
  53707. SpriteManager.prototype.dispose = function () {
  53708. if (this._buffer) {
  53709. this._buffer.dispose();
  53710. this._buffer = null;
  53711. }
  53712. if (this._indexBuffer) {
  53713. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53714. this._indexBuffer = null;
  53715. }
  53716. if (this._spriteTexture) {
  53717. this._spriteTexture.dispose();
  53718. this._spriteTexture = null;
  53719. }
  53720. // Remove from scene
  53721. var index = this._scene.spriteManagers.indexOf(this);
  53722. this._scene.spriteManagers.splice(index, 1);
  53723. // Callback
  53724. this.onDisposeObservable.notifyObservers(this);
  53725. this.onDisposeObservable.clear();
  53726. };
  53727. return SpriteManager;
  53728. }());
  53729. BABYLON.SpriteManager = SpriteManager;
  53730. })(BABYLON || (BABYLON = {}));
  53731. //# sourceMappingURL=babylon.spriteManager.js.map
  53732. var BABYLON;
  53733. (function (BABYLON) {
  53734. var Sprite = /** @class */ (function () {
  53735. function Sprite(name, manager) {
  53736. this.name = name;
  53737. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53738. this.width = 1.0;
  53739. this.height = 1.0;
  53740. this.angle = 0;
  53741. this.cellIndex = 0;
  53742. this.invertU = 0;
  53743. this.invertV = 0;
  53744. this.animations = new Array();
  53745. this.isPickable = false;
  53746. this._animationStarted = false;
  53747. this._loopAnimation = false;
  53748. this._fromIndex = 0;
  53749. this._toIndex = 0;
  53750. this._delay = 0;
  53751. this._direction = 1;
  53752. this._time = 0;
  53753. /**
  53754. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53755. */
  53756. this.isVisible = true;
  53757. this._manager = manager;
  53758. this._manager.sprites.push(this);
  53759. this.position = BABYLON.Vector3.Zero();
  53760. }
  53761. Object.defineProperty(Sprite.prototype, "size", {
  53762. get: function () {
  53763. return this.width;
  53764. },
  53765. set: function (value) {
  53766. this.width = value;
  53767. this.height = value;
  53768. },
  53769. enumerable: true,
  53770. configurable: true
  53771. });
  53772. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53773. this._fromIndex = from;
  53774. this._toIndex = to;
  53775. this._loopAnimation = loop;
  53776. this._delay = delay;
  53777. this._animationStarted = true;
  53778. this._direction = from < to ? 1 : -1;
  53779. this.cellIndex = from;
  53780. this._time = 0;
  53781. this._onAnimationEnd = onAnimationEnd;
  53782. };
  53783. Sprite.prototype.stopAnimation = function () {
  53784. this._animationStarted = false;
  53785. };
  53786. /** @hidden */
  53787. Sprite.prototype._animate = function (deltaTime) {
  53788. if (!this._animationStarted)
  53789. return;
  53790. this._time += deltaTime;
  53791. if (this._time > this._delay) {
  53792. this._time = this._time % this._delay;
  53793. this.cellIndex += this._direction;
  53794. if (this.cellIndex > this._toIndex) {
  53795. if (this._loopAnimation) {
  53796. this.cellIndex = this._fromIndex;
  53797. }
  53798. else {
  53799. this.cellIndex = this._toIndex;
  53800. this._animationStarted = false;
  53801. if (this._onAnimationEnd) {
  53802. this._onAnimationEnd();
  53803. }
  53804. if (this.disposeWhenFinishedAnimating) {
  53805. this.dispose();
  53806. }
  53807. }
  53808. }
  53809. }
  53810. };
  53811. Sprite.prototype.dispose = function () {
  53812. for (var i = 0; i < this._manager.sprites.length; i++) {
  53813. if (this._manager.sprites[i] == this) {
  53814. this._manager.sprites.splice(i, 1);
  53815. }
  53816. }
  53817. };
  53818. return Sprite;
  53819. }());
  53820. BABYLON.Sprite = Sprite;
  53821. })(BABYLON || (BABYLON = {}));
  53822. //# sourceMappingURL=babylon.sprite.js.map
  53823. var BABYLON;
  53824. (function (BABYLON) {
  53825. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  53826. if (!BABYLON.PickingInfo) {
  53827. return null;
  53828. }
  53829. var pickingInfo = null;
  53830. if (!camera) {
  53831. if (!this.activeCamera) {
  53832. return null;
  53833. }
  53834. camera = this.activeCamera;
  53835. }
  53836. if (this.spriteManagers.length > 0) {
  53837. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  53838. var spriteManager = this.spriteManagers[spriteIndex];
  53839. if (!spriteManager.isPickable) {
  53840. continue;
  53841. }
  53842. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  53843. if (!result || !result.hit)
  53844. continue;
  53845. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  53846. continue;
  53847. pickingInfo = result;
  53848. if (fastCheck) {
  53849. break;
  53850. }
  53851. }
  53852. }
  53853. return pickingInfo || new BABYLON.PickingInfo();
  53854. };
  53855. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  53856. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  53857. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  53858. };
  53859. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  53860. if (!this._tempSpritePickingRay) {
  53861. return null;
  53862. }
  53863. if (!camera) {
  53864. if (!this.activeCamera) {
  53865. return null;
  53866. }
  53867. camera = this.activeCamera;
  53868. }
  53869. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  53870. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  53871. };
  53872. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  53873. if (this._pointerOverSprite === sprite) {
  53874. return;
  53875. }
  53876. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  53877. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  53878. }
  53879. this._pointerOverSprite = sprite;
  53880. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  53881. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  53882. }
  53883. };
  53884. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  53885. return this._pointerOverSprite;
  53886. };
  53887. /**
  53888. * Defines the sprite scene component responsible to manage sprites
  53889. * in a given scene.
  53890. */
  53891. var SpriteSceneComponent = /** @class */ (function () {
  53892. /**
  53893. * Creates a new instance of the component for the given scene
  53894. * @param scene Defines the scene to register the component in
  53895. */
  53896. function SpriteSceneComponent(scene) {
  53897. /**
  53898. * The component name helpfull to identify the component in the list of scene components.
  53899. */
  53900. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  53901. this.scene = scene;
  53902. this.scene.spriteManagers = new Array();
  53903. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  53904. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  53905. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  53906. this._spritePredicate = function (sprite) {
  53907. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  53908. };
  53909. }
  53910. /**
  53911. * Registers the component in a given scene
  53912. */
  53913. SpriteSceneComponent.prototype.register = function () {
  53914. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  53915. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  53916. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  53917. };
  53918. /**
  53919. * Rebuilds the elements related to this component in case of
  53920. * context lost for instance.
  53921. */
  53922. SpriteSceneComponent.prototype.rebuild = function () {
  53923. /** Nothing to do for sprites */
  53924. };
  53925. /**
  53926. * Disposes the component and the associated ressources.
  53927. */
  53928. SpriteSceneComponent.prototype.dispose = function () {
  53929. this.scene.onBeforeSpritesRenderingObservable.clear();
  53930. this.scene.onAfterSpritesRenderingObservable.clear();
  53931. var spriteManagers = this.scene.spriteManagers;
  53932. while (spriteManagers.length) {
  53933. spriteManagers[0].dispose();
  53934. }
  53935. };
  53936. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  53937. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  53938. if (result) {
  53939. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  53940. }
  53941. return result;
  53942. };
  53943. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  53944. var scene = this.scene;
  53945. if (isMeshPicked) {
  53946. scene.setPointerOverSprite(null);
  53947. }
  53948. else {
  53949. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  53950. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  53951. scene.setPointerOverSprite(pickResult.pickedSprite);
  53952. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  53953. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  53954. }
  53955. else {
  53956. canvas.style.cursor = scene.hoverCursor;
  53957. }
  53958. }
  53959. else {
  53960. scene.setPointerOverSprite(null);
  53961. }
  53962. }
  53963. return pickResult;
  53964. };
  53965. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  53966. var scene = this.scene;
  53967. scene._pickedDownSprite = null;
  53968. if (scene.spriteManagers.length > 0) {
  53969. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  53970. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  53971. if (pickResult.pickedSprite.actionManager) {
  53972. scene._pickedDownSprite = pickResult.pickedSprite;
  53973. switch (evt.button) {
  53974. case 0:
  53975. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  53976. break;
  53977. case 1:
  53978. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  53979. break;
  53980. case 2:
  53981. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  53982. break;
  53983. }
  53984. if (pickResult.pickedSprite.actionManager) {
  53985. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  53986. }
  53987. }
  53988. }
  53989. }
  53990. return pickResult;
  53991. };
  53992. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  53993. var scene = this.scene;
  53994. if (scene.spriteManagers.length > 0) {
  53995. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  53996. if (spritePickResult) {
  53997. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  53998. if (spritePickResult.pickedSprite.actionManager) {
  53999. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  54000. if (spritePickResult.pickedSprite.actionManager) {
  54001. if (!this.scene._isPointerSwiping()) {
  54002. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  54003. }
  54004. }
  54005. }
  54006. }
  54007. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  54008. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  54009. }
  54010. }
  54011. }
  54012. return pickResult;
  54013. };
  54014. return SpriteSceneComponent;
  54015. }());
  54016. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  54017. })(BABYLON || (BABYLON = {}));
  54018. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  54019. var BABYLON;
  54020. (function (BABYLON) {
  54021. var IntersectionInfo = /** @class */ (function () {
  54022. function IntersectionInfo(bu, bv, distance) {
  54023. this.bu = bu;
  54024. this.bv = bv;
  54025. this.distance = distance;
  54026. this.faceId = 0;
  54027. this.subMeshId = 0;
  54028. }
  54029. return IntersectionInfo;
  54030. }());
  54031. BABYLON.IntersectionInfo = IntersectionInfo;
  54032. /**
  54033. * Information about the result of picking within a scene
  54034. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54035. */
  54036. var PickingInfo = /** @class */ (function () {
  54037. function PickingInfo() {
  54038. /**
  54039. * If the pick collided with an object
  54040. */
  54041. this.hit = false;
  54042. /**
  54043. * Distance away where the pick collided
  54044. */
  54045. this.distance = 0;
  54046. /**
  54047. * The location of pick collision
  54048. */
  54049. this.pickedPoint = null;
  54050. /**
  54051. * The mesh corresponding the the pick collision
  54052. */
  54053. this.pickedMesh = null;
  54054. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54055. this.bu = 0;
  54056. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54057. this.bv = 0;
  54058. /** The id of the face on the mesh that was picked */
  54059. this.faceId = -1;
  54060. /** Id of the the submesh that was picked */
  54061. this.subMeshId = 0;
  54062. /** If a sprite was picked, this will be the sprite the pick collided with */
  54063. this.pickedSprite = null;
  54064. /**
  54065. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54066. */
  54067. this.originMesh = null;
  54068. /**
  54069. * The ray that was used to perform the picking.
  54070. */
  54071. this.ray = null;
  54072. }
  54073. /**
  54074. * Gets the normal correspodning to the face the pick collided with
  54075. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54076. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54077. * @returns The normal correspodning to the face the pick collided with
  54078. */
  54079. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54080. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54081. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54082. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54083. return null;
  54084. }
  54085. var indices = this.pickedMesh.getIndices();
  54086. if (!indices) {
  54087. return null;
  54088. }
  54089. var result;
  54090. if (useVerticesNormals) {
  54091. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54092. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54093. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54094. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54095. normal0 = normal0.scale(this.bu);
  54096. normal1 = normal1.scale(this.bv);
  54097. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54098. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54099. }
  54100. else {
  54101. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54102. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54103. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54104. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54105. var p1p2 = vertex1.subtract(vertex2);
  54106. var p3p2 = vertex3.subtract(vertex2);
  54107. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54108. }
  54109. if (useWorldCoordinates) {
  54110. var wm = this.pickedMesh.getWorldMatrix();
  54111. if (this.pickedMesh.nonUniformScaling) {
  54112. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  54113. wm = BABYLON.Tmp.Matrix[0];
  54114. wm.setTranslationFromFloats(0, 0, 0);
  54115. wm.invert();
  54116. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  54117. wm = BABYLON.Tmp.Matrix[1];
  54118. }
  54119. result = BABYLON.Vector3.TransformNormal(result, wm);
  54120. }
  54121. result.normalize();
  54122. return result;
  54123. };
  54124. /**
  54125. * Gets the texture coordinates of where the pick occured
  54126. * @returns the vector containing the coordnates of the texture
  54127. */
  54128. PickingInfo.prototype.getTextureCoordinates = function () {
  54129. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54130. return null;
  54131. }
  54132. var indices = this.pickedMesh.getIndices();
  54133. if (!indices) {
  54134. return null;
  54135. }
  54136. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54137. if (!uvs) {
  54138. return null;
  54139. }
  54140. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54141. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54142. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54143. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54144. uv1 = uv1.scale(this.bu);
  54145. uv2 = uv2.scale(this.bv);
  54146. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54147. };
  54148. return PickingInfo;
  54149. }());
  54150. BABYLON.PickingInfo = PickingInfo;
  54151. })(BABYLON || (BABYLON = {}));
  54152. //# sourceMappingURL=babylon.pickingInfo.js.map
  54153. var BABYLON;
  54154. (function (BABYLON) {
  54155. var Ray = /** @class */ (function () {
  54156. function Ray(origin, direction, length) {
  54157. if (length === void 0) { length = Number.MAX_VALUE; }
  54158. this.origin = origin;
  54159. this.direction = direction;
  54160. this.length = length;
  54161. }
  54162. // Methods
  54163. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54164. var d = 0.0;
  54165. var maxValue = Number.MAX_VALUE;
  54166. var inv;
  54167. var min;
  54168. var max;
  54169. var temp;
  54170. if (Math.abs(this.direction.x) < 0.0000001) {
  54171. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54172. return false;
  54173. }
  54174. }
  54175. else {
  54176. inv = 1.0 / this.direction.x;
  54177. min = (minimum.x - this.origin.x) * inv;
  54178. max = (maximum.x - this.origin.x) * inv;
  54179. if (max === -Infinity) {
  54180. max = Infinity;
  54181. }
  54182. if (min > max) {
  54183. temp = min;
  54184. min = max;
  54185. max = temp;
  54186. }
  54187. d = Math.max(min, d);
  54188. maxValue = Math.min(max, maxValue);
  54189. if (d > maxValue) {
  54190. return false;
  54191. }
  54192. }
  54193. if (Math.abs(this.direction.y) < 0.0000001) {
  54194. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54195. return false;
  54196. }
  54197. }
  54198. else {
  54199. inv = 1.0 / this.direction.y;
  54200. min = (minimum.y - this.origin.y) * inv;
  54201. max = (maximum.y - this.origin.y) * inv;
  54202. if (max === -Infinity) {
  54203. max = Infinity;
  54204. }
  54205. if (min > max) {
  54206. temp = min;
  54207. min = max;
  54208. max = temp;
  54209. }
  54210. d = Math.max(min, d);
  54211. maxValue = Math.min(max, maxValue);
  54212. if (d > maxValue) {
  54213. return false;
  54214. }
  54215. }
  54216. if (Math.abs(this.direction.z) < 0.0000001) {
  54217. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54218. return false;
  54219. }
  54220. }
  54221. else {
  54222. inv = 1.0 / this.direction.z;
  54223. min = (minimum.z - this.origin.z) * inv;
  54224. max = (maximum.z - this.origin.z) * inv;
  54225. if (max === -Infinity) {
  54226. max = Infinity;
  54227. }
  54228. if (min > max) {
  54229. temp = min;
  54230. min = max;
  54231. max = temp;
  54232. }
  54233. d = Math.max(min, d);
  54234. maxValue = Math.min(max, maxValue);
  54235. if (d > maxValue) {
  54236. return false;
  54237. }
  54238. }
  54239. return true;
  54240. };
  54241. Ray.prototype.intersectsBox = function (box) {
  54242. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54243. };
  54244. Ray.prototype.intersectsSphere = function (sphere) {
  54245. var x = sphere.center.x - this.origin.x;
  54246. var y = sphere.center.y - this.origin.y;
  54247. var z = sphere.center.z - this.origin.z;
  54248. var pyth = (x * x) + (y * y) + (z * z);
  54249. var rr = sphere.radius * sphere.radius;
  54250. if (pyth <= rr) {
  54251. return true;
  54252. }
  54253. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54254. if (dot < 0.0) {
  54255. return false;
  54256. }
  54257. var temp = pyth - (dot * dot);
  54258. return temp <= rr;
  54259. };
  54260. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54261. if (!this._edge1) {
  54262. this._edge1 = BABYLON.Vector3.Zero();
  54263. this._edge2 = BABYLON.Vector3.Zero();
  54264. this._pvec = BABYLON.Vector3.Zero();
  54265. this._tvec = BABYLON.Vector3.Zero();
  54266. this._qvec = BABYLON.Vector3.Zero();
  54267. }
  54268. vertex1.subtractToRef(vertex0, this._edge1);
  54269. vertex2.subtractToRef(vertex0, this._edge2);
  54270. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54271. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54272. if (det === 0) {
  54273. return null;
  54274. }
  54275. var invdet = 1 / det;
  54276. this.origin.subtractToRef(vertex0, this._tvec);
  54277. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54278. if (bu < 0 || bu > 1.0) {
  54279. return null;
  54280. }
  54281. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54282. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54283. if (bv < 0 || bu + bv > 1.0) {
  54284. return null;
  54285. }
  54286. //check if the distance is longer than the predefined length.
  54287. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54288. if (distance > this.length) {
  54289. return null;
  54290. }
  54291. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54292. };
  54293. Ray.prototype.intersectsPlane = function (plane) {
  54294. var distance;
  54295. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54296. if (Math.abs(result1) < 9.99999997475243E-07) {
  54297. return null;
  54298. }
  54299. else {
  54300. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54301. distance = (-plane.d - result2) / result1;
  54302. if (distance < 0.0) {
  54303. if (distance < -9.99999997475243E-07) {
  54304. return null;
  54305. }
  54306. else {
  54307. return 0;
  54308. }
  54309. }
  54310. return distance;
  54311. }
  54312. };
  54313. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54314. var tm = BABYLON.Tmp.Matrix[0];
  54315. mesh.getWorldMatrix().invertToRef(tm);
  54316. if (this._tmpRay) {
  54317. Ray.TransformToRef(this, tm, this._tmpRay);
  54318. }
  54319. else {
  54320. this._tmpRay = Ray.Transform(this, tm);
  54321. }
  54322. return mesh.intersects(this._tmpRay, fastCheck);
  54323. };
  54324. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54325. if (results) {
  54326. results.length = 0;
  54327. }
  54328. else {
  54329. results = [];
  54330. }
  54331. for (var i = 0; i < meshes.length; i++) {
  54332. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54333. if (pickInfo.hit) {
  54334. results.push(pickInfo);
  54335. }
  54336. }
  54337. results.sort(this._comparePickingInfo);
  54338. return results;
  54339. };
  54340. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54341. if (pickingInfoA.distance < pickingInfoB.distance) {
  54342. return -1;
  54343. }
  54344. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54345. return 1;
  54346. }
  54347. else {
  54348. return 0;
  54349. }
  54350. };
  54351. /**
  54352. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54353. * @param sega the first point of the segment to test the intersection against
  54354. * @param segb the second point of the segment to test the intersection against
  54355. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54356. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54357. */
  54358. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54359. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54360. var u = segb.subtract(sega);
  54361. var v = rsegb.subtract(this.origin);
  54362. var w = sega.subtract(this.origin);
  54363. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54364. var b = BABYLON.Vector3.Dot(u, v);
  54365. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54366. var d = BABYLON.Vector3.Dot(u, w);
  54367. var e = BABYLON.Vector3.Dot(v, w);
  54368. var D = a * c - b * b; // always >= 0
  54369. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54370. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54371. // compute the line parameters of the two closest points
  54372. if (D < Ray.smallnum) { // the lines are almost parallel
  54373. sN = 0.0; // force using point P0 on segment S1
  54374. sD = 1.0; // to prevent possible division by 0.0 later
  54375. tN = e;
  54376. tD = c;
  54377. }
  54378. else { // get the closest points on the infinite lines
  54379. sN = (b * e - c * d);
  54380. tN = (a * e - b * d);
  54381. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54382. sN = 0.0;
  54383. tN = e;
  54384. tD = c;
  54385. }
  54386. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54387. sN = sD;
  54388. tN = e + b;
  54389. tD = c;
  54390. }
  54391. }
  54392. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54393. tN = 0.0;
  54394. // recompute sc for this edge
  54395. if (-d < 0.0) {
  54396. sN = 0.0;
  54397. }
  54398. else if (-d > a)
  54399. sN = sD;
  54400. else {
  54401. sN = -d;
  54402. sD = a;
  54403. }
  54404. }
  54405. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54406. tN = tD;
  54407. // recompute sc for this edge
  54408. if ((-d + b) < 0.0) {
  54409. sN = 0;
  54410. }
  54411. else if ((-d + b) > a) {
  54412. sN = sD;
  54413. }
  54414. else {
  54415. sN = (-d + b);
  54416. sD = a;
  54417. }
  54418. }
  54419. // finally do the division to get sc and tc
  54420. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54421. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54422. // get the difference of the two closest points
  54423. var qtc = v.multiplyByFloats(tc, tc, tc);
  54424. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54425. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54426. if (isIntersected) {
  54427. return qtc.length();
  54428. }
  54429. return -1;
  54430. };
  54431. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54432. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54433. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54434. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54435. this.direction.normalize();
  54436. return this;
  54437. };
  54438. // Statics
  54439. Ray.Zero = function () {
  54440. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54441. };
  54442. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54443. var result = Ray.Zero();
  54444. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54445. };
  54446. /**
  54447. * 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
  54448. * transformed to the given world matrix.
  54449. * @param origin The origin point
  54450. * @param end The end point
  54451. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54452. */
  54453. Ray.CreateNewFromTo = function (origin, end, world) {
  54454. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54455. var direction = end.subtract(origin);
  54456. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54457. direction.normalize();
  54458. return Ray.Transform(new Ray(origin, direction, length), world);
  54459. };
  54460. Ray.Transform = function (ray, matrix) {
  54461. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54462. Ray.TransformToRef(ray, matrix, result);
  54463. return result;
  54464. };
  54465. Ray.TransformToRef = function (ray, matrix, result) {
  54466. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54467. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54468. result.length = ray.length;
  54469. var dir = result.direction;
  54470. var len = dir.length();
  54471. if (!(len === 0 || len === 1)) {
  54472. var num = 1.0 / len;
  54473. dir.x *= num;
  54474. dir.y *= num;
  54475. dir.z *= num;
  54476. result.length *= len;
  54477. }
  54478. };
  54479. Ray.smallnum = 0.00000001;
  54480. Ray.rayl = 10e8;
  54481. return Ray;
  54482. }());
  54483. BABYLON.Ray = Ray;
  54484. })(BABYLON || (BABYLON = {}));
  54485. //# sourceMappingURL=babylon.ray.js.map
  54486. var BABYLON;
  54487. (function (BABYLON) {
  54488. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54489. if (boxMin.x > sphereCenter.x + sphereRadius)
  54490. return false;
  54491. if (sphereCenter.x - sphereRadius > boxMax.x)
  54492. return false;
  54493. if (boxMin.y > sphereCenter.y + sphereRadius)
  54494. return false;
  54495. if (sphereCenter.y - sphereRadius > boxMax.y)
  54496. return false;
  54497. if (boxMin.z > sphereCenter.z + sphereRadius)
  54498. return false;
  54499. if (sphereCenter.z - sphereRadius > boxMax.z)
  54500. return false;
  54501. return true;
  54502. };
  54503. var getLowestRoot = (function () {
  54504. var result = { root: 0, found: false };
  54505. return function (a, b, c, maxR) {
  54506. result.root = 0;
  54507. result.found = false;
  54508. var determinant = b * b - 4.0 * a * c;
  54509. if (determinant < 0)
  54510. return result;
  54511. var sqrtD = Math.sqrt(determinant);
  54512. var r1 = (-b - sqrtD) / (2.0 * a);
  54513. var r2 = (-b + sqrtD) / (2.0 * a);
  54514. if (r1 > r2) {
  54515. var temp = r2;
  54516. r2 = r1;
  54517. r1 = temp;
  54518. }
  54519. if (r1 > 0 && r1 < maxR) {
  54520. result.root = r1;
  54521. result.found = true;
  54522. return result;
  54523. }
  54524. if (r2 > 0 && r2 < maxR) {
  54525. result.root = r2;
  54526. result.found = true;
  54527. return result;
  54528. }
  54529. return result;
  54530. };
  54531. })();
  54532. var Collider = /** @class */ (function () {
  54533. function Collider() {
  54534. this._collisionPoint = BABYLON.Vector3.Zero();
  54535. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54536. this._tempVector = BABYLON.Vector3.Zero();
  54537. this._tempVector2 = BABYLON.Vector3.Zero();
  54538. this._tempVector3 = BABYLON.Vector3.Zero();
  54539. this._tempVector4 = BABYLON.Vector3.Zero();
  54540. this._edge = BABYLON.Vector3.Zero();
  54541. this._baseToVertex = BABYLON.Vector3.Zero();
  54542. this._destinationPoint = BABYLON.Vector3.Zero();
  54543. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54544. this._displacementVector = BABYLON.Vector3.Zero();
  54545. /** @hidden */
  54546. this._radius = BABYLON.Vector3.One();
  54547. /** @hidden */
  54548. this._retry = 0;
  54549. /** @hidden */
  54550. this._basePointWorld = BABYLON.Vector3.Zero();
  54551. this._velocityWorld = BABYLON.Vector3.Zero();
  54552. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54553. this._collisionMask = -1;
  54554. }
  54555. Object.defineProperty(Collider.prototype, "collisionMask", {
  54556. get: function () {
  54557. return this._collisionMask;
  54558. },
  54559. set: function (mask) {
  54560. this._collisionMask = !isNaN(mask) ? mask : -1;
  54561. },
  54562. enumerable: true,
  54563. configurable: true
  54564. });
  54565. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54566. /**
  54567. * Gets the plane normal used to compute the sliding response (in local space)
  54568. */
  54569. get: function () {
  54570. return this._slidePlaneNormal;
  54571. },
  54572. enumerable: true,
  54573. configurable: true
  54574. });
  54575. // Methods
  54576. /** @hidden */
  54577. Collider.prototype._initialize = function (source, dir, e) {
  54578. this._velocity = dir;
  54579. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54580. this._basePoint = source;
  54581. source.multiplyToRef(this._radius, this._basePointWorld);
  54582. dir.multiplyToRef(this._radius, this._velocityWorld);
  54583. this._velocityWorldLength = this._velocityWorld.length();
  54584. this._epsilon = e;
  54585. this.collisionFound = false;
  54586. };
  54587. /** @hidden */
  54588. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54589. pa.subtractToRef(point, this._tempVector);
  54590. pb.subtractToRef(point, this._tempVector2);
  54591. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54592. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54593. if (d < 0)
  54594. return false;
  54595. pc.subtractToRef(point, this._tempVector3);
  54596. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54597. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54598. if (d < 0)
  54599. return false;
  54600. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54601. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54602. return d >= 0;
  54603. };
  54604. /** @hidden */
  54605. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54606. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54607. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54608. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54609. return false;
  54610. }
  54611. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54612. return false;
  54613. return true;
  54614. };
  54615. /** @hidden */
  54616. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54617. var t0;
  54618. var embeddedInPlane = false;
  54619. //defensive programming, actually not needed.
  54620. if (!trianglePlaneArray) {
  54621. trianglePlaneArray = [];
  54622. }
  54623. if (!trianglePlaneArray[faceIndex]) {
  54624. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54625. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54626. }
  54627. var trianglePlane = trianglePlaneArray[faceIndex];
  54628. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54629. return;
  54630. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54631. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54632. if (normalDotVelocity == 0) {
  54633. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54634. return;
  54635. embeddedInPlane = true;
  54636. t0 = 0;
  54637. }
  54638. else {
  54639. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54640. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54641. if (t0 > t1) {
  54642. var temp = t1;
  54643. t1 = t0;
  54644. t0 = temp;
  54645. }
  54646. if (t0 > 1.0 || t1 < 0.0)
  54647. return;
  54648. if (t0 < 0)
  54649. t0 = 0;
  54650. if (t0 > 1.0)
  54651. t0 = 1.0;
  54652. }
  54653. this._collisionPoint.copyFromFloats(0, 0, 0);
  54654. var found = false;
  54655. var t = 1.0;
  54656. if (!embeddedInPlane) {
  54657. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54658. this._velocity.scaleToRef(t0, this._tempVector);
  54659. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54660. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54661. found = true;
  54662. t = t0;
  54663. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54664. }
  54665. }
  54666. if (!found) {
  54667. var velocitySquaredLength = this._velocity.lengthSquared();
  54668. var a = velocitySquaredLength;
  54669. this._basePoint.subtractToRef(p1, this._tempVector);
  54670. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54671. var c = this._tempVector.lengthSquared() - 1.0;
  54672. var lowestRoot = getLowestRoot(a, b, c, t);
  54673. if (lowestRoot.found) {
  54674. t = lowestRoot.root;
  54675. found = true;
  54676. this._collisionPoint.copyFrom(p1);
  54677. }
  54678. this._basePoint.subtractToRef(p2, this._tempVector);
  54679. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54680. c = this._tempVector.lengthSquared() - 1.0;
  54681. lowestRoot = getLowestRoot(a, b, c, t);
  54682. if (lowestRoot.found) {
  54683. t = lowestRoot.root;
  54684. found = true;
  54685. this._collisionPoint.copyFrom(p2);
  54686. }
  54687. this._basePoint.subtractToRef(p3, this._tempVector);
  54688. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54689. c = this._tempVector.lengthSquared() - 1.0;
  54690. lowestRoot = getLowestRoot(a, b, c, t);
  54691. if (lowestRoot.found) {
  54692. t = lowestRoot.root;
  54693. found = true;
  54694. this._collisionPoint.copyFrom(p3);
  54695. }
  54696. p2.subtractToRef(p1, this._edge);
  54697. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54698. var edgeSquaredLength = this._edge.lengthSquared();
  54699. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54700. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54701. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54702. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54703. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54704. lowestRoot = getLowestRoot(a, b, c, t);
  54705. if (lowestRoot.found) {
  54706. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54707. if (f >= 0.0 && f <= 1.0) {
  54708. t = lowestRoot.root;
  54709. found = true;
  54710. this._edge.scaleInPlace(f);
  54711. p1.addToRef(this._edge, this._collisionPoint);
  54712. }
  54713. }
  54714. p3.subtractToRef(p2, this._edge);
  54715. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54716. edgeSquaredLength = this._edge.lengthSquared();
  54717. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54718. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54719. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54720. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54721. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54722. lowestRoot = getLowestRoot(a, b, c, t);
  54723. if (lowestRoot.found) {
  54724. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54725. if (f >= 0.0 && f <= 1.0) {
  54726. t = lowestRoot.root;
  54727. found = true;
  54728. this._edge.scaleInPlace(f);
  54729. p2.addToRef(this._edge, this._collisionPoint);
  54730. }
  54731. }
  54732. p1.subtractToRef(p3, this._edge);
  54733. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54734. edgeSquaredLength = this._edge.lengthSquared();
  54735. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54736. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54737. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54738. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54739. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54740. lowestRoot = getLowestRoot(a, b, c, t);
  54741. if (lowestRoot.found) {
  54742. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54743. if (f >= 0.0 && f <= 1.0) {
  54744. t = lowestRoot.root;
  54745. found = true;
  54746. this._edge.scaleInPlace(f);
  54747. p3.addToRef(this._edge, this._collisionPoint);
  54748. }
  54749. }
  54750. }
  54751. if (found) {
  54752. var distToCollision = t * this._velocity.length();
  54753. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54754. if (!this.intersectionPoint) {
  54755. this.intersectionPoint = this._collisionPoint.clone();
  54756. }
  54757. else {
  54758. this.intersectionPoint.copyFrom(this._collisionPoint);
  54759. }
  54760. this._nearestDistance = distToCollision;
  54761. this.collisionFound = true;
  54762. }
  54763. }
  54764. };
  54765. /** @hidden */
  54766. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54767. for (var i = indexStart; i < indexEnd; i += 3) {
  54768. var p1 = pts[indices[i] - decal];
  54769. var p2 = pts[indices[i + 1] - decal];
  54770. var p3 = pts[indices[i + 2] - decal];
  54771. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54772. }
  54773. };
  54774. /** @hidden */
  54775. Collider.prototype._getResponse = function (pos, vel) {
  54776. pos.addToRef(vel, this._destinationPoint);
  54777. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54778. this._basePoint.addToRef(vel, pos);
  54779. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54780. this._slidePlaneNormal.normalize();
  54781. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54782. pos.addInPlace(this._displacementVector);
  54783. this.intersectionPoint.addInPlace(this._displacementVector);
  54784. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54785. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54786. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54787. };
  54788. return Collider;
  54789. }());
  54790. BABYLON.Collider = Collider;
  54791. })(BABYLON || (BABYLON = {}));
  54792. //# sourceMappingURL=babylon.collider.js.map
  54793. var BABYLON;
  54794. (function (BABYLON) {
  54795. //WebWorker code will be inserted to this variable.
  54796. BABYLON.CollisionWorker = "";
  54797. /** Defines supported task for worker process */
  54798. var WorkerTaskType;
  54799. (function (WorkerTaskType) {
  54800. /** Initialization */
  54801. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54802. /** Update of geometry */
  54803. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54804. /** Evaluate collision */
  54805. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54806. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54807. /** Defines kind of replies returned by worker */
  54808. var WorkerReplyType;
  54809. (function (WorkerReplyType) {
  54810. /** Success */
  54811. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54812. /** Unkown error */
  54813. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54814. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54815. var CollisionCoordinatorWorker = /** @class */ (function () {
  54816. function CollisionCoordinatorWorker() {
  54817. var _this = this;
  54818. this._scaledPosition = BABYLON.Vector3.Zero();
  54819. this._scaledVelocity = BABYLON.Vector3.Zero();
  54820. this.onMeshUpdated = function (transformNode) {
  54821. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54822. };
  54823. this.onGeometryUpdated = function (geometry) {
  54824. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54825. };
  54826. this._afterRender = function () {
  54827. if (!_this._init)
  54828. return;
  54829. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54830. return;
  54831. }
  54832. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54833. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54834. if (_this._runningUpdated > 4) {
  54835. return;
  54836. }
  54837. ++_this._runningUpdated;
  54838. var payload = {
  54839. updatedMeshes: _this._addUpdateMeshesList,
  54840. updatedGeometries: _this._addUpdateGeometriesList,
  54841. removedGeometries: _this._toRemoveGeometryArray,
  54842. removedMeshes: _this._toRemoveMeshesArray
  54843. };
  54844. var message = {
  54845. payload: payload,
  54846. taskType: WorkerTaskType.UPDATE
  54847. };
  54848. var serializable = [];
  54849. for (var id in payload.updatedGeometries) {
  54850. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54851. //prepare transferables
  54852. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54853. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54854. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54855. }
  54856. }
  54857. _this._worker.postMessage(message, serializable);
  54858. _this._addUpdateMeshesList = {};
  54859. _this._addUpdateGeometriesList = {};
  54860. _this._toRemoveGeometryArray = [];
  54861. _this._toRemoveMeshesArray = [];
  54862. };
  54863. this._onMessageFromWorker = function (e) {
  54864. var returnData = e.data;
  54865. if (returnData.error != WorkerReplyType.SUCCESS) {
  54866. //TODO what errors can be returned from the worker?
  54867. BABYLON.Tools.Warn("error returned from worker!");
  54868. return;
  54869. }
  54870. switch (returnData.taskType) {
  54871. case WorkerTaskType.INIT:
  54872. _this._init = true;
  54873. //Update the worked with ALL of the scene's current state
  54874. _this._scene.meshes.forEach(function (mesh) {
  54875. _this.onMeshAdded(mesh);
  54876. });
  54877. _this._scene.getGeometries().forEach(function (geometry) {
  54878. _this.onGeometryAdded(geometry);
  54879. });
  54880. break;
  54881. case WorkerTaskType.UPDATE:
  54882. _this._runningUpdated--;
  54883. break;
  54884. case WorkerTaskType.COLLIDE:
  54885. var returnPayload = returnData.payload;
  54886. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54887. return;
  54888. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54889. if (callback) {
  54890. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54891. if (mesh) {
  54892. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54893. }
  54894. }
  54895. //cleanup
  54896. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54897. break;
  54898. }
  54899. };
  54900. this._collisionsCallbackArray = [];
  54901. this._init = false;
  54902. this._runningUpdated = 0;
  54903. this._addUpdateMeshesList = {};
  54904. this._addUpdateGeometriesList = {};
  54905. this._toRemoveGeometryArray = [];
  54906. this._toRemoveMeshesArray = [];
  54907. }
  54908. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54909. if (!this._init)
  54910. return;
  54911. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54912. return;
  54913. position.divideToRef(collider._radius, this._scaledPosition);
  54914. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54915. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54916. var payload = {
  54917. collider: {
  54918. position: this._scaledPosition.asArray(),
  54919. velocity: this._scaledVelocity.asArray(),
  54920. radius: collider._radius.asArray()
  54921. },
  54922. collisionId: collisionIndex,
  54923. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54924. maximumRetry: maximumRetry
  54925. };
  54926. var message = {
  54927. payload: payload,
  54928. taskType: WorkerTaskType.COLLIDE
  54929. };
  54930. this._worker.postMessage(message);
  54931. };
  54932. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54933. this._scene = scene;
  54934. this._scene.registerAfterRender(this._afterRender);
  54935. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54936. this._worker = new Worker(workerUrl);
  54937. this._worker.onmessage = this._onMessageFromWorker;
  54938. var message = {
  54939. payload: {},
  54940. taskType: WorkerTaskType.INIT
  54941. };
  54942. this._worker.postMessage(message);
  54943. };
  54944. CollisionCoordinatorWorker.prototype.destroy = function () {
  54945. this._scene.unregisterAfterRender(this._afterRender);
  54946. this._worker.terminate();
  54947. };
  54948. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54949. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54950. this.onMeshUpdated(mesh);
  54951. };
  54952. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54953. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54954. };
  54955. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54956. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54957. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54958. this.onGeometryUpdated(geometry);
  54959. };
  54960. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54961. this._toRemoveGeometryArray.push(geometry.id);
  54962. };
  54963. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54964. var submeshes = [];
  54965. if (mesh.subMeshes) {
  54966. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54967. var boundingInfo = sm.getBoundingInfo();
  54968. return {
  54969. position: idx,
  54970. verticesStart: sm.verticesStart,
  54971. verticesCount: sm.verticesCount,
  54972. indexStart: sm.indexStart,
  54973. indexCount: sm.indexCount,
  54974. hasMaterial: !!sm.getMaterial(),
  54975. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54976. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54977. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54978. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54979. };
  54980. });
  54981. }
  54982. var geometryId = null;
  54983. if (mesh instanceof BABYLON.Mesh) {
  54984. var geometry = mesh.geometry;
  54985. geometryId = geometry ? geometry.id : null;
  54986. }
  54987. else if (mesh instanceof BABYLON.InstancedMesh) {
  54988. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54989. geometryId = geometry ? geometry.id : null;
  54990. }
  54991. var boundingInfo = mesh.getBoundingInfo();
  54992. return {
  54993. uniqueId: mesh.uniqueId,
  54994. id: mesh.id,
  54995. name: mesh.name,
  54996. geometryId: geometryId,
  54997. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54998. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54999. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55000. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55001. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55002. subMeshes: submeshes,
  55003. checkCollisions: mesh.checkCollisions
  55004. };
  55005. };
  55006. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55007. return {
  55008. id: geometry.id,
  55009. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55010. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55011. indices: new Uint32Array(geometry.getIndices() || []),
  55012. };
  55013. };
  55014. return CollisionCoordinatorWorker;
  55015. }());
  55016. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55017. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55018. function CollisionCoordinatorLegacy() {
  55019. this._scaledPosition = BABYLON.Vector3.Zero();
  55020. this._scaledVelocity = BABYLON.Vector3.Zero();
  55021. this._finalPosition = BABYLON.Vector3.Zero();
  55022. }
  55023. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55024. position.divideToRef(collider._radius, this._scaledPosition);
  55025. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55026. collider.collidedMesh = null;
  55027. collider._retry = 0;
  55028. collider._initialVelocity = this._scaledVelocity;
  55029. collider._initialPosition = this._scaledPosition;
  55030. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55031. this._finalPosition.multiplyInPlace(collider._radius);
  55032. //run the callback
  55033. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55034. };
  55035. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55036. this._scene = scene;
  55037. };
  55038. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55039. //Legacy need no destruction method.
  55040. };
  55041. //No update in legacy mode
  55042. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55043. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55044. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55045. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55046. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55047. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55048. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55049. if (excludedMesh === void 0) { excludedMesh = null; }
  55050. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55051. if (collider._retry >= maximumRetry) {
  55052. finalPosition.copyFrom(position);
  55053. return;
  55054. }
  55055. // Check if this is a mesh else camera or -1
  55056. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55057. collider._initialize(position, velocity, closeDistance);
  55058. // Check all meshes
  55059. for (var index = 0; index < this._scene.meshes.length; index++) {
  55060. var mesh = this._scene.meshes[index];
  55061. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55062. mesh._checkCollision(collider);
  55063. }
  55064. }
  55065. if (!collider.collisionFound) {
  55066. position.addToRef(velocity, finalPosition);
  55067. return;
  55068. }
  55069. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55070. collider._getResponse(position, velocity);
  55071. }
  55072. if (velocity.length() <= closeDistance) {
  55073. finalPosition.copyFrom(position);
  55074. return;
  55075. }
  55076. collider._retry++;
  55077. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55078. };
  55079. return CollisionCoordinatorLegacy;
  55080. }());
  55081. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55082. })(BABYLON || (BABYLON = {}));
  55083. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55084. var BABYLON;
  55085. (function (BABYLON) {
  55086. /**
  55087. * A particle represents one of the element emitted by a particle system.
  55088. * This is mainly define by its coordinates, direction, velocity and age.
  55089. */
  55090. var Particle = /** @class */ (function () {
  55091. /**
  55092. * Creates a new instance Particle
  55093. * @param particleSystem the particle system the particle belongs to
  55094. */
  55095. function Particle(
  55096. /**
  55097. * The particle system the particle belongs to.
  55098. */
  55099. particleSystem) {
  55100. this.particleSystem = particleSystem;
  55101. /**
  55102. * The world position of the particle in the scene.
  55103. */
  55104. this.position = BABYLON.Vector3.Zero();
  55105. /**
  55106. * The world direction of the particle in the scene.
  55107. */
  55108. this.direction = BABYLON.Vector3.Zero();
  55109. /**
  55110. * The color of the particle.
  55111. */
  55112. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55113. /**
  55114. * The color change of the particle per step.
  55115. */
  55116. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55117. /**
  55118. * Defines how long will the life of the particle be.
  55119. */
  55120. this.lifeTime = 1.0;
  55121. /**
  55122. * The current age of the particle.
  55123. */
  55124. this.age = 0;
  55125. /**
  55126. * The current size of the particle.
  55127. */
  55128. this.size = 0;
  55129. /**
  55130. * The current scale of the particle.
  55131. */
  55132. this.scale = new BABYLON.Vector2(1, 1);
  55133. /**
  55134. * The current angle of the particle.
  55135. */
  55136. this.angle = 0;
  55137. /**
  55138. * Defines how fast is the angle changing.
  55139. */
  55140. this.angularSpeed = 0;
  55141. /**
  55142. * Defines the cell index used by the particle to be rendered from a sprite.
  55143. */
  55144. this.cellIndex = 0;
  55145. /** @hidden */
  55146. this._attachedSubEmitters = null;
  55147. /** @hidden */
  55148. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  55149. /** @hidden */
  55150. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  55151. /** @hidden */
  55152. this._currentSize1 = 0;
  55153. /** @hidden */
  55154. this._currentSize2 = 0;
  55155. /** @hidden */
  55156. this._currentAngularSpeed1 = 0;
  55157. /** @hidden */
  55158. this._currentAngularSpeed2 = 0;
  55159. /** @hidden */
  55160. this._currentVelocity1 = 0;
  55161. /** @hidden */
  55162. this._currentVelocity2 = 0;
  55163. /** @hidden */
  55164. this._currentLimitVelocity1 = 0;
  55165. /** @hidden */
  55166. this._currentLimitVelocity2 = 0;
  55167. /** @hidden */
  55168. this._currentDrag1 = 0;
  55169. /** @hidden */
  55170. this._currentDrag2 = 0;
  55171. this.id = Particle._Count++;
  55172. if (!this.particleSystem.isAnimationSheetEnabled) {
  55173. return;
  55174. }
  55175. this.updateCellInfoFromSystem();
  55176. }
  55177. Particle.prototype.updateCellInfoFromSystem = function () {
  55178. this.cellIndex = this.particleSystem.startSpriteCellID;
  55179. };
  55180. /**
  55181. * Defines how the sprite cell index is updated for the particle
  55182. */
  55183. Particle.prototype.updateCellIndex = function () {
  55184. var offsetAge = this.age;
  55185. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  55186. if (this.particleSystem.spriteRandomStartCell) {
  55187. if (this._randomCellOffset === undefined) {
  55188. this._randomCellOffset = Math.random() * this.lifeTime;
  55189. }
  55190. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  55191. changeSpeed = 1;
  55192. offsetAge = this._randomCellOffset;
  55193. }
  55194. else {
  55195. offsetAge += this._randomCellOffset;
  55196. }
  55197. }
  55198. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  55199. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  55200. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  55201. };
  55202. /** @hidden */
  55203. Particle.prototype._reset = function () {
  55204. this.age = 0;
  55205. this._currentColorGradient = null;
  55206. this._currentSizeGradient = null;
  55207. this._currentAngularSpeedGradient = null;
  55208. this._currentVelocityGradient = null;
  55209. this._currentLimitVelocityGradient = null;
  55210. this._currentDragGradient = null;
  55211. this.cellIndex = this.particleSystem.startSpriteCellID;
  55212. this._randomCellOffset = undefined;
  55213. };
  55214. /**
  55215. * Copy the properties of particle to another one.
  55216. * @param other the particle to copy the information to.
  55217. */
  55218. Particle.prototype.copyTo = function (other) {
  55219. other.position.copyFrom(this.position);
  55220. if (this._initialDirection) {
  55221. if (other._initialDirection) {
  55222. other._initialDirection.copyFrom(this._initialDirection);
  55223. }
  55224. else {
  55225. other._initialDirection = this._initialDirection.clone();
  55226. }
  55227. }
  55228. else {
  55229. other._initialDirection = null;
  55230. }
  55231. other.direction.copyFrom(this.direction);
  55232. other.color.copyFrom(this.color);
  55233. other.colorStep.copyFrom(this.colorStep);
  55234. other.lifeTime = this.lifeTime;
  55235. other.age = this.age;
  55236. other._randomCellOffset = undefined;
  55237. other.size = this.size;
  55238. other.scale.copyFrom(this.scale);
  55239. other.angle = this.angle;
  55240. other.angularSpeed = this.angularSpeed;
  55241. other.particleSystem = this.particleSystem;
  55242. other.cellIndex = this.cellIndex;
  55243. other.id = this.id;
  55244. other._attachedSubEmitters = this._attachedSubEmitters;
  55245. if (this._currentColorGradient) {
  55246. other._currentColorGradient = this._currentColorGradient;
  55247. other._currentColor1.copyFrom(this._currentColor1);
  55248. other._currentColor2.copyFrom(this._currentColor2);
  55249. }
  55250. if (this._currentSizeGradient) {
  55251. other._currentSizeGradient = this._currentSizeGradient;
  55252. other._currentSize1 = this._currentSize1;
  55253. other._currentSize2 = this._currentSize2;
  55254. }
  55255. if (this._currentAngularSpeedGradient) {
  55256. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  55257. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  55258. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  55259. }
  55260. if (this._currentVelocityGradient) {
  55261. other._currentVelocityGradient = this._currentVelocityGradient;
  55262. other._currentVelocity1 = this._currentVelocity1;
  55263. other._currentVelocity2 = this._currentVelocity2;
  55264. }
  55265. if (this._currentLimitVelocityGradient) {
  55266. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  55267. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  55268. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  55269. }
  55270. if (this._currentDragGradient) {
  55271. other._currentDragGradient = this._currentDragGradient;
  55272. other._currentDrag1 = this._currentDrag1;
  55273. other._currentDrag2 = this._currentDrag2;
  55274. }
  55275. if (this.particleSystem.isAnimationSheetEnabled) {
  55276. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55277. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55278. }
  55279. if (this.particleSystem.useRampGradients) {
  55280. other.remapData.copyFrom(this.remapData);
  55281. }
  55282. if (this._randomNoiseCoordinates1) {
  55283. if (other._randomNoiseCoordinates1) {
  55284. other._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  55285. other._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  55286. }
  55287. else {
  55288. other._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  55289. other._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  55290. }
  55291. }
  55292. };
  55293. Particle._Count = 0;
  55294. return Particle;
  55295. }());
  55296. BABYLON.Particle = Particle;
  55297. })(BABYLON || (BABYLON = {}));
  55298. //# sourceMappingURL=babylon.particle.js.map
  55299. var BABYLON;
  55300. (function (BABYLON) {
  55301. /**
  55302. * This represents the base class for particle system in Babylon.
  55303. * 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.
  55304. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55305. * @example https://doc.babylonjs.com/babylon101/particles
  55306. */
  55307. var BaseParticleSystem = /** @class */ (function () {
  55308. /**
  55309. * Instantiates a particle system.
  55310. * 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.
  55311. * @param name The name of the particle system
  55312. */
  55313. function BaseParticleSystem(name) {
  55314. /**
  55315. * List of animations used by the particle system.
  55316. */
  55317. this.animations = [];
  55318. /**
  55319. * The rendering group used by the Particle system to chose when to render.
  55320. */
  55321. this.renderingGroupId = 0;
  55322. /**
  55323. * The emitter represents the Mesh or position we are attaching the particle system to.
  55324. */
  55325. this.emitter = null;
  55326. /**
  55327. * The maximum number of particles to emit per frame
  55328. */
  55329. this.emitRate = 10;
  55330. /**
  55331. * If you want to launch only a few particles at once, that can be done, as well.
  55332. */
  55333. this.manualEmitCount = -1;
  55334. /**
  55335. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55336. */
  55337. this.updateSpeed = 0.01;
  55338. /**
  55339. * The amount of time the particle system is running (depends of the overall update speed).
  55340. */
  55341. this.targetStopDuration = 0;
  55342. /**
  55343. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55344. */
  55345. this.disposeOnStop = false;
  55346. /**
  55347. * Minimum power of emitting particles.
  55348. */
  55349. this.minEmitPower = 1;
  55350. /**
  55351. * Maximum power of emitting particles.
  55352. */
  55353. this.maxEmitPower = 1;
  55354. /**
  55355. * Minimum life time of emitting particles.
  55356. */
  55357. this.minLifeTime = 1;
  55358. /**
  55359. * Maximum life time of emitting particles.
  55360. */
  55361. this.maxLifeTime = 1;
  55362. /**
  55363. * Minimum Size of emitting particles.
  55364. */
  55365. this.minSize = 1;
  55366. /**
  55367. * Maximum Size of emitting particles.
  55368. */
  55369. this.maxSize = 1;
  55370. /**
  55371. * Minimum scale of emitting particles on X axis.
  55372. */
  55373. this.minScaleX = 1;
  55374. /**
  55375. * Maximum scale of emitting particles on X axis.
  55376. */
  55377. this.maxScaleX = 1;
  55378. /**
  55379. * Minimum scale of emitting particles on Y axis.
  55380. */
  55381. this.minScaleY = 1;
  55382. /**
  55383. * Maximum scale of emitting particles on Y axis.
  55384. */
  55385. this.maxScaleY = 1;
  55386. /**
  55387. * Gets or sets the minimal initial rotation in radians.
  55388. */
  55389. this.minInitialRotation = 0;
  55390. /**
  55391. * Gets or sets the maximal initial rotation in radians.
  55392. */
  55393. this.maxInitialRotation = 0;
  55394. /**
  55395. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55396. */
  55397. this.minAngularSpeed = 0;
  55398. /**
  55399. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55400. */
  55401. this.maxAngularSpeed = 0;
  55402. /**
  55403. * The layer mask we are rendering the particles through.
  55404. */
  55405. this.layerMask = 0x0FFFFFFF;
  55406. /**
  55407. * This can help using your own shader to render the particle system.
  55408. * The according effect will be created
  55409. */
  55410. this.customShader = null;
  55411. /**
  55412. * By default particle system starts as soon as they are created. This prevents the
  55413. * automatic start to happen and let you decide when to start emitting particles.
  55414. */
  55415. this.preventAutoStart = false;
  55416. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55417. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55418. /**
  55419. * Callback triggered when the particle animation is ending.
  55420. */
  55421. this.onAnimationEnd = null;
  55422. /**
  55423. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55424. */
  55425. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55426. /**
  55427. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55428. * to override the particles.
  55429. */
  55430. this.forceDepthWrite = false;
  55431. /** 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 */
  55432. this.preWarmCycles = 0;
  55433. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55434. this.preWarmStepOffset = 1;
  55435. /**
  55436. * 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)
  55437. */
  55438. this.spriteCellChangeSpeed = 1;
  55439. /**
  55440. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55441. */
  55442. this.startSpriteCellID = 0;
  55443. /**
  55444. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55445. */
  55446. this.endSpriteCellID = 0;
  55447. /**
  55448. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55449. */
  55450. this.spriteCellWidth = 0;
  55451. /**
  55452. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55453. */
  55454. this.spriteCellHeight = 0;
  55455. /**
  55456. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  55457. */
  55458. this.spriteRandomStartCell = false;
  55459. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55460. this.translationPivot = new BABYLON.Vector2(0, 0);
  55461. /**
  55462. * You can use gravity if you want to give an orientation to your particles.
  55463. */
  55464. this.gravity = BABYLON.Vector3.Zero();
  55465. this._colorGradients = null;
  55466. this._sizeGradients = null;
  55467. this._lifeTimeGradients = null;
  55468. this._angularSpeedGradients = null;
  55469. this._velocityGradients = null;
  55470. this._limitVelocityGradients = null;
  55471. this._dragGradients = null;
  55472. this._emitRateGradients = null;
  55473. this._startSizeGradients = null;
  55474. this._rampGradients = null;
  55475. this._colorRemapGradients = null;
  55476. this._alphaRemapGradients = null;
  55477. /**
  55478. * Defines the delay in milliseconds before starting the system (0 by default)
  55479. */
  55480. this.startDelay = 0;
  55481. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  55482. this.limitVelocityDamping = 0.4;
  55483. /**
  55484. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55485. */
  55486. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55487. /**
  55488. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55489. */
  55490. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55491. /**
  55492. * Color the particle will have at the end of its lifetime
  55493. */
  55494. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55495. /**
  55496. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55497. */
  55498. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55499. /**
  55500. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55501. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55502. */
  55503. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55504. this._isBillboardBased = true;
  55505. /**
  55506. * Local cache of defines for image processing.
  55507. */
  55508. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  55509. this.id = name;
  55510. this.name = name;
  55511. }
  55512. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  55513. /**
  55514. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55515. */
  55516. get: function () {
  55517. return this._isAnimationSheetEnabled;
  55518. },
  55519. set: function (value) {
  55520. if (this._isAnimationSheetEnabled == value) {
  55521. return;
  55522. }
  55523. this._isAnimationSheetEnabled = value;
  55524. this._reset();
  55525. },
  55526. enumerable: true,
  55527. configurable: true
  55528. });
  55529. /**
  55530. * Get hosting scene
  55531. * @returns the scene
  55532. */
  55533. BaseParticleSystem.prototype.getScene = function () {
  55534. return this._scene;
  55535. };
  55536. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  55537. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  55538. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  55539. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  55540. };
  55541. /**
  55542. * Gets the current list of drag gradients.
  55543. * You must use addDragGradient and removeDragGradient to udpate this list
  55544. * @returns the list of drag gradients
  55545. */
  55546. BaseParticleSystem.prototype.getDragGradients = function () {
  55547. return this._dragGradients;
  55548. };
  55549. /**
  55550. * Gets the current list of limit velocity gradients.
  55551. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  55552. * @returns the list of limit velocity gradients
  55553. */
  55554. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  55555. return this._limitVelocityGradients;
  55556. };
  55557. /**
  55558. * Gets the current list of color gradients.
  55559. * You must use addColorGradient and removeColorGradient to udpate this list
  55560. * @returns the list of color gradients
  55561. */
  55562. BaseParticleSystem.prototype.getColorGradients = function () {
  55563. return this._colorGradients;
  55564. };
  55565. /**
  55566. * Gets the current list of size gradients.
  55567. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55568. * @returns the list of size gradients
  55569. */
  55570. BaseParticleSystem.prototype.getSizeGradients = function () {
  55571. return this._sizeGradients;
  55572. };
  55573. /**
  55574. * Gets the current list of color remap gradients.
  55575. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  55576. * @returns the list of color remap gradients
  55577. */
  55578. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  55579. return this._colorRemapGradients;
  55580. };
  55581. /**
  55582. * Gets the current list of alpha remap gradients.
  55583. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  55584. * @returns the list of alpha remap gradients
  55585. */
  55586. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  55587. return this._alphaRemapGradients;
  55588. };
  55589. /**
  55590. * Gets the current list of life time gradients.
  55591. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55592. * @returns the list of life time gradients
  55593. */
  55594. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  55595. return this._lifeTimeGradients;
  55596. };
  55597. /**
  55598. * Gets the current list of angular speed gradients.
  55599. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55600. * @returns the list of angular speed gradients
  55601. */
  55602. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  55603. return this._angularSpeedGradients;
  55604. };
  55605. /**
  55606. * Gets the current list of velocity gradients.
  55607. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55608. * @returns the list of velocity gradients
  55609. */
  55610. BaseParticleSystem.prototype.getVelocityGradients = function () {
  55611. return this._velocityGradients;
  55612. };
  55613. /**
  55614. * Gets the current list of start size gradients.
  55615. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  55616. * @returns the list of start size gradients
  55617. */
  55618. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  55619. return this._startSizeGradients;
  55620. };
  55621. /**
  55622. * Gets the current list of emit rate gradients.
  55623. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  55624. * @returns the list of emit rate gradients
  55625. */
  55626. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  55627. return this._emitRateGradients;
  55628. };
  55629. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  55630. /**
  55631. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55632. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55633. */
  55634. get: function () {
  55635. if (this.particleEmitterType.direction1) {
  55636. return this.particleEmitterType.direction1;
  55637. }
  55638. return BABYLON.Vector3.Zero();
  55639. },
  55640. set: function (value) {
  55641. if (this.particleEmitterType.direction1) {
  55642. this.particleEmitterType.direction1 = value;
  55643. }
  55644. },
  55645. enumerable: true,
  55646. configurable: true
  55647. });
  55648. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  55649. /**
  55650. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55651. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55652. */
  55653. get: function () {
  55654. if (this.particleEmitterType.direction2) {
  55655. return this.particleEmitterType.direction2;
  55656. }
  55657. return BABYLON.Vector3.Zero();
  55658. },
  55659. set: function (value) {
  55660. if (this.particleEmitterType.direction2) {
  55661. this.particleEmitterType.direction2 = value;
  55662. }
  55663. },
  55664. enumerable: true,
  55665. configurable: true
  55666. });
  55667. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  55668. /**
  55669. * 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.
  55670. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55671. */
  55672. get: function () {
  55673. if (this.particleEmitterType.minEmitBox) {
  55674. return this.particleEmitterType.minEmitBox;
  55675. }
  55676. return BABYLON.Vector3.Zero();
  55677. },
  55678. set: function (value) {
  55679. if (this.particleEmitterType.minEmitBox) {
  55680. this.particleEmitterType.minEmitBox = value;
  55681. }
  55682. },
  55683. enumerable: true,
  55684. configurable: true
  55685. });
  55686. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  55687. /**
  55688. * 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.
  55689. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55690. */
  55691. get: function () {
  55692. if (this.particleEmitterType.maxEmitBox) {
  55693. return this.particleEmitterType.maxEmitBox;
  55694. }
  55695. return BABYLON.Vector3.Zero();
  55696. },
  55697. set: function (value) {
  55698. if (this.particleEmitterType.maxEmitBox) {
  55699. this.particleEmitterType.maxEmitBox = value;
  55700. }
  55701. },
  55702. enumerable: true,
  55703. configurable: true
  55704. });
  55705. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  55706. /**
  55707. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55708. */
  55709. get: function () {
  55710. return this._isBillboardBased;
  55711. },
  55712. set: function (value) {
  55713. if (this._isBillboardBased === value) {
  55714. return;
  55715. }
  55716. this._isBillboardBased = value;
  55717. this._reset();
  55718. },
  55719. enumerable: true,
  55720. configurable: true
  55721. });
  55722. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  55723. /**
  55724. * Gets the image processing configuration used either in this material.
  55725. */
  55726. get: function () {
  55727. return this._imageProcessingConfiguration;
  55728. },
  55729. /**
  55730. * Sets the Default image processing configuration used either in the this material.
  55731. *
  55732. * If sets to null, the scene one is in use.
  55733. */
  55734. set: function (value) {
  55735. this._attachImageProcessingConfiguration(value);
  55736. },
  55737. enumerable: true,
  55738. configurable: true
  55739. });
  55740. /**
  55741. * Attaches a new image processing configuration to the Standard Material.
  55742. * @param configuration
  55743. */
  55744. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  55745. if (configuration === this._imageProcessingConfiguration) {
  55746. return;
  55747. }
  55748. // Pick the scene configuration if needed.
  55749. if (!configuration) {
  55750. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  55751. }
  55752. else {
  55753. this._imageProcessingConfiguration = configuration;
  55754. }
  55755. };
  55756. /** @hidden */
  55757. BaseParticleSystem.prototype._reset = function () {
  55758. };
  55759. /** @hidden */
  55760. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  55761. if (!gradients) {
  55762. return this;
  55763. }
  55764. var index = 0;
  55765. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  55766. var valueGradient = gradients_1[_i];
  55767. if (valueGradient.gradient === gradient) {
  55768. gradients.splice(index, 1);
  55769. break;
  55770. }
  55771. index++;
  55772. }
  55773. if (texture) {
  55774. texture.dispose();
  55775. }
  55776. return this;
  55777. };
  55778. /**
  55779. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  55780. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55781. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55782. * @returns the emitter
  55783. */
  55784. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  55785. var particleEmitter = new BABYLON.PointParticleEmitter();
  55786. particleEmitter.direction1 = direction1;
  55787. particleEmitter.direction2 = direction2;
  55788. this.particleEmitterType = particleEmitter;
  55789. return particleEmitter;
  55790. };
  55791. /**
  55792. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  55793. * @param radius The radius of the hemisphere to emit from
  55794. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  55795. * @returns the emitter
  55796. */
  55797. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  55798. if (radius === void 0) { radius = 1; }
  55799. if (radiusRange === void 0) { radiusRange = 1; }
  55800. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  55801. this.particleEmitterType = particleEmitter;
  55802. return particleEmitter;
  55803. };
  55804. /**
  55805. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  55806. * @param radius The radius of the sphere to emit from
  55807. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  55808. * @returns the emitter
  55809. */
  55810. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  55811. if (radius === void 0) { radius = 1; }
  55812. if (radiusRange === void 0) { radiusRange = 1; }
  55813. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  55814. this.particleEmitterType = particleEmitter;
  55815. return particleEmitter;
  55816. };
  55817. /**
  55818. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  55819. * @param radius The radius of the sphere to emit from
  55820. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55821. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55822. * @returns the emitter
  55823. */
  55824. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55825. if (radius === void 0) { radius = 1; }
  55826. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55827. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55828. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55829. this.particleEmitterType = particleEmitter;
  55830. return particleEmitter;
  55831. };
  55832. /**
  55833. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  55834. * @param radius The radius of the emission cylinder
  55835. * @param height The height of the emission cylinder
  55836. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  55837. * @param directionRandomizer How much to randomize the particle direction [0-1]
  55838. * @returns the emitter
  55839. */
  55840. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  55841. if (radius === void 0) { radius = 1; }
  55842. if (height === void 0) { height = 1; }
  55843. if (radiusRange === void 0) { radiusRange = 1; }
  55844. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  55845. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  55846. this.particleEmitterType = particleEmitter;
  55847. return particleEmitter;
  55848. };
  55849. /**
  55850. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  55851. * @param radius The radius of the cylinder to emit from
  55852. * @param height The height of the emission cylinder
  55853. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  55854. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  55855. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  55856. * @returns the emitter
  55857. */
  55858. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  55859. if (radius === void 0) { radius = 1; }
  55860. if (height === void 0) { height = 1; }
  55861. if (radiusRange === void 0) { radiusRange = 1; }
  55862. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55863. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55864. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  55865. this.particleEmitterType = particleEmitter;
  55866. return particleEmitter;
  55867. };
  55868. /**
  55869. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  55870. * @param radius The radius of the cone to emit from
  55871. * @param angle The base angle of the cone
  55872. * @returns the emitter
  55873. */
  55874. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55875. if (radius === void 0) { radius = 1; }
  55876. if (angle === void 0) { angle = Math.PI / 4; }
  55877. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55878. this.particleEmitterType = particleEmitter;
  55879. return particleEmitter;
  55880. };
  55881. /**
  55882. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55883. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55884. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55885. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55886. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55887. * @returns the emitter
  55888. */
  55889. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55890. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55891. this.particleEmitterType = particleEmitter;
  55892. this.direction1 = direction1;
  55893. this.direction2 = direction2;
  55894. this.minEmitBox = minEmitBox;
  55895. this.maxEmitBox = maxEmitBox;
  55896. return particleEmitter;
  55897. };
  55898. /**
  55899. * Source color is added to the destination color without alpha affecting the result
  55900. */
  55901. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  55902. /**
  55903. * Blend current color and particle color using particle’s alpha
  55904. */
  55905. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  55906. /**
  55907. * Add current color and particle color multiplied by particle’s alpha
  55908. */
  55909. BaseParticleSystem.BLENDMODE_ADD = 2;
  55910. /**
  55911. * Multiply current color with particle color
  55912. */
  55913. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  55914. /**
  55915. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  55916. */
  55917. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  55918. return BaseParticleSystem;
  55919. }());
  55920. BABYLON.BaseParticleSystem = BaseParticleSystem;
  55921. })(BABYLON || (BABYLON = {}));
  55922. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  55923. var BABYLON;
  55924. (function (BABYLON) {
  55925. /**
  55926. * This represents a particle system in Babylon.
  55927. * 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.
  55928. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55929. * @example https://doc.babylonjs.com/babylon101/particles
  55930. */
  55931. var ParticleSystem = /** @class */ (function (_super) {
  55932. __extends(ParticleSystem, _super);
  55933. /**
  55934. * Instantiates a particle system.
  55935. * 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.
  55936. * @param name The name of the particle system
  55937. * @param capacity The max number of particles alive at the same time
  55938. * @param scene The scene the particle system belongs to
  55939. * @param customEffect a custom effect used to change the way particles are rendered by default
  55940. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55941. * @param epsilon Offset used to render the particles
  55942. */
  55943. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55944. if (customEffect === void 0) { customEffect = null; }
  55945. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55946. if (epsilon === void 0) { epsilon = 0.01; }
  55947. var _this = _super.call(this, name) || this;
  55948. /**
  55949. * @hidden
  55950. */
  55951. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  55952. /**
  55953. * An event triggered when the system is disposed
  55954. */
  55955. _this.onDisposeObservable = new BABYLON.Observable();
  55956. _this._particles = new Array();
  55957. _this._stockParticles = new Array();
  55958. _this._newPartsExcess = 0;
  55959. _this._vertexBuffers = {};
  55960. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55961. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55962. _this._scaledDirection = BABYLON.Vector3.Zero();
  55963. _this._scaledGravity = BABYLON.Vector3.Zero();
  55964. _this._currentRenderId = -1;
  55965. _this._useInstancing = false;
  55966. _this._started = false;
  55967. _this._stopped = false;
  55968. _this._actualFrame = 0;
  55969. /** @hidden */
  55970. _this._currentEmitRate1 = 0;
  55971. /** @hidden */
  55972. _this._currentEmitRate2 = 0;
  55973. /** @hidden */
  55974. _this._currentStartSize1 = 0;
  55975. /** @hidden */
  55976. _this._currentStartSize2 = 0;
  55977. _this._rawTextureWidth = 256;
  55978. _this._useRampGradients = false;
  55979. /**
  55980. * @hidden
  55981. * If the particle systems emitter should be disposed when the particle system is disposed
  55982. */
  55983. _this._disposeEmitterOnDispose = false;
  55984. // start of sub system methods
  55985. /**
  55986. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55987. * Its lifetime will start back at 0.
  55988. */
  55989. _this.recycleParticle = function (particle) {
  55990. // move particle from activeParticle list to stock particles
  55991. var lastParticle = _this._particles.pop();
  55992. if (lastParticle !== particle) {
  55993. lastParticle.copyTo(particle);
  55994. }
  55995. _this._stockParticles.push(lastParticle);
  55996. };
  55997. _this._createParticle = function () {
  55998. var particle;
  55999. if (_this._stockParticles.length !== 0) {
  56000. particle = _this._stockParticles.pop();
  56001. particle._reset();
  56002. }
  56003. else {
  56004. particle = new BABYLON.Particle(_this);
  56005. }
  56006. // Attach emitters
  56007. if (_this._subEmitters && _this._subEmitters.length > 0) {
  56008. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  56009. particle._attachedSubEmitters = [];
  56010. subEmitters.forEach(function (subEmitter) {
  56011. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  56012. var newEmitter = subEmitter.clone();
  56013. particle._attachedSubEmitters.push(newEmitter);
  56014. newEmitter.particleSystem.start();
  56015. }
  56016. });
  56017. }
  56018. return particle;
  56019. };
  56020. _this._emitFromParticle = function (particle) {
  56021. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  56022. return;
  56023. }
  56024. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  56025. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  56026. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  56027. var subSystem = subEmitter.clone();
  56028. ParticleSystem._InheritParticleInfoToSubEmitter(subSystem, particle);
  56029. subSystem.particleSystem._rootParticleSystem = _this;
  56030. _this.activeSubSystems.push(subSystem.particleSystem);
  56031. subSystem.particleSystem.start();
  56032. }
  56033. });
  56034. };
  56035. _this._capacity = capacity;
  56036. _this._epsilon = epsilon;
  56037. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56038. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56039. // Setup the default processing configuration to the scene.
  56040. _this._attachImageProcessingConfiguration(null);
  56041. _this._customEffect = customEffect;
  56042. _this._scene.particleSystems.push(_this);
  56043. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  56044. _this._createIndexBuffer();
  56045. _this._createVertexBuffers();
  56046. // Default emitter type
  56047. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56048. // Update
  56049. _this.updateFunction = function (particles) {
  56050. var noiseTextureSize = null;
  56051. var noiseTextureData = null;
  56052. if (_this.noiseTexture) { // We need to get texture data back to CPU
  56053. noiseTextureSize = _this.noiseTexture.getSize();
  56054. noiseTextureData = (_this.noiseTexture.getContent());
  56055. }
  56056. var _loop_1 = function () {
  56057. particle = particles[index];
  56058. particle.age += _this._scaledUpdateSpeed;
  56059. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56060. _this._emitFromParticle(particle);
  56061. if (particle._attachedSubEmitters) {
  56062. particle._attachedSubEmitters.forEach(function (subEmitter) {
  56063. subEmitter.particleSystem.disposeOnStop = true;
  56064. subEmitter.particleSystem.stop();
  56065. });
  56066. particle._attachedSubEmitters = null;
  56067. }
  56068. _this.recycleParticle(particle);
  56069. index--;
  56070. return "continue";
  56071. }
  56072. else {
  56073. var ratio = particle.age / particle.lifeTime;
  56074. // Color
  56075. if (_this._colorGradients && _this._colorGradients.length > 0) {
  56076. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  56077. if (currentGradient !== particle._currentColorGradient) {
  56078. particle._currentColor1.copyFrom(particle._currentColor2);
  56079. nextGradient.getColorToRef(particle._currentColor2);
  56080. particle._currentColorGradient = currentGradient;
  56081. }
  56082. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  56083. });
  56084. }
  56085. else {
  56086. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56087. particle.color.addInPlace(_this._scaledColorStep);
  56088. if (particle.color.a < 0) {
  56089. particle.color.a = 0;
  56090. }
  56091. }
  56092. // Angular speed
  56093. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  56094. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  56095. if (currentGradient !== particle._currentAngularSpeedGradient) {
  56096. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  56097. particle._currentAngularSpeed2 = nextGradient.getFactor();
  56098. particle._currentAngularSpeedGradient = currentGradient;
  56099. }
  56100. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  56101. });
  56102. }
  56103. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56104. // Direction
  56105. var directionScale_1 = _this._scaledUpdateSpeed;
  56106. /// Velocity
  56107. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  56108. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  56109. if (currentGradient !== particle._currentVelocityGradient) {
  56110. particle._currentVelocity1 = particle._currentVelocity2;
  56111. particle._currentVelocity2 = nextGradient.getFactor();
  56112. particle._currentVelocityGradient = currentGradient;
  56113. }
  56114. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  56115. });
  56116. }
  56117. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  56118. /// Limit velocity
  56119. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  56120. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  56121. if (currentGradient !== particle._currentLimitVelocityGradient) {
  56122. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  56123. particle._currentLimitVelocity2 = nextGradient.getFactor();
  56124. particle._currentLimitVelocityGradient = currentGradient;
  56125. }
  56126. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  56127. var currentVelocity = particle.direction.length();
  56128. if (currentVelocity > limitVelocity) {
  56129. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  56130. }
  56131. });
  56132. }
  56133. /// Drag
  56134. if (_this._dragGradients && _this._dragGradients.length > 0) {
  56135. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  56136. if (currentGradient !== particle._currentDragGradient) {
  56137. particle._currentDrag1 = particle._currentDrag2;
  56138. particle._currentDrag2 = nextGradient.getFactor();
  56139. particle._currentDragGradient = currentGradient;
  56140. }
  56141. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  56142. _this._scaledDirection.scaleInPlace(1.0 - drag);
  56143. });
  56144. }
  56145. particle.position.addInPlace(_this._scaledDirection);
  56146. // Noise
  56147. if (noiseTextureData && noiseTextureSize) {
  56148. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56149. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56150. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56151. var force = BABYLON.Tmp.Vector3[0];
  56152. var scaledForce = BABYLON.Tmp.Vector3[1];
  56153. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  56154. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  56155. particle.direction.addInPlace(scaledForce);
  56156. }
  56157. // Gravity
  56158. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56159. particle.direction.addInPlace(_this._scaledGravity);
  56160. // Size
  56161. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  56162. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  56163. if (currentGradient !== particle._currentSizeGradient) {
  56164. particle._currentSize1 = particle._currentSize2;
  56165. particle._currentSize2 = nextGradient.getFactor();
  56166. particle._currentSizeGradient = currentGradient;
  56167. }
  56168. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  56169. });
  56170. }
  56171. // Remap data
  56172. if (_this._useRampGradients) {
  56173. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  56174. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  56175. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  56176. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  56177. particle.remapData.x = min;
  56178. particle.remapData.y = max - min;
  56179. });
  56180. }
  56181. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  56182. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  56183. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  56184. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  56185. particle.remapData.z = min;
  56186. particle.remapData.w = max - min;
  56187. });
  56188. }
  56189. }
  56190. if (_this._isAnimationSheetEnabled) {
  56191. particle.updateCellIndex();
  56192. }
  56193. // Update the position of the attached sub-emitters to match their attached particle
  56194. if (particle._attachedSubEmitters && particle._attachedSubEmitters.length > 0) {
  56195. particle._attachedSubEmitters.forEach(function (subEmitter) {
  56196. ParticleSystem._InheritParticleInfoToSubEmitter(subEmitter, particle);
  56197. });
  56198. }
  56199. }
  56200. };
  56201. var particle;
  56202. for (var index = 0; index < particles.length; index++) {
  56203. _loop_1();
  56204. }
  56205. };
  56206. return _this;
  56207. }
  56208. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56209. /**
  56210. * Sets a callback that will be triggered when the system is disposed
  56211. */
  56212. set: function (callback) {
  56213. if (this._onDisposeObserver) {
  56214. this.onDisposeObservable.remove(this._onDisposeObserver);
  56215. }
  56216. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56217. },
  56218. enumerable: true,
  56219. configurable: true
  56220. });
  56221. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  56222. /** Gets or sets a boolean indicating that ramp gradients must be used
  56223. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  56224. */
  56225. get: function () {
  56226. return this._useRampGradients;
  56227. },
  56228. set: function (value) {
  56229. if (this._useRampGradients === value) {
  56230. return;
  56231. }
  56232. this._useRampGradients = value;
  56233. this._resetEffect();
  56234. },
  56235. enumerable: true,
  56236. configurable: true
  56237. });
  56238. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56239. //end of Sub-emitter
  56240. /**
  56241. * Gets the current list of active particles
  56242. */
  56243. get: function () {
  56244. return this._particles;
  56245. },
  56246. enumerable: true,
  56247. configurable: true
  56248. });
  56249. /**
  56250. * Returns the string "ParticleSystem"
  56251. * @returns a string containing the class name
  56252. */
  56253. ParticleSystem.prototype.getClassName = function () {
  56254. return "ParticleSystem";
  56255. };
  56256. ParticleSystem._InheritParticleInfoToSubEmitter = function (subEmitter, particle) {
  56257. if (subEmitter.particleSystem.emitter.position) {
  56258. var emitterMesh = subEmitter.particleSystem.emitter;
  56259. emitterMesh.position.copyFrom(particle.position);
  56260. if (subEmitter.inheritDirection) {
  56261. emitterMesh.position.subtractToRef(particle.direction, BABYLON.Tmp.Vector3[0]);
  56262. // Look at using Y as forward
  56263. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  56264. }
  56265. }
  56266. else {
  56267. var emitterPosition = subEmitter.particleSystem.emitter;
  56268. emitterPosition.copyFrom(particle.position);
  56269. }
  56270. // Set inheritedVelocityOffset to be used when new particles are created
  56271. particle.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  56272. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  56273. };
  56274. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  56275. var newGradient = new BABYLON.FactorGradient();
  56276. newGradient.gradient = gradient;
  56277. newGradient.factor1 = factor;
  56278. newGradient.factor2 = factor2;
  56279. factorGradients.push(newGradient);
  56280. factorGradients.sort(function (a, b) {
  56281. if (a.gradient < b.gradient) {
  56282. return -1;
  56283. }
  56284. else if (a.gradient > b.gradient) {
  56285. return 1;
  56286. }
  56287. return 0;
  56288. });
  56289. };
  56290. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  56291. if (!factorGradients) {
  56292. return;
  56293. }
  56294. var index = 0;
  56295. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  56296. var factorGradient = factorGradients_1[_i];
  56297. if (factorGradient.gradient === gradient) {
  56298. factorGradients.splice(index, 1);
  56299. break;
  56300. }
  56301. index++;
  56302. }
  56303. };
  56304. /**
  56305. * Adds a new life time gradient
  56306. * @param gradient defines the gradient to use (between 0 and 1)
  56307. * @param factor defines the life time factor to affect to the specified gradient
  56308. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56309. * @returns the current particle system
  56310. */
  56311. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  56312. if (!this._lifeTimeGradients) {
  56313. this._lifeTimeGradients = [];
  56314. }
  56315. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  56316. return this;
  56317. };
  56318. /**
  56319. * Remove a specific life time gradient
  56320. * @param gradient defines the gradient to remove
  56321. * @returns the current particle system
  56322. */
  56323. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  56324. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  56325. return this;
  56326. };
  56327. /**
  56328. * Adds a new size gradient
  56329. * @param gradient defines the gradient to use (between 0 and 1)
  56330. * @param factor defines the size factor to affect to the specified gradient
  56331. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56332. * @returns the current particle system
  56333. */
  56334. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  56335. if (!this._sizeGradients) {
  56336. this._sizeGradients = [];
  56337. }
  56338. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  56339. return this;
  56340. };
  56341. /**
  56342. * Remove a specific size gradient
  56343. * @param gradient defines the gradient to remove
  56344. * @returns the current particle system
  56345. */
  56346. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  56347. this._removeFactorGradient(this._sizeGradients, gradient);
  56348. return this;
  56349. };
  56350. /**
  56351. * Adds a new color remap gradient
  56352. * @param gradient defines the gradient to use (between 0 and 1)
  56353. * @param min defines the color remap minimal range
  56354. * @param max defines the color remap maximal range
  56355. * @returns the current particle system
  56356. */
  56357. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  56358. if (!this._colorRemapGradients) {
  56359. this._colorRemapGradients = [];
  56360. }
  56361. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  56362. return this;
  56363. };
  56364. /**
  56365. * Remove a specific color remap gradient
  56366. * @param gradient defines the gradient to remove
  56367. * @returns the current particle system
  56368. */
  56369. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  56370. this._removeFactorGradient(this._colorRemapGradients, gradient);
  56371. return this;
  56372. };
  56373. /**
  56374. * Adds a new alpha remap gradient
  56375. * @param gradient defines the gradient to use (between 0 and 1)
  56376. * @param min defines the alpha remap minimal range
  56377. * @param max defines the alpha remap maximal range
  56378. * @returns the current particle system
  56379. */
  56380. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  56381. if (!this._alphaRemapGradients) {
  56382. this._alphaRemapGradients = [];
  56383. }
  56384. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  56385. return this;
  56386. };
  56387. /**
  56388. * Remove a specific alpha remap gradient
  56389. * @param gradient defines the gradient to remove
  56390. * @returns the current particle system
  56391. */
  56392. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  56393. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  56394. return this;
  56395. };
  56396. /**
  56397. * Adds a new angular speed gradient
  56398. * @param gradient defines the gradient to use (between 0 and 1)
  56399. * @param factor defines the angular speed to affect to the specified gradient
  56400. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56401. * @returns the current particle system
  56402. */
  56403. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  56404. if (!this._angularSpeedGradients) {
  56405. this._angularSpeedGradients = [];
  56406. }
  56407. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  56408. return this;
  56409. };
  56410. /**
  56411. * Remove a specific angular speed gradient
  56412. * @param gradient defines the gradient to remove
  56413. * @returns the current particle system
  56414. */
  56415. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  56416. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  56417. return this;
  56418. };
  56419. /**
  56420. * Adds a new velocity gradient
  56421. * @param gradient defines the gradient to use (between 0 and 1)
  56422. * @param factor defines the velocity to affect to the specified gradient
  56423. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56424. * @returns the current particle system
  56425. */
  56426. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  56427. if (!this._velocityGradients) {
  56428. this._velocityGradients = [];
  56429. }
  56430. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  56431. return this;
  56432. };
  56433. /**
  56434. * Remove a specific velocity gradient
  56435. * @param gradient defines the gradient to remove
  56436. * @returns the current particle system
  56437. */
  56438. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  56439. this._removeFactorGradient(this._velocityGradients, gradient);
  56440. return this;
  56441. };
  56442. /**
  56443. * Adds a new limit velocity gradient
  56444. * @param gradient defines the gradient to use (between 0 and 1)
  56445. * @param factor defines the limit velocity value to affect to the specified gradient
  56446. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56447. * @returns the current particle system
  56448. */
  56449. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  56450. if (!this._limitVelocityGradients) {
  56451. this._limitVelocityGradients = [];
  56452. }
  56453. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  56454. return this;
  56455. };
  56456. /**
  56457. * Remove a specific limit velocity gradient
  56458. * @param gradient defines the gradient to remove
  56459. * @returns the current particle system
  56460. */
  56461. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  56462. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  56463. return this;
  56464. };
  56465. /**
  56466. * Adds a new drag gradient
  56467. * @param gradient defines the gradient to use (between 0 and 1)
  56468. * @param factor defines the drag value to affect to the specified gradient
  56469. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56470. * @returns the current particle system
  56471. */
  56472. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  56473. if (!this._dragGradients) {
  56474. this._dragGradients = [];
  56475. }
  56476. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  56477. return this;
  56478. };
  56479. /**
  56480. * Remove a specific drag gradient
  56481. * @param gradient defines the gradient to remove
  56482. * @returns the current particle system
  56483. */
  56484. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  56485. this._removeFactorGradient(this._dragGradients, gradient);
  56486. return this;
  56487. };
  56488. /**
  56489. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  56490. * @param gradient defines the gradient to use (between 0 and 1)
  56491. * @param factor defines the emit rate value to affect to the specified gradient
  56492. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56493. * @returns the current particle system
  56494. */
  56495. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  56496. if (!this._emitRateGradients) {
  56497. this._emitRateGradients = [];
  56498. }
  56499. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  56500. if (!this._currentEmitRateGradient) {
  56501. this._currentEmitRateGradient = this._emitRateGradients[0];
  56502. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  56503. this._currentEmitRate2 = this._currentEmitRate1;
  56504. }
  56505. if (this._emitRateGradients.length === 2) {
  56506. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  56507. }
  56508. return this;
  56509. };
  56510. /**
  56511. * Remove a specific emit rate gradient
  56512. * @param gradient defines the gradient to remove
  56513. * @returns the current particle system
  56514. */
  56515. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  56516. this._removeFactorGradient(this._emitRateGradients, gradient);
  56517. return this;
  56518. };
  56519. /**
  56520. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  56521. * @param gradient defines the gradient to use (between 0 and 1)
  56522. * @param factor defines the start size value to affect to the specified gradient
  56523. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56524. * @returns the current particle system
  56525. */
  56526. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  56527. if (!this._startSizeGradients) {
  56528. this._startSizeGradients = [];
  56529. }
  56530. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  56531. if (!this._currentStartSizeGradient) {
  56532. this._currentStartSizeGradient = this._startSizeGradients[0];
  56533. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  56534. this._currentStartSize2 = this._currentStartSize1;
  56535. }
  56536. if (this._startSizeGradients.length === 2) {
  56537. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  56538. }
  56539. return this;
  56540. };
  56541. /**
  56542. * Remove a specific start size gradient
  56543. * @param gradient defines the gradient to remove
  56544. * @returns the current particle system
  56545. */
  56546. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  56547. this._removeFactorGradient(this._emitRateGradients, gradient);
  56548. return this;
  56549. };
  56550. ParticleSystem.prototype._createRampGradientTexture = function () {
  56551. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  56552. return;
  56553. }
  56554. var data = new Uint8Array(this._rawTextureWidth * 4);
  56555. var tmpColor = BABYLON.Tmp.Color3[0];
  56556. for (var x = 0; x < this._rawTextureWidth; x++) {
  56557. var ratio = x / this._rawTextureWidth;
  56558. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  56559. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  56560. data[x * 4] = tmpColor.r * 255;
  56561. data[x * 4 + 1] = tmpColor.g * 255;
  56562. data[x * 4 + 2] = tmpColor.b * 255;
  56563. data[x * 4 + 3] = 255;
  56564. });
  56565. }
  56566. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  56567. };
  56568. /**
  56569. * Gets the current list of ramp gradients.
  56570. * You must use addRampGradient and removeRampGradient to udpate this list
  56571. * @returns the list of ramp gradients
  56572. */
  56573. ParticleSystem.prototype.getRampGradients = function () {
  56574. return this._rampGradients;
  56575. };
  56576. /**
  56577. * Adds a new ramp gradient used to remap particle colors
  56578. * @param gradient defines the gradient to use (between 0 and 1)
  56579. * @param color defines the color to affect to the specified gradient
  56580. * @returns the current particle system
  56581. */
  56582. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  56583. if (!this._rampGradients) {
  56584. this._rampGradients = [];
  56585. }
  56586. var rampGradient = new BABYLON.Color3Gradient();
  56587. rampGradient.gradient = gradient;
  56588. rampGradient.color = color;
  56589. this._rampGradients.push(rampGradient);
  56590. this._rampGradients.sort(function (a, b) {
  56591. if (a.gradient < b.gradient) {
  56592. return -1;
  56593. }
  56594. else if (a.gradient > b.gradient) {
  56595. return 1;
  56596. }
  56597. return 0;
  56598. });
  56599. if (this._rampGradientsTexture) {
  56600. this._rampGradientsTexture.dispose();
  56601. this._rampGradientsTexture = null;
  56602. }
  56603. this._createRampGradientTexture();
  56604. return this;
  56605. };
  56606. /**
  56607. * Remove a specific ramp gradient
  56608. * @param gradient defines the gradient to remove
  56609. * @returns the current particle system
  56610. */
  56611. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  56612. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  56613. this._rampGradientsTexture = null;
  56614. if (this._rampGradients && this._rampGradients.length > 0) {
  56615. this._createRampGradientTexture();
  56616. }
  56617. return this;
  56618. };
  56619. /**
  56620. * Adds a new color gradient
  56621. * @param gradient defines the gradient to use (between 0 and 1)
  56622. * @param color defines the color to affect to the specified gradient
  56623. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  56624. */
  56625. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  56626. if (!this._colorGradients) {
  56627. this._colorGradients = [];
  56628. }
  56629. var colorGradient = new BABYLON.ColorGradient();
  56630. colorGradient.gradient = gradient;
  56631. colorGradient.color1 = color;
  56632. colorGradient.color2 = color2;
  56633. this._colorGradients.push(colorGradient);
  56634. this._colorGradients.sort(function (a, b) {
  56635. if (a.gradient < b.gradient) {
  56636. return -1;
  56637. }
  56638. else if (a.gradient > b.gradient) {
  56639. return 1;
  56640. }
  56641. return 0;
  56642. });
  56643. return this;
  56644. };
  56645. /**
  56646. * Remove a specific color gradient
  56647. * @param gradient defines the gradient to remove
  56648. */
  56649. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  56650. if (!this._colorGradients) {
  56651. return this;
  56652. }
  56653. var index = 0;
  56654. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  56655. var colorGradient = _a[_i];
  56656. if (colorGradient.gradient === gradient) {
  56657. this._colorGradients.splice(index, 1);
  56658. break;
  56659. }
  56660. index++;
  56661. }
  56662. return this;
  56663. };
  56664. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  56665. u = Math.abs(u) * 0.5 + 0.5;
  56666. v = Math.abs(v) * 0.5 + 0.5;
  56667. var wrappedU = ((u * width) % width) | 0;
  56668. var wrappedV = ((v * height) % height) | 0;
  56669. var position = (wrappedU + wrappedV * width) * 4;
  56670. return pixels[position] / 255;
  56671. };
  56672. ParticleSystem.prototype._reset = function () {
  56673. this._resetEffect();
  56674. };
  56675. ParticleSystem.prototype._resetEffect = function () {
  56676. if (this._vertexBuffer) {
  56677. this._vertexBuffer.dispose();
  56678. this._vertexBuffer = null;
  56679. }
  56680. if (this._spriteBuffer) {
  56681. this._spriteBuffer.dispose();
  56682. this._spriteBuffer = null;
  56683. }
  56684. this._createVertexBuffers();
  56685. };
  56686. ParticleSystem.prototype._createVertexBuffers = function () {
  56687. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  56688. if (this._isAnimationSheetEnabled) {
  56689. this._vertexBufferSize += 1;
  56690. }
  56691. if (!this._isBillboardBased) {
  56692. this._vertexBufferSize += 3;
  56693. }
  56694. if (this._useRampGradients) {
  56695. this._vertexBufferSize += 4;
  56696. }
  56697. var engine = this._scene.getEngine();
  56698. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  56699. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  56700. var dataOffset = 0;
  56701. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56702. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56703. dataOffset += 3;
  56704. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56705. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56706. dataOffset += 4;
  56707. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56708. this._vertexBuffers["angle"] = options;
  56709. dataOffset += 1;
  56710. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56711. this._vertexBuffers["size"] = size;
  56712. dataOffset += 2;
  56713. if (this._isAnimationSheetEnabled) {
  56714. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56715. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56716. dataOffset += 1;
  56717. }
  56718. if (!this._isBillboardBased) {
  56719. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56720. this._vertexBuffers["direction"] = directionBuffer;
  56721. dataOffset += 3;
  56722. }
  56723. if (this._useRampGradients) {
  56724. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56725. this._vertexBuffers["remapData"] = rampDataBuffer;
  56726. dataOffset += 4;
  56727. }
  56728. var offsets;
  56729. if (this._useInstancing) {
  56730. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  56731. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  56732. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  56733. }
  56734. else {
  56735. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56736. dataOffset += 2;
  56737. }
  56738. this._vertexBuffers["offset"] = offsets;
  56739. };
  56740. ParticleSystem.prototype._createIndexBuffer = function () {
  56741. if (this._useInstancing) {
  56742. return;
  56743. }
  56744. var indices = [];
  56745. var index = 0;
  56746. for (var count = 0; count < this._capacity; count++) {
  56747. indices.push(index);
  56748. indices.push(index + 1);
  56749. indices.push(index + 2);
  56750. indices.push(index);
  56751. indices.push(index + 2);
  56752. indices.push(index + 3);
  56753. index += 4;
  56754. }
  56755. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56756. };
  56757. /**
  56758. * Gets the maximum number of particles active at the same time.
  56759. * @returns The max number of active particles.
  56760. */
  56761. ParticleSystem.prototype.getCapacity = function () {
  56762. return this._capacity;
  56763. };
  56764. /**
  56765. * Gets whether there are still active particles in the system.
  56766. * @returns True if it is alive, otherwise false.
  56767. */
  56768. ParticleSystem.prototype.isAlive = function () {
  56769. return this._alive;
  56770. };
  56771. /**
  56772. * Gets if the system has been started. (Note: this will still be true after stop is called)
  56773. * @returns True if it has been started, otherwise false.
  56774. */
  56775. ParticleSystem.prototype.isStarted = function () {
  56776. return this._started;
  56777. };
  56778. /**
  56779. * Starts the particle system and begins to emit
  56780. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  56781. */
  56782. ParticleSystem.prototype.start = function (delay) {
  56783. var _this = this;
  56784. if (delay === void 0) { delay = this.startDelay; }
  56785. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  56786. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  56787. }
  56788. if (delay) {
  56789. setTimeout(function () {
  56790. _this.start(0);
  56791. }, delay);
  56792. return;
  56793. }
  56794. // Convert the subEmitters field to the constant type field _subEmitters
  56795. this._subEmitters = new Array();
  56796. if (this.subEmitters) {
  56797. this.subEmitters.forEach(function (subEmitter) {
  56798. if (subEmitter instanceof ParticleSystem) {
  56799. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  56800. }
  56801. else if (subEmitter instanceof BABYLON.SubEmitter) {
  56802. _this._subEmitters.push([subEmitter]);
  56803. }
  56804. else if (subEmitter instanceof Array) {
  56805. _this._subEmitters.push(subEmitter);
  56806. }
  56807. _this._subEmitters[_this._subEmitters.length - 1].forEach(function (se) {
  56808. if (!(se.particleSystem.emitter instanceof BABYLON.AbstractMesh) && se.inheritDirection) {
  56809. BABYLON.Tools.Warn("subEmitter.inheritDirection is not supported with non-mesh emitter type");
  56810. }
  56811. });
  56812. });
  56813. }
  56814. this._started = true;
  56815. this._stopped = false;
  56816. this._actualFrame = 0;
  56817. if (this._subEmitters && this._subEmitters.length != 0) {
  56818. this.activeSubSystems = new Array();
  56819. }
  56820. if (this.preWarmCycles) {
  56821. var noiseTextureAsProcedural_1 = this.noiseTexture;
  56822. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  56823. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  56824. setTimeout(function () {
  56825. for (var index = 0; index < _this.preWarmCycles; index++) {
  56826. _this.animate(true);
  56827. noiseTextureAsProcedural_1.render();
  56828. }
  56829. });
  56830. });
  56831. }
  56832. else {
  56833. for (var index = 0; index < this.preWarmCycles; index++) {
  56834. this.animate(true);
  56835. }
  56836. }
  56837. }
  56838. };
  56839. /**
  56840. * Stops the particle system.
  56841. * @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.
  56842. */
  56843. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56844. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56845. this._stopped = true;
  56846. if (stopSubEmitters) {
  56847. this._stopSubEmitters();
  56848. }
  56849. };
  56850. // animation sheet
  56851. /**
  56852. * Remove all active particles
  56853. */
  56854. ParticleSystem.prototype.reset = function () {
  56855. this._stockParticles = [];
  56856. this._particles = [];
  56857. };
  56858. /**
  56859. * @hidden (for internal use only)
  56860. */
  56861. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56862. var offset = index * this._vertexBufferSize;
  56863. this._vertexData[offset++] = particle.position.x;
  56864. this._vertexData[offset++] = particle.position.y;
  56865. this._vertexData[offset++] = particle.position.z;
  56866. this._vertexData[offset++] = particle.color.r;
  56867. this._vertexData[offset++] = particle.color.g;
  56868. this._vertexData[offset++] = particle.color.b;
  56869. this._vertexData[offset++] = particle.color.a;
  56870. this._vertexData[offset++] = particle.angle;
  56871. this._vertexData[offset++] = particle.scale.x * particle.size;
  56872. this._vertexData[offset++] = particle.scale.y * particle.size;
  56873. if (this._isAnimationSheetEnabled) {
  56874. this._vertexData[offset++] = particle.cellIndex;
  56875. }
  56876. if (!this._isBillboardBased) {
  56877. if (particle._initialDirection) {
  56878. this._vertexData[offset++] = particle._initialDirection.x;
  56879. this._vertexData[offset++] = particle._initialDirection.y;
  56880. this._vertexData[offset++] = particle._initialDirection.z;
  56881. }
  56882. else {
  56883. this._vertexData[offset++] = particle.direction.x;
  56884. this._vertexData[offset++] = particle.direction.y;
  56885. this._vertexData[offset++] = particle.direction.z;
  56886. }
  56887. }
  56888. if (this._useRampGradients) {
  56889. this._vertexData[offset++] = particle.remapData.x;
  56890. this._vertexData[offset++] = particle.remapData.y;
  56891. this._vertexData[offset++] = particle.remapData.z;
  56892. this._vertexData[offset++] = particle.remapData.w;
  56893. }
  56894. if (!this._useInstancing) {
  56895. if (this._isAnimationSheetEnabled) {
  56896. if (offsetX === 0)
  56897. offsetX = this._epsilon;
  56898. else if (offsetX === 1)
  56899. offsetX = 1 - this._epsilon;
  56900. if (offsetY === 0)
  56901. offsetY = this._epsilon;
  56902. else if (offsetY === 1)
  56903. offsetY = 1 - this._epsilon;
  56904. }
  56905. this._vertexData[offset++] = offsetX;
  56906. this._vertexData[offset++] = offsetY;
  56907. }
  56908. };
  56909. ParticleSystem.prototype._stopSubEmitters = function () {
  56910. if (!this.activeSubSystems) {
  56911. return;
  56912. }
  56913. this.activeSubSystems.forEach(function (subSystem) {
  56914. subSystem.stop(true);
  56915. });
  56916. this.activeSubSystems = new Array();
  56917. };
  56918. ParticleSystem.prototype._removeFromRoot = function () {
  56919. if (!this._rootParticleSystem) {
  56920. return;
  56921. }
  56922. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56923. if (index !== -1) {
  56924. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56925. }
  56926. };
  56927. // End of sub system methods
  56928. ParticleSystem.prototype._update = function (newParticles) {
  56929. var _this = this;
  56930. // Update current
  56931. this._alive = this._particles.length > 0;
  56932. if (this.emitter.position) {
  56933. var emitterMesh = this.emitter;
  56934. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  56935. }
  56936. else {
  56937. var emitterPosition = this.emitter;
  56938. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56939. }
  56940. this.updateFunction(this._particles);
  56941. // Add new ones
  56942. var particle;
  56943. var _loop_2 = function () {
  56944. if (this_1._particles.length === this_1._capacity) {
  56945. return "break";
  56946. }
  56947. particle = this_1._createParticle();
  56948. this_1._particles.push(particle);
  56949. // Emitter
  56950. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  56951. if (this_1.startPositionFunction) {
  56952. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56953. }
  56954. else {
  56955. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56956. }
  56957. if (this_1.startDirectionFunction) {
  56958. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56959. }
  56960. else {
  56961. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56962. }
  56963. if (emitPower === 0) {
  56964. if (!particle._initialDirection) {
  56965. particle._initialDirection = particle.direction.clone();
  56966. }
  56967. else {
  56968. particle._initialDirection.copyFrom(particle.direction);
  56969. }
  56970. }
  56971. else {
  56972. particle._initialDirection = null;
  56973. }
  56974. particle.direction.scaleInPlace(emitPower);
  56975. // Life time
  56976. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  56977. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  56978. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  56979. var factorGradient1 = currentGradient;
  56980. var factorGradient2 = nextGradient;
  56981. var lifeTime1 = factorGradient1.getFactor();
  56982. var lifeTime2 = factorGradient2.getFactor();
  56983. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  56984. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  56985. });
  56986. }
  56987. else {
  56988. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  56989. }
  56990. // Size
  56991. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  56992. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  56993. }
  56994. else {
  56995. particle._currentSizeGradient = this_1._sizeGradients[0];
  56996. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  56997. particle.size = particle._currentSize1;
  56998. if (this_1._sizeGradients.length > 1) {
  56999. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  57000. }
  57001. else {
  57002. particle._currentSize2 = particle._currentSize1;
  57003. }
  57004. }
  57005. // Size and scale
  57006. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  57007. // Adjust scale by start size
  57008. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  57009. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  57010. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  57011. if (currentGradient !== _this._currentStartSizeGradient) {
  57012. _this._currentStartSize1 = _this._currentStartSize2;
  57013. _this._currentStartSize2 = nextGradient.getFactor();
  57014. _this._currentStartSizeGradient = currentGradient;
  57015. }
  57016. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  57017. particle.scale.scaleInPlace(value);
  57018. });
  57019. }
  57020. // Angle
  57021. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  57022. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  57023. }
  57024. else {
  57025. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  57026. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  57027. particle._currentAngularSpeed1 = particle.angularSpeed;
  57028. if (this_1._angularSpeedGradients.length > 1) {
  57029. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  57030. }
  57031. else {
  57032. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  57033. }
  57034. }
  57035. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  57036. // Velocity
  57037. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  57038. particle._currentVelocityGradient = this_1._velocityGradients[0];
  57039. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  57040. if (this_1._velocityGradients.length > 1) {
  57041. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  57042. }
  57043. else {
  57044. particle._currentVelocity2 = particle._currentVelocity1;
  57045. }
  57046. }
  57047. // Limit velocity
  57048. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  57049. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  57050. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  57051. if (this_1._limitVelocityGradients.length > 1) {
  57052. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  57053. }
  57054. else {
  57055. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  57056. }
  57057. }
  57058. // Drag
  57059. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  57060. particle._currentDragGradient = this_1._dragGradients[0];
  57061. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  57062. if (this_1._dragGradients.length > 1) {
  57063. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  57064. }
  57065. else {
  57066. particle._currentDrag2 = particle._currentDrag1;
  57067. }
  57068. }
  57069. // Color
  57070. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  57071. step = BABYLON.Scalar.RandomRange(0, 1.0);
  57072. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  57073. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  57074. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  57075. }
  57076. else {
  57077. particle._currentColorGradient = this_1._colorGradients[0];
  57078. particle._currentColorGradient.getColorToRef(particle.color);
  57079. particle._currentColor1.copyFrom(particle.color);
  57080. if (this_1._colorGradients.length > 1) {
  57081. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  57082. }
  57083. else {
  57084. particle._currentColor2.copyFrom(particle.color);
  57085. }
  57086. }
  57087. // Sheet
  57088. if (this_1._isAnimationSheetEnabled) {
  57089. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  57090. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  57091. }
  57092. // Inherited Velocity
  57093. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  57094. // Ramp
  57095. if (this_1._useRampGradients) {
  57096. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  57097. }
  57098. // Noise texture coordinates
  57099. if (this_1.noiseTexture) {
  57100. if (particle._randomNoiseCoordinates1) {
  57101. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  57102. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  57103. }
  57104. else {
  57105. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  57106. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  57107. }
  57108. }
  57109. };
  57110. var this_1 = this, step;
  57111. for (var index = 0; index < newParticles; index++) {
  57112. var state_1 = _loop_2();
  57113. if (state_1 === "break")
  57114. break;
  57115. }
  57116. };
  57117. /** @hidden */
  57118. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  57119. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57120. if (isBillboardBased === void 0) { isBillboardBased = false; }
  57121. if (useRampGradients === void 0) { useRampGradients = false; }
  57122. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  57123. if (isAnimationSheetEnabled) {
  57124. attributeNamesOrOptions.push("cellIndex");
  57125. }
  57126. if (!isBillboardBased) {
  57127. attributeNamesOrOptions.push("direction");
  57128. }
  57129. if (useRampGradients) {
  57130. attributeNamesOrOptions.push("remapData");
  57131. }
  57132. return attributeNamesOrOptions;
  57133. };
  57134. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  57135. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57136. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  57137. if (isAnimationSheetEnabled) {
  57138. effectCreationOption.push("particlesInfos");
  57139. }
  57140. return effectCreationOption;
  57141. };
  57142. ParticleSystem.prototype._getEffect = function (blendMode) {
  57143. if (this._customEffect) {
  57144. return this._customEffect;
  57145. }
  57146. ;
  57147. var defines = [];
  57148. if (this._scene.clipPlane) {
  57149. defines.push("#define CLIPPLANE");
  57150. }
  57151. if (this._scene.clipPlane2) {
  57152. defines.push("#define CLIPPLANE2");
  57153. }
  57154. if (this._scene.clipPlane3) {
  57155. defines.push("#define CLIPPLANE3");
  57156. }
  57157. if (this._scene.clipPlane4) {
  57158. defines.push("#define CLIPPLANE4");
  57159. }
  57160. if (this._isAnimationSheetEnabled) {
  57161. defines.push("#define ANIMATESHEET");
  57162. }
  57163. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  57164. defines.push("#define BLENDMULTIPLYMODE");
  57165. }
  57166. if (this._useRampGradients) {
  57167. defines.push("#define RAMPGRADIENT");
  57168. }
  57169. if (this._isBillboardBased) {
  57170. defines.push("#define BILLBOARD");
  57171. switch (this.billboardMode) {
  57172. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57173. defines.push("#define BILLBOARDY");
  57174. break;
  57175. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57176. default:
  57177. break;
  57178. }
  57179. }
  57180. if (this._imageProcessingConfiguration) {
  57181. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  57182. defines.push(this._imageProcessingConfigurationDefines.toString());
  57183. }
  57184. // Effect
  57185. var join = defines.join("\n");
  57186. if (this._cachedDefines !== join) {
  57187. this._cachedDefines = join;
  57188. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased, this._useRampGradients);
  57189. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  57190. var samplers = ["diffuseSampler", "rampSampler"];
  57191. if (BABYLON.ImageProcessingConfiguration) {
  57192. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  57193. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  57194. }
  57195. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  57196. }
  57197. return this._effect;
  57198. };
  57199. /**
  57200. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57201. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  57202. */
  57203. ParticleSystem.prototype.animate = function (preWarmOnly) {
  57204. var _this = this;
  57205. if (preWarmOnly === void 0) { preWarmOnly = false; }
  57206. if (!this._started)
  57207. return;
  57208. if (!preWarmOnly) {
  57209. // Check
  57210. if (!this.isReady())
  57211. return;
  57212. if (this._currentRenderId === this._scene.getRenderId()) {
  57213. return;
  57214. }
  57215. this._currentRenderId = this._scene.getRenderId();
  57216. }
  57217. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57218. // Determine the number of particles we need to create
  57219. var newParticles;
  57220. if (this.manualEmitCount > -1) {
  57221. newParticles = this.manualEmitCount;
  57222. this._newPartsExcess = 0;
  57223. this.manualEmitCount = 0;
  57224. }
  57225. else {
  57226. var rate_1 = this.emitRate;
  57227. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  57228. var ratio = this._actualFrame / this.targetStopDuration;
  57229. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  57230. if (currentGradient !== _this._currentEmitRateGradient) {
  57231. _this._currentEmitRate1 = _this._currentEmitRate2;
  57232. _this._currentEmitRate2 = nextGradient.getFactor();
  57233. _this._currentEmitRateGradient = currentGradient;
  57234. }
  57235. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  57236. });
  57237. }
  57238. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  57239. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  57240. }
  57241. if (this._newPartsExcess > 1.0) {
  57242. newParticles += this._newPartsExcess >> 0;
  57243. this._newPartsExcess -= this._newPartsExcess >> 0;
  57244. }
  57245. this._alive = false;
  57246. if (!this._stopped) {
  57247. this._actualFrame += this._scaledUpdateSpeed;
  57248. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  57249. this.stop();
  57250. }
  57251. else {
  57252. newParticles = 0;
  57253. }
  57254. this._update(newParticles);
  57255. // Stopped?
  57256. if (this._stopped) {
  57257. if (!this._alive) {
  57258. this._started = false;
  57259. if (this.onAnimationEnd) {
  57260. this.onAnimationEnd();
  57261. }
  57262. if (this.disposeOnStop) {
  57263. this._scene._toBeDisposed.push(this);
  57264. }
  57265. }
  57266. }
  57267. if (!preWarmOnly) {
  57268. // Update VBO
  57269. var offset = 0;
  57270. for (var index = 0; index < this._particles.length; index++) {
  57271. var particle = this._particles[index];
  57272. this._appendParticleVertices(offset, particle);
  57273. offset += this._useInstancing ? 1 : 4;
  57274. }
  57275. if (this._vertexBuffer) {
  57276. this._vertexBuffer.update(this._vertexData);
  57277. }
  57278. }
  57279. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  57280. this.stop();
  57281. }
  57282. };
  57283. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  57284. this._appendParticleVertex(offset++, particle, 0, 0);
  57285. if (!this._useInstancing) {
  57286. this._appendParticleVertex(offset++, particle, 1, 0);
  57287. this._appendParticleVertex(offset++, particle, 1, 1);
  57288. this._appendParticleVertex(offset++, particle, 0, 1);
  57289. }
  57290. };
  57291. /**
  57292. * Rebuilds the particle system.
  57293. */
  57294. ParticleSystem.prototype.rebuild = function () {
  57295. this._createIndexBuffer();
  57296. if (this._vertexBuffer) {
  57297. this._vertexBuffer._rebuild();
  57298. }
  57299. };
  57300. /**
  57301. * Is this system ready to be used/rendered
  57302. * @return true if the system is ready
  57303. */
  57304. ParticleSystem.prototype.isReady = function () {
  57305. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57306. return false;
  57307. }
  57308. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  57309. if (!this._getEffect(this.blendMode).isReady()) {
  57310. return false;
  57311. }
  57312. }
  57313. else {
  57314. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  57315. return false;
  57316. }
  57317. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  57318. return false;
  57319. }
  57320. }
  57321. return true;
  57322. };
  57323. ParticleSystem.prototype._render = function (blendMode) {
  57324. var effect = this._getEffect(blendMode);
  57325. var engine = this._scene.getEngine();
  57326. // Render
  57327. engine.enableEffect(effect);
  57328. var viewMatrix = this._scene.getViewMatrix();
  57329. effect.setTexture("diffuseSampler", this.particleTexture);
  57330. effect.setMatrix("view", viewMatrix);
  57331. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  57332. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57333. var baseSize = this.particleTexture.getBaseSize();
  57334. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57335. }
  57336. effect.setVector2("translationPivot", this.translationPivot);
  57337. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  57338. if (this._isBillboardBased) {
  57339. var camera = this._scene.activeCamera;
  57340. effect.setVector3("eyePosition", camera.globalPosition);
  57341. }
  57342. if (this._rampGradientsTexture) {
  57343. effect.setTexture("rampSampler", this._rampGradientsTexture);
  57344. }
  57345. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  57346. var invView = viewMatrix.clone();
  57347. invView.invert();
  57348. effect.setMatrix("invView", invView);
  57349. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  57350. }
  57351. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57352. // image processing
  57353. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  57354. this._imageProcessingConfiguration.bind(effect);
  57355. }
  57356. // Draw order
  57357. switch (blendMode) {
  57358. case ParticleSystem.BLENDMODE_ADD:
  57359. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57360. break;
  57361. case ParticleSystem.BLENDMODE_ONEONE:
  57362. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57363. break;
  57364. case ParticleSystem.BLENDMODE_STANDARD:
  57365. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57366. break;
  57367. case ParticleSystem.BLENDMODE_MULTIPLY:
  57368. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  57369. break;
  57370. }
  57371. if (this._useInstancing) {
  57372. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  57373. }
  57374. else {
  57375. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  57376. }
  57377. return this._particles.length;
  57378. };
  57379. /**
  57380. * Renders the particle system in its current state.
  57381. * @returns the current number of particles
  57382. */
  57383. ParticleSystem.prototype.render = function () {
  57384. // Check
  57385. if (!this.isReady() || !this._particles.length) {
  57386. return 0;
  57387. }
  57388. var engine = this._scene.getEngine();
  57389. engine.setState(false);
  57390. if (this.forceDepthWrite) {
  57391. engine.setDepthWrite(true);
  57392. }
  57393. var outparticles = 0;
  57394. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  57395. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  57396. }
  57397. outparticles = this._render(this.blendMode);
  57398. engine.unbindInstanceAttributes();
  57399. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57400. return outparticles;
  57401. };
  57402. /**
  57403. * Disposes the particle system and free the associated resources
  57404. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57405. */
  57406. ParticleSystem.prototype.dispose = function (disposeTexture) {
  57407. if (disposeTexture === void 0) { disposeTexture = true; }
  57408. if (this._vertexBuffer) {
  57409. this._vertexBuffer.dispose();
  57410. this._vertexBuffer = null;
  57411. }
  57412. if (this._spriteBuffer) {
  57413. this._spriteBuffer.dispose();
  57414. this._spriteBuffer = null;
  57415. }
  57416. if (this._indexBuffer) {
  57417. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57418. this._indexBuffer = null;
  57419. }
  57420. if (disposeTexture && this.particleTexture) {
  57421. this.particleTexture.dispose();
  57422. this.particleTexture = null;
  57423. }
  57424. if (disposeTexture && this.noiseTexture) {
  57425. this.noiseTexture.dispose();
  57426. this.noiseTexture = null;
  57427. }
  57428. if (this._rampGradientsTexture) {
  57429. this._rampGradientsTexture.dispose();
  57430. this._rampGradientsTexture = null;
  57431. }
  57432. this._removeFromRoot();
  57433. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  57434. this.emitter.dispose(true);
  57435. }
  57436. // Remove from scene
  57437. var index = this._scene.particleSystems.indexOf(this);
  57438. if (index > -1) {
  57439. this._scene.particleSystems.splice(index, 1);
  57440. }
  57441. // Callback
  57442. this.onDisposeObservable.notifyObservers(this);
  57443. this.onDisposeObservable.clear();
  57444. };
  57445. // Clone
  57446. /**
  57447. * Clones the particle system.
  57448. * @param name The name of the cloned object
  57449. * @param newEmitter The new emitter to use
  57450. * @returns the cloned particle system
  57451. */
  57452. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57453. var custom = null;
  57454. var program = null;
  57455. if (this.customShader != null) {
  57456. program = this.customShader;
  57457. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57458. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57459. }
  57460. else if (this._customEffect) {
  57461. custom = this._customEffect;
  57462. }
  57463. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57464. result.customShader = program;
  57465. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  57466. if (newEmitter === undefined) {
  57467. newEmitter = this.emitter;
  57468. }
  57469. result.noiseTexture = this.noiseTexture;
  57470. result.emitter = newEmitter;
  57471. if (this.particleTexture) {
  57472. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57473. }
  57474. // Clone gradients
  57475. if (this._colorGradients) {
  57476. this._colorGradients.forEach(function (v) {
  57477. result.addColorGradient(v.gradient, v.color1, v.color2);
  57478. });
  57479. }
  57480. if (this._dragGradients) {
  57481. this._dragGradients.forEach(function (v) {
  57482. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  57483. });
  57484. }
  57485. if (this._angularSpeedGradients) {
  57486. this._angularSpeedGradients.forEach(function (v) {
  57487. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  57488. });
  57489. }
  57490. if (this._emitRateGradients) {
  57491. this._emitRateGradients.forEach(function (v) {
  57492. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  57493. });
  57494. }
  57495. if (this._lifeTimeGradients) {
  57496. this._lifeTimeGradients.forEach(function (v) {
  57497. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  57498. });
  57499. }
  57500. if (this._limitVelocityGradients) {
  57501. this._limitVelocityGradients.forEach(function (v) {
  57502. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  57503. });
  57504. }
  57505. if (this._sizeGradients) {
  57506. this._sizeGradients.forEach(function (v) {
  57507. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  57508. });
  57509. }
  57510. if (this._startSizeGradients) {
  57511. this._startSizeGradients.forEach(function (v) {
  57512. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  57513. });
  57514. }
  57515. if (this._velocityGradients) {
  57516. this._velocityGradients.forEach(function (v) {
  57517. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  57518. });
  57519. }
  57520. if (this._rampGradients) {
  57521. this._rampGradients.forEach(function (v) {
  57522. result.addRampGradient(v.gradient, v.color);
  57523. });
  57524. }
  57525. if (this._colorRemapGradients) {
  57526. this._colorRemapGradients.forEach(function (v) {
  57527. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  57528. });
  57529. }
  57530. if (this._alphaRemapGradients) {
  57531. this._alphaRemapGradients.forEach(function (v) {
  57532. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  57533. });
  57534. }
  57535. if (!this.preventAutoStart) {
  57536. result.start();
  57537. }
  57538. return result;
  57539. };
  57540. /**
  57541. * Serializes the particle system to a JSON object.
  57542. * @returns the JSON object
  57543. */
  57544. ParticleSystem.prototype.serialize = function () {
  57545. var serializationObject = {};
  57546. ParticleSystem._Serialize(serializationObject, this);
  57547. serializationObject.textureMask = this.textureMask.asArray();
  57548. serializationObject.customShader = this.customShader;
  57549. serializationObject.preventAutoStart = this.preventAutoStart;
  57550. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57551. return serializationObject;
  57552. };
  57553. /** @hidden */
  57554. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  57555. serializationObject.name = particleSystem.name;
  57556. serializationObject.id = particleSystem.id;
  57557. serializationObject.capacity = particleSystem.getCapacity();
  57558. // Emitter
  57559. if (particleSystem.emitter.position) {
  57560. var emitterMesh = particleSystem.emitter;
  57561. serializationObject.emitterId = emitterMesh.id;
  57562. }
  57563. else {
  57564. var emitterPosition = particleSystem.emitter;
  57565. serializationObject.emitter = emitterPosition.asArray();
  57566. }
  57567. // Emitter
  57568. if (particleSystem.particleEmitterType) {
  57569. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  57570. }
  57571. if (particleSystem.particleTexture) {
  57572. serializationObject.textureName = particleSystem.particleTexture.name;
  57573. }
  57574. // Animations
  57575. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  57576. // Particle system
  57577. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  57578. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  57579. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  57580. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  57581. serializationObject.minSize = particleSystem.minSize;
  57582. serializationObject.maxSize = particleSystem.maxSize;
  57583. serializationObject.minScaleX = particleSystem.minScaleX;
  57584. serializationObject.maxScaleX = particleSystem.maxScaleX;
  57585. serializationObject.minScaleY = particleSystem.minScaleY;
  57586. serializationObject.maxScaleY = particleSystem.maxScaleY;
  57587. serializationObject.minEmitPower = particleSystem.minEmitPower;
  57588. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  57589. serializationObject.minLifeTime = particleSystem.minLifeTime;
  57590. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  57591. serializationObject.emitRate = particleSystem.emitRate;
  57592. serializationObject.gravity = particleSystem.gravity.asArray();
  57593. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  57594. serializationObject.color1 = particleSystem.color1.asArray();
  57595. serializationObject.color2 = particleSystem.color2.asArray();
  57596. serializationObject.colorDead = particleSystem.colorDead.asArray();
  57597. serializationObject.updateSpeed = particleSystem.updateSpeed;
  57598. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  57599. serializationObject.blendMode = particleSystem.blendMode;
  57600. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  57601. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  57602. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  57603. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  57604. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  57605. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  57606. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  57607. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  57608. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  57609. var colorGradients = particleSystem.getColorGradients();
  57610. if (colorGradients) {
  57611. serializationObject.colorGradients = [];
  57612. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  57613. var colorGradient = colorGradients_1[_i];
  57614. var serializedGradient = {
  57615. gradient: colorGradient.gradient,
  57616. color1: colorGradient.color1.asArray()
  57617. };
  57618. if (colorGradient.color2) {
  57619. serializedGradient.color2 = colorGradient.color2.asArray();
  57620. }
  57621. serializationObject.colorGradients.push(serializedGradient);
  57622. }
  57623. }
  57624. var rampGradients = particleSystem.getRampGradients();
  57625. if (rampGradients) {
  57626. serializationObject.rampGradients = [];
  57627. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  57628. var rampGradient = rampGradients_1[_a];
  57629. var serializedGradient = {
  57630. gradient: rampGradient.gradient,
  57631. color: rampGradient.color.asArray()
  57632. };
  57633. serializationObject.rampGradients.push(serializedGradient);
  57634. }
  57635. }
  57636. var colorRemapGradients = particleSystem.getColorRemapGradients();
  57637. if (colorRemapGradients) {
  57638. serializationObject.colorRemapGradients = [];
  57639. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  57640. var colorRemapGradient = colorRemapGradients_1[_b];
  57641. var serializedGradient = {
  57642. gradient: colorRemapGradient.gradient,
  57643. factor1: colorRemapGradient.factor1
  57644. };
  57645. if (colorRemapGradient.factor2 !== undefined) {
  57646. serializedGradient.factor2 = colorRemapGradient.factor2;
  57647. }
  57648. serializationObject.colorRemapGradients.push(serializedGradient);
  57649. }
  57650. }
  57651. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  57652. if (alphaRemapGradients) {
  57653. serializationObject.alphaRemapGradients = [];
  57654. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  57655. var alphaRemapGradient = alphaRemapGradients_1[_c];
  57656. var serializedGradient = {
  57657. gradient: alphaRemapGradient.gradient,
  57658. factor1: alphaRemapGradient.factor1
  57659. };
  57660. if (alphaRemapGradient.factor2 !== undefined) {
  57661. serializedGradient.factor2 = alphaRemapGradient.factor2;
  57662. }
  57663. serializationObject.alphaRemapGradients.push(serializedGradient);
  57664. }
  57665. }
  57666. var sizeGradients = particleSystem.getSizeGradients();
  57667. if (sizeGradients) {
  57668. serializationObject.sizeGradients = [];
  57669. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  57670. var sizeGradient = sizeGradients_1[_d];
  57671. var serializedGradient = {
  57672. gradient: sizeGradient.gradient,
  57673. factor1: sizeGradient.factor1
  57674. };
  57675. if (sizeGradient.factor2 !== undefined) {
  57676. serializedGradient.factor2 = sizeGradient.factor2;
  57677. }
  57678. serializationObject.sizeGradients.push(serializedGradient);
  57679. }
  57680. }
  57681. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  57682. if (angularSpeedGradients) {
  57683. serializationObject.angularSpeedGradients = [];
  57684. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  57685. var angularSpeedGradient = angularSpeedGradients_1[_e];
  57686. var serializedGradient = {
  57687. gradient: angularSpeedGradient.gradient,
  57688. factor1: angularSpeedGradient.factor1
  57689. };
  57690. if (angularSpeedGradient.factor2 !== undefined) {
  57691. serializedGradient.factor2 = angularSpeedGradient.factor2;
  57692. }
  57693. serializationObject.angularSpeedGradients.push(serializedGradient);
  57694. }
  57695. }
  57696. var velocityGradients = particleSystem.getVelocityGradients();
  57697. if (velocityGradients) {
  57698. serializationObject.velocityGradients = [];
  57699. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  57700. var velocityGradient = velocityGradients_1[_f];
  57701. var serializedGradient = {
  57702. gradient: velocityGradient.gradient,
  57703. factor1: velocityGradient.factor1
  57704. };
  57705. if (velocityGradient.factor2 !== undefined) {
  57706. serializedGradient.factor2 = velocityGradient.factor2;
  57707. }
  57708. serializationObject.velocityGradients.push(serializedGradient);
  57709. }
  57710. }
  57711. var dragGradients = particleSystem.getDragGradients();
  57712. if (dragGradients) {
  57713. serializationObject.dragyGradients = [];
  57714. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  57715. var dragGradient = dragGradients_1[_g];
  57716. var serializedGradient = {
  57717. gradient: dragGradient.gradient,
  57718. factor1: dragGradient.factor1
  57719. };
  57720. if (dragGradient.factor2 !== undefined) {
  57721. serializedGradient.factor2 = dragGradient.factor2;
  57722. }
  57723. serializationObject.dragGradients.push(serializedGradient);
  57724. }
  57725. }
  57726. var emitRateGradients = particleSystem.getEmitRateGradients();
  57727. if (emitRateGradients) {
  57728. serializationObject.emitRateGradients = [];
  57729. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  57730. var emitRateGradient = emitRateGradients_1[_h];
  57731. var serializedGradient = {
  57732. gradient: emitRateGradient.gradient,
  57733. factor1: emitRateGradient.factor1
  57734. };
  57735. if (emitRateGradient.factor2 !== undefined) {
  57736. serializedGradient.factor2 = emitRateGradient.factor2;
  57737. }
  57738. serializationObject.emitRateGradients.push(serializedGradient);
  57739. }
  57740. }
  57741. var startSizeGradients = particleSystem.getStartSizeGradients();
  57742. if (startSizeGradients) {
  57743. serializationObject.startSizeGradients = [];
  57744. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  57745. var startSizeGradient = startSizeGradients_1[_j];
  57746. var serializedGradient = {
  57747. gradient: startSizeGradient.gradient,
  57748. factor1: startSizeGradient.factor1
  57749. };
  57750. if (startSizeGradient.factor2 !== undefined) {
  57751. serializedGradient.factor2 = startSizeGradient.factor2;
  57752. }
  57753. serializationObject.startSizeGradients.push(serializedGradient);
  57754. }
  57755. }
  57756. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  57757. if (limitVelocityGradients) {
  57758. serializationObject.limitVelocityGradients = [];
  57759. for (var _k = 0, limitVelocityGradients_1 = limitVelocityGradients; _k < limitVelocityGradients_1.length; _k++) {
  57760. var limitVelocityGradient = limitVelocityGradients_1[_k];
  57761. var serializedGradient = {
  57762. gradient: limitVelocityGradient.gradient,
  57763. factor1: limitVelocityGradient.factor1
  57764. };
  57765. if (limitVelocityGradient.factor2 !== undefined) {
  57766. serializedGradient.factor2 = limitVelocityGradient.factor2;
  57767. }
  57768. serializationObject.limitVelocityGradients.push(serializedGradient);
  57769. }
  57770. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  57771. }
  57772. if (particleSystem.noiseTexture) {
  57773. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  57774. }
  57775. };
  57776. /** @hidden */
  57777. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  57778. // Texture
  57779. if (parsedParticleSystem.textureName) {
  57780. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57781. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57782. }
  57783. // Emitter
  57784. if (parsedParticleSystem.emitterId === undefined) {
  57785. particleSystem.emitter = BABYLON.Vector3.Zero();
  57786. }
  57787. else if (parsedParticleSystem.emitterId) {
  57788. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57789. }
  57790. else {
  57791. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57792. }
  57793. // Misc.
  57794. if (parsedParticleSystem.renderingGroupId !== undefined) {
  57795. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  57796. }
  57797. if (parsedParticleSystem.isBillboardBased !== undefined) {
  57798. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  57799. }
  57800. // Animations
  57801. if (parsedParticleSystem.animations) {
  57802. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57803. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57804. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57805. }
  57806. }
  57807. if (parsedParticleSystem.autoAnimate) {
  57808. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57809. }
  57810. // Particle system
  57811. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57812. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57813. particleSystem.minSize = parsedParticleSystem.minSize;
  57814. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57815. if (parsedParticleSystem.minScaleX) {
  57816. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  57817. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  57818. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  57819. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  57820. }
  57821. if (parsedParticleSystem.preWarmCycles !== undefined) {
  57822. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  57823. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  57824. }
  57825. if (parsedParticleSystem.minInitialRotation !== undefined) {
  57826. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  57827. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  57828. }
  57829. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57830. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57831. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57832. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57833. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57834. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57835. if (parsedParticleSystem.noiseStrength) {
  57836. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  57837. }
  57838. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57839. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57840. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57841. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57842. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57843. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57844. if (parsedParticleSystem.colorGradients) {
  57845. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  57846. var colorGradient = _a[_i];
  57847. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  57848. }
  57849. }
  57850. if (parsedParticleSystem.rampGradients) {
  57851. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  57852. var rampGradient = _c[_b];
  57853. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color1));
  57854. }
  57855. }
  57856. if (parsedParticleSystem.colorRemapGradients) {
  57857. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  57858. var colorRemapGradient = _e[_d];
  57859. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  57860. }
  57861. }
  57862. if (parsedParticleSystem.alphaRemapGradients) {
  57863. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  57864. var alphaRemapGradient = _g[_f];
  57865. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  57866. }
  57867. }
  57868. if (parsedParticleSystem.sizeGradients) {
  57869. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  57870. var sizeGradient = _j[_h];
  57871. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  57872. }
  57873. }
  57874. if (parsedParticleSystem.sizeGradients) {
  57875. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  57876. var sizeGradient = _l[_k];
  57877. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  57878. }
  57879. }
  57880. if (parsedParticleSystem.angularSpeedGradients) {
  57881. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  57882. var angularSpeedGradient = _o[_m];
  57883. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  57884. }
  57885. }
  57886. if (parsedParticleSystem.velocityGradients) {
  57887. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  57888. var velocityGradient = _q[_p];
  57889. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  57890. }
  57891. }
  57892. if (parsedParticleSystem.dragGradients) {
  57893. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  57894. var dragGradient = _s[_r];
  57895. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  57896. }
  57897. }
  57898. if (parsedParticleSystem.emitRateGradients) {
  57899. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  57900. var emitRateGradient = _u[_t];
  57901. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  57902. }
  57903. }
  57904. if (parsedParticleSystem.startSizeGradients) {
  57905. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  57906. var startSizeGradient = _w[_v];
  57907. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  57908. }
  57909. }
  57910. if (parsedParticleSystem.limitVelocityGradients) {
  57911. for (var _x = 0, _y = parsedParticleSystem.limitVelocityGradients; _x < _y.length; _x++) {
  57912. var limitVelocityGradient = _y[_x];
  57913. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  57914. }
  57915. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  57916. }
  57917. if (parsedParticleSystem.noiseTexture) {
  57918. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  57919. }
  57920. // Emitter
  57921. var emitterType;
  57922. if (parsedParticleSystem.particleEmitterType) {
  57923. switch (parsedParticleSystem.particleEmitterType.type) {
  57924. case "SphereParticleEmitter":
  57925. emitterType = new BABYLON.SphereParticleEmitter();
  57926. break;
  57927. case "SphereDirectedParticleEmitter":
  57928. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57929. break;
  57930. case "ConeEmitter":
  57931. case "ConeParticleEmitter":
  57932. emitterType = new BABYLON.ConeParticleEmitter();
  57933. break;
  57934. case "BoxEmitter":
  57935. case "BoxParticleEmitter":
  57936. default:
  57937. emitterType = new BABYLON.BoxParticleEmitter();
  57938. break;
  57939. }
  57940. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57941. }
  57942. else {
  57943. emitterType = new BABYLON.BoxParticleEmitter();
  57944. emitterType.parse(parsedParticleSystem);
  57945. }
  57946. particleSystem.particleEmitterType = emitterType;
  57947. // Animation sheet
  57948. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57949. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57950. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57951. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57952. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57953. };
  57954. /**
  57955. * Parses a JSON object to create a particle system.
  57956. * @param parsedParticleSystem The JSON object to parse
  57957. * @param scene The scene to create the particle system in
  57958. * @param rootUrl The root url to use to load external dependencies like texture
  57959. * @returns the Parsed particle system
  57960. */
  57961. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57962. var name = parsedParticleSystem.name;
  57963. var custom = null;
  57964. var program = null;
  57965. if (parsedParticleSystem.customShader) {
  57966. program = parsedParticleSystem.customShader;
  57967. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57968. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57969. }
  57970. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  57971. particleSystem.customShader = program;
  57972. if (parsedParticleSystem.id) {
  57973. particleSystem.id = parsedParticleSystem.id;
  57974. }
  57975. // Auto start
  57976. if (parsedParticleSystem.preventAutoStart) {
  57977. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57978. }
  57979. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57980. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57981. if (!particleSystem.preventAutoStart) {
  57982. particleSystem.start();
  57983. }
  57984. return particleSystem;
  57985. };
  57986. return ParticleSystem;
  57987. }(BABYLON.BaseParticleSystem));
  57988. BABYLON.ParticleSystem = ParticleSystem;
  57989. })(BABYLON || (BABYLON = {}));
  57990. //# sourceMappingURL=babylon.particleSystem.js.map
  57991. var BABYLON;
  57992. (function (BABYLON) {
  57993. /**
  57994. * Particle emitter emitting particles from the inside of a box.
  57995. * It emits the particles randomly between 2 given directions.
  57996. */
  57997. var BoxParticleEmitter = /** @class */ (function () {
  57998. /**
  57999. * Creates a new instance BoxParticleEmitter
  58000. */
  58001. function BoxParticleEmitter() {
  58002. /**
  58003. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58004. */
  58005. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  58006. /**
  58007. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58008. */
  58009. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  58010. /**
  58011. * 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.
  58012. */
  58013. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  58014. /**
  58015. * 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.
  58016. */
  58017. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  58018. }
  58019. /**
  58020. * Called by the particle System when the direction is computed for the created particle.
  58021. * @param worldMatrix is the world matrix of the particle system
  58022. * @param directionToUpdate is the direction vector to update with the result
  58023. * @param particle is the particle we are computed the direction for
  58024. */
  58025. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58026. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58027. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58028. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58029. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58030. };
  58031. /**
  58032. * Called by the particle System when the position is computed for the created particle.
  58033. * @param worldMatrix is the world matrix of the particle system
  58034. * @param positionToUpdate is the position vector to update with the result
  58035. * @param particle is the particle we are computed the position for
  58036. */
  58037. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58038. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  58039. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  58040. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  58041. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58042. };
  58043. /**
  58044. * Clones the current emitter and returns a copy of it
  58045. * @returns the new emitter
  58046. */
  58047. BoxParticleEmitter.prototype.clone = function () {
  58048. var newOne = new BoxParticleEmitter();
  58049. BABYLON.Tools.DeepCopy(this, newOne);
  58050. return newOne;
  58051. };
  58052. /**
  58053. * Called by the GPUParticleSystem to setup the update shader
  58054. * @param effect defines the update shader
  58055. */
  58056. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  58057. effect.setVector3("direction1", this.direction1);
  58058. effect.setVector3("direction2", this.direction2);
  58059. effect.setVector3("minEmitBox", this.minEmitBox);
  58060. effect.setVector3("maxEmitBox", this.maxEmitBox);
  58061. };
  58062. /**
  58063. * Returns a string to use to update the GPU particles update shader
  58064. * @returns a string containng the defines string
  58065. */
  58066. BoxParticleEmitter.prototype.getEffectDefines = function () {
  58067. return "#define BOXEMITTER";
  58068. };
  58069. /**
  58070. * Returns the string "BoxParticleEmitter"
  58071. * @returns a string containing the class name
  58072. */
  58073. BoxParticleEmitter.prototype.getClassName = function () {
  58074. return "BoxParticleEmitter";
  58075. };
  58076. /**
  58077. * Serializes the particle system to a JSON object.
  58078. * @returns the JSON object
  58079. */
  58080. BoxParticleEmitter.prototype.serialize = function () {
  58081. var serializationObject = {};
  58082. serializationObject.type = this.getClassName();
  58083. serializationObject.direction1 = this.direction1.asArray();
  58084. serializationObject.direction2 = this.direction2.asArray();
  58085. serializationObject.minEmitBox = this.minEmitBox.asArray();
  58086. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  58087. return serializationObject;
  58088. };
  58089. /**
  58090. * Parse properties from a JSON object
  58091. * @param serializationObject defines the JSON object
  58092. */
  58093. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  58094. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  58095. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  58096. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  58097. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  58098. };
  58099. return BoxParticleEmitter;
  58100. }());
  58101. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  58102. })(BABYLON || (BABYLON = {}));
  58103. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  58104. var BABYLON;
  58105. (function (BABYLON) {
  58106. /**
  58107. * Particle emitter emitting particles from the inside of a cylinder.
  58108. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  58109. */
  58110. var CylinderParticleEmitter = /** @class */ (function () {
  58111. /**
  58112. * Creates a new instance CylinderParticleEmitter
  58113. * @param radius the radius of the emission cylinder (1 by default)
  58114. * @param height the height of the emission cylinder (1 by default)
  58115. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58116. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58117. */
  58118. function CylinderParticleEmitter(
  58119. /**
  58120. * The radius of the emission cylinder.
  58121. */
  58122. radius,
  58123. /**
  58124. * The height of the emission cylinder.
  58125. */
  58126. height,
  58127. /**
  58128. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58129. */
  58130. radiusRange,
  58131. /**
  58132. * How much to randomize the particle direction [0-1].
  58133. */
  58134. directionRandomizer) {
  58135. if (radius === void 0) { radius = 1; }
  58136. if (height === void 0) { height = 1; }
  58137. if (radiusRange === void 0) { radiusRange = 1; }
  58138. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58139. this.radius = radius;
  58140. this.height = height;
  58141. this.radiusRange = radiusRange;
  58142. this.directionRandomizer = directionRandomizer;
  58143. }
  58144. /**
  58145. * Called by the particle System when the direction is computed for the created particle.
  58146. * @param worldMatrix is the world matrix of the particle system
  58147. * @param directionToUpdate is the direction vector to update with the result
  58148. * @param particle is the particle we are computed the direction for
  58149. */
  58150. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58151. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58152. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  58153. var angle = Math.atan2(direction.x, direction.z);
  58154. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  58155. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  58156. direction.x = Math.sin(angle);
  58157. direction.z = Math.cos(angle);
  58158. direction.normalize();
  58159. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58160. };
  58161. /**
  58162. * Called by the particle System when the position is computed for the created particle.
  58163. * @param worldMatrix is the world matrix of the particle system
  58164. * @param positionToUpdate is the position vector to update with the result
  58165. * @param particle is the particle we are computed the position for
  58166. */
  58167. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58168. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  58169. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58170. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  58171. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  58172. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  58173. var xPos = positionRadius * Math.cos(angle);
  58174. var zPos = positionRadius * Math.sin(angle);
  58175. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  58176. };
  58177. /**
  58178. * Clones the current emitter and returns a copy of it
  58179. * @returns the new emitter
  58180. */
  58181. CylinderParticleEmitter.prototype.clone = function () {
  58182. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  58183. BABYLON.Tools.DeepCopy(this, newOne);
  58184. return newOne;
  58185. };
  58186. /**
  58187. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58188. * @param effect defines the update shader
  58189. */
  58190. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  58191. effect.setFloat("radius", this.radius);
  58192. effect.setFloat("height", this.height);
  58193. effect.setFloat("radiusRange", this.radiusRange);
  58194. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58195. };
  58196. /**
  58197. * Returns a string to use to update the GPU particles update shader
  58198. * @returns a string containng the defines string
  58199. */
  58200. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  58201. return "#define CYLINDEREMITTER";
  58202. };
  58203. /**
  58204. * Returns the string "CylinderParticleEmitter"
  58205. * @returns a string containing the class name
  58206. */
  58207. CylinderParticleEmitter.prototype.getClassName = function () {
  58208. return "CylinderParticleEmitter";
  58209. };
  58210. /**
  58211. * Serializes the particle system to a JSON object.
  58212. * @returns the JSON object
  58213. */
  58214. CylinderParticleEmitter.prototype.serialize = function () {
  58215. var serializationObject = {};
  58216. serializationObject.type = this.getClassName();
  58217. serializationObject.radius = this.radius;
  58218. serializationObject.height = this.height;
  58219. serializationObject.radiusRange = this.radiusRange;
  58220. serializationObject.directionRandomizer = this.directionRandomizer;
  58221. return serializationObject;
  58222. };
  58223. /**
  58224. * Parse properties from a JSON object
  58225. * @param serializationObject defines the JSON object
  58226. */
  58227. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  58228. this.radius = serializationObject.radius;
  58229. this.height = serializationObject.height;
  58230. this.radiusRange = serializationObject.radiusRange;
  58231. this.directionRandomizer = serializationObject.directionRandomizer;
  58232. };
  58233. return CylinderParticleEmitter;
  58234. }());
  58235. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  58236. /**
  58237. * Particle emitter emitting particles from the inside of a cylinder.
  58238. * It emits the particles randomly between two vectors.
  58239. */
  58240. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  58241. __extends(CylinderDirectedParticleEmitter, _super);
  58242. /**
  58243. * Creates a new instance CylinderDirectedParticleEmitter
  58244. * @param radius the radius of the emission cylinder (1 by default)
  58245. * @param height the height of the emission cylinder (1 by default)
  58246. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58247. * @param direction1 the min limit of the emission direction (up vector by default)
  58248. * @param direction2 the max limit of the emission direction (up vector by default)
  58249. */
  58250. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  58251. /**
  58252. * The min limit of the emission direction.
  58253. */
  58254. direction1,
  58255. /**
  58256. * The max limit of the emission direction.
  58257. */
  58258. direction2) {
  58259. if (radius === void 0) { radius = 1; }
  58260. if (height === void 0) { height = 1; }
  58261. if (radiusRange === void 0) { radiusRange = 1; }
  58262. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58263. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58264. var _this = _super.call(this, radius, height, radiusRange) || this;
  58265. _this.direction1 = direction1;
  58266. _this.direction2 = direction2;
  58267. return _this;
  58268. }
  58269. /**
  58270. * Called by the particle System when the direction is computed for the created particle.
  58271. * @param worldMatrix is the world matrix of the particle system
  58272. * @param directionToUpdate is the direction vector to update with the result
  58273. * @param particle is the particle we are computed the direction for
  58274. */
  58275. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58276. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58277. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58278. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58279. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58280. };
  58281. /**
  58282. * Clones the current emitter and returns a copy of it
  58283. * @returns the new emitter
  58284. */
  58285. CylinderDirectedParticleEmitter.prototype.clone = function () {
  58286. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  58287. BABYLON.Tools.DeepCopy(this, newOne);
  58288. return newOne;
  58289. };
  58290. /**
  58291. * Called by the GPUParticleSystem to setup the update shader
  58292. * @param effect defines the update shader
  58293. */
  58294. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58295. effect.setFloat("radius", this.radius);
  58296. effect.setFloat("height", this.height);
  58297. effect.setFloat("radiusRange", this.radiusRange);
  58298. effect.setVector3("direction1", this.direction1);
  58299. effect.setVector3("direction2", this.direction2);
  58300. };
  58301. /**
  58302. * Returns a string to use to update the GPU particles update shader
  58303. * @returns a string containng the defines string
  58304. */
  58305. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58306. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  58307. };
  58308. /**
  58309. * Returns the string "CylinderDirectedParticleEmitter"
  58310. * @returns a string containing the class name
  58311. */
  58312. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  58313. return "CylinderDirectedParticleEmitter";
  58314. };
  58315. /**
  58316. * Serializes the particle system to a JSON object.
  58317. * @returns the JSON object
  58318. */
  58319. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  58320. var serializationObject = _super.prototype.serialize.call(this);
  58321. serializationObject.direction1 = this.direction1.asArray();
  58322. serializationObject.direction2 = this.direction2.asArray();
  58323. return serializationObject;
  58324. };
  58325. /**
  58326. * Parse properties from a JSON object
  58327. * @param serializationObject defines the JSON object
  58328. */
  58329. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58330. _super.prototype.parse.call(this, serializationObject);
  58331. this.direction1.copyFrom(serializationObject.direction1);
  58332. this.direction2.copyFrom(serializationObject.direction2);
  58333. };
  58334. return CylinderDirectedParticleEmitter;
  58335. }(CylinderParticleEmitter));
  58336. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  58337. })(BABYLON || (BABYLON = {}));
  58338. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  58339. var BABYLON;
  58340. (function (BABYLON) {
  58341. /**
  58342. * Particle emitter emitting particles from the inside of a cone.
  58343. * It emits the particles alongside the cone volume from the base to the particle.
  58344. * The emission direction might be randomized.
  58345. */
  58346. var ConeParticleEmitter = /** @class */ (function () {
  58347. /**
  58348. * Creates a new instance ConeParticleEmitter
  58349. * @param radius the radius of the emission cone (1 by default)
  58350. * @param angles the cone base angle (PI by default)
  58351. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  58352. */
  58353. function ConeParticleEmitter(radius, angle,
  58354. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  58355. directionRandomizer) {
  58356. if (radius === void 0) { radius = 1; }
  58357. if (angle === void 0) { angle = Math.PI; }
  58358. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58359. this.directionRandomizer = directionRandomizer;
  58360. /**
  58361. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  58362. */
  58363. this.radiusRange = 1;
  58364. /**
  58365. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  58366. */
  58367. this.heightRange = 1;
  58368. /**
  58369. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  58370. */
  58371. this.emitFromSpawnPointOnly = false;
  58372. this.angle = angle;
  58373. this.radius = radius;
  58374. }
  58375. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  58376. /**
  58377. * Gets or sets the radius of the emission cone
  58378. */
  58379. get: function () {
  58380. return this._radius;
  58381. },
  58382. set: function (value) {
  58383. this._radius = value;
  58384. this._buildHeight();
  58385. },
  58386. enumerable: true,
  58387. configurable: true
  58388. });
  58389. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  58390. /**
  58391. * Gets or sets the angle of the emission cone
  58392. */
  58393. get: function () {
  58394. return this._angle;
  58395. },
  58396. set: function (value) {
  58397. this._angle = value;
  58398. this._buildHeight();
  58399. },
  58400. enumerable: true,
  58401. configurable: true
  58402. });
  58403. ConeParticleEmitter.prototype._buildHeight = function () {
  58404. if (this._angle !== 0) {
  58405. this._height = this._radius / Math.tan(this._angle / 2);
  58406. }
  58407. else {
  58408. this._height = 1;
  58409. }
  58410. };
  58411. /**
  58412. * Called by the particle System when the direction is computed for the created particle.
  58413. * @param worldMatrix is the world matrix of the particle system
  58414. * @param directionToUpdate is the direction vector to update with the result
  58415. * @param particle is the particle we are computed the direction for
  58416. */
  58417. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58418. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  58419. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  58420. }
  58421. else {
  58422. // measure the direction Vector from the emitter to the particle.
  58423. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58424. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58425. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58426. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58427. direction.x += randX;
  58428. direction.y += randY;
  58429. direction.z += randZ;
  58430. direction.normalize();
  58431. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58432. }
  58433. };
  58434. /**
  58435. * Called by the particle System when the position is computed for the created particle.
  58436. * @param worldMatrix is the world matrix of the particle system
  58437. * @param positionToUpdate is the position vector to update with the result
  58438. * @param particle is the particle we are computed the position for
  58439. */
  58440. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58441. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  58442. var h;
  58443. if (!this.emitFromSpawnPointOnly) {
  58444. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  58445. // Better distribution in a cone at normal angles.
  58446. h = 1 - h * h;
  58447. }
  58448. else {
  58449. h = 0.0001;
  58450. }
  58451. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  58452. radius = radius * h;
  58453. var randX = radius * Math.sin(s);
  58454. var randZ = radius * Math.cos(s);
  58455. var randY = h * this._height;
  58456. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58457. };
  58458. /**
  58459. * Clones the current emitter and returns a copy of it
  58460. * @returns the new emitter
  58461. */
  58462. ConeParticleEmitter.prototype.clone = function () {
  58463. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  58464. BABYLON.Tools.DeepCopy(this, newOne);
  58465. return newOne;
  58466. };
  58467. /**
  58468. * Called by the GPUParticleSystem to setup the update shader
  58469. * @param effect defines the update shader
  58470. */
  58471. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  58472. effect.setFloat2("radius", this._radius, this.radiusRange);
  58473. effect.setFloat("coneAngle", this._angle);
  58474. effect.setFloat2("height", this._height, this.heightRange);
  58475. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58476. };
  58477. /**
  58478. * Returns a string to use to update the GPU particles update shader
  58479. * @returns a string containng the defines string
  58480. */
  58481. ConeParticleEmitter.prototype.getEffectDefines = function () {
  58482. var defines = "#define CONEEMITTER";
  58483. if (this.emitFromSpawnPointOnly) {
  58484. defines += "\n#define CONEEMITTERSPAWNPOINT";
  58485. }
  58486. return defines;
  58487. };
  58488. /**
  58489. * Returns the string "ConeParticleEmitter"
  58490. * @returns a string containing the class name
  58491. */
  58492. ConeParticleEmitter.prototype.getClassName = function () {
  58493. return "ConeParticleEmitter";
  58494. };
  58495. /**
  58496. * Serializes the particle system to a JSON object.
  58497. * @returns the JSON object
  58498. */
  58499. ConeParticleEmitter.prototype.serialize = function () {
  58500. var serializationObject = {};
  58501. serializationObject.type = this.getClassName();
  58502. serializationObject.radius = this._radius;
  58503. serializationObject.angle = this._angle;
  58504. serializationObject.directionRandomizer = this.directionRandomizer;
  58505. return serializationObject;
  58506. };
  58507. /**
  58508. * Parse properties from a JSON object
  58509. * @param serializationObject defines the JSON object
  58510. */
  58511. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  58512. this.radius = serializationObject.radius;
  58513. this.angle = serializationObject.angle;
  58514. this.directionRandomizer = serializationObject.directionRandomizer;
  58515. };
  58516. return ConeParticleEmitter;
  58517. }());
  58518. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  58519. })(BABYLON || (BABYLON = {}));
  58520. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  58521. var BABYLON;
  58522. (function (BABYLON) {
  58523. /**
  58524. * Particle emitter emitting particles from the inside of a sphere.
  58525. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  58526. */
  58527. var SphereParticleEmitter = /** @class */ (function () {
  58528. /**
  58529. * Creates a new instance SphereParticleEmitter
  58530. * @param radius the radius of the emission sphere (1 by default)
  58531. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58532. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58533. */
  58534. function SphereParticleEmitter(
  58535. /**
  58536. * The radius of the emission sphere.
  58537. */
  58538. radius,
  58539. /**
  58540. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58541. */
  58542. radiusRange,
  58543. /**
  58544. * How much to randomize the particle direction [0-1].
  58545. */
  58546. directionRandomizer) {
  58547. if (radius === void 0) { radius = 1; }
  58548. if (radiusRange === void 0) { radiusRange = 1; }
  58549. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58550. this.radius = radius;
  58551. this.radiusRange = radiusRange;
  58552. this.directionRandomizer = directionRandomizer;
  58553. }
  58554. /**
  58555. * Called by the particle System when the direction is computed for the created particle.
  58556. * @param worldMatrix is the world matrix of the particle system
  58557. * @param directionToUpdate is the direction vector to update with the result
  58558. * @param particle is the particle we are computed the direction for
  58559. */
  58560. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58561. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58562. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58563. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58564. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58565. direction.x += randX;
  58566. direction.y += randY;
  58567. direction.z += randZ;
  58568. direction.normalize();
  58569. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58570. };
  58571. /**
  58572. * Called by the particle System when the position is computed for the created particle.
  58573. * @param worldMatrix is the world matrix of the particle system
  58574. * @param positionToUpdate is the position vector to update with the result
  58575. * @param particle is the particle we are computed the position for
  58576. */
  58577. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58578. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58579. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58580. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58581. var theta = Math.acos(2 * v - 1);
  58582. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58583. var randY = randRadius * Math.cos(theta);
  58584. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58585. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58586. };
  58587. /**
  58588. * Clones the current emitter and returns a copy of it
  58589. * @returns the new emitter
  58590. */
  58591. SphereParticleEmitter.prototype.clone = function () {
  58592. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  58593. BABYLON.Tools.DeepCopy(this, newOne);
  58594. return newOne;
  58595. };
  58596. /**
  58597. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58598. * @param effect defines the update shader
  58599. */
  58600. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  58601. effect.setFloat("radius", this.radius);
  58602. effect.setFloat("radiusRange", this.radiusRange);
  58603. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58604. };
  58605. /**
  58606. * Returns a string to use to update the GPU particles update shader
  58607. * @returns a string containng the defines string
  58608. */
  58609. SphereParticleEmitter.prototype.getEffectDefines = function () {
  58610. return "#define SPHEREEMITTER";
  58611. };
  58612. /**
  58613. * Returns the string "SphereParticleEmitter"
  58614. * @returns a string containing the class name
  58615. */
  58616. SphereParticleEmitter.prototype.getClassName = function () {
  58617. return "SphereParticleEmitter";
  58618. };
  58619. /**
  58620. * Serializes the particle system to a JSON object.
  58621. * @returns the JSON object
  58622. */
  58623. SphereParticleEmitter.prototype.serialize = function () {
  58624. var serializationObject = {};
  58625. serializationObject.type = this.getClassName();
  58626. serializationObject.radius = this.radius;
  58627. serializationObject.radiusRange = this.radiusRange;
  58628. serializationObject.directionRandomizer = this.directionRandomizer;
  58629. return serializationObject;
  58630. };
  58631. /**
  58632. * Parse properties from a JSON object
  58633. * @param serializationObject defines the JSON object
  58634. */
  58635. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  58636. this.radius = serializationObject.radius;
  58637. this.radiusRange = serializationObject.radiusRange;
  58638. this.directionRandomizer = serializationObject.directionRandomizer;
  58639. };
  58640. return SphereParticleEmitter;
  58641. }());
  58642. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  58643. /**
  58644. * Particle emitter emitting particles from the inside of a sphere.
  58645. * It emits the particles randomly between two vectors.
  58646. */
  58647. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  58648. __extends(SphereDirectedParticleEmitter, _super);
  58649. /**
  58650. * Creates a new instance SphereDirectedParticleEmitter
  58651. * @param radius the radius of the emission sphere (1 by default)
  58652. * @param direction1 the min limit of the emission direction (up vector by default)
  58653. * @param direction2 the max limit of the emission direction (up vector by default)
  58654. */
  58655. function SphereDirectedParticleEmitter(radius,
  58656. /**
  58657. * The min limit of the emission direction.
  58658. */
  58659. direction1,
  58660. /**
  58661. * The max limit of the emission direction.
  58662. */
  58663. direction2) {
  58664. if (radius === void 0) { radius = 1; }
  58665. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58666. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58667. var _this = _super.call(this, radius) || this;
  58668. _this.direction1 = direction1;
  58669. _this.direction2 = direction2;
  58670. return _this;
  58671. }
  58672. /**
  58673. * Called by the particle System when the direction is computed for the created particle.
  58674. * @param worldMatrix is the world matrix of the particle system
  58675. * @param directionToUpdate is the direction vector to update with the result
  58676. * @param particle is the particle we are computed the direction for
  58677. */
  58678. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58679. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58680. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58681. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58682. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58683. };
  58684. /**
  58685. * Clones the current emitter and returns a copy of it
  58686. * @returns the new emitter
  58687. */
  58688. SphereDirectedParticleEmitter.prototype.clone = function () {
  58689. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  58690. BABYLON.Tools.DeepCopy(this, newOne);
  58691. return newOne;
  58692. };
  58693. /**
  58694. * Called by the GPUParticleSystem to setup the update shader
  58695. * @param effect defines the update shader
  58696. */
  58697. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58698. effect.setFloat("radius", this.radius);
  58699. effect.setFloat("radiusRange", this.radiusRange);
  58700. effect.setVector3("direction1", this.direction1);
  58701. effect.setVector3("direction2", this.direction2);
  58702. };
  58703. /**
  58704. * Returns a string to use to update the GPU particles update shader
  58705. * @returns a string containng the defines string
  58706. */
  58707. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58708. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  58709. };
  58710. /**
  58711. * Returns the string "SphereDirectedParticleEmitter"
  58712. * @returns a string containing the class name
  58713. */
  58714. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  58715. return "SphereDirectedParticleEmitter";
  58716. };
  58717. /**
  58718. * Serializes the particle system to a JSON object.
  58719. * @returns the JSON object
  58720. */
  58721. SphereDirectedParticleEmitter.prototype.serialize = function () {
  58722. var serializationObject = _super.prototype.serialize.call(this);
  58723. serializationObject.direction1 = this.direction1.asArray();
  58724. serializationObject.direction2 = this.direction2.asArray();
  58725. return serializationObject;
  58726. };
  58727. /**
  58728. * Parse properties from a JSON object
  58729. * @param serializationObject defines the JSON object
  58730. */
  58731. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58732. _super.prototype.parse.call(this, serializationObject);
  58733. this.direction1.copyFrom(serializationObject.direction1);
  58734. this.direction2.copyFrom(serializationObject.direction2);
  58735. };
  58736. return SphereDirectedParticleEmitter;
  58737. }(SphereParticleEmitter));
  58738. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  58739. })(BABYLON || (BABYLON = {}));
  58740. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  58741. var BABYLON;
  58742. (function (BABYLON) {
  58743. /**
  58744. * Particle emitter emitting particles from the inside of a hemisphere.
  58745. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  58746. */
  58747. var HemisphericParticleEmitter = /** @class */ (function () {
  58748. /**
  58749. * Creates a new instance HemisphericParticleEmitter
  58750. * @param radius the radius of the emission hemisphere (1 by default)
  58751. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58752. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58753. */
  58754. function HemisphericParticleEmitter(
  58755. /**
  58756. * The radius of the emission hemisphere.
  58757. */
  58758. radius,
  58759. /**
  58760. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58761. */
  58762. radiusRange,
  58763. /**
  58764. * How much to randomize the particle direction [0-1].
  58765. */
  58766. directionRandomizer) {
  58767. if (radius === void 0) { radius = 1; }
  58768. if (radiusRange === void 0) { radiusRange = 1; }
  58769. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58770. this.radius = radius;
  58771. this.radiusRange = radiusRange;
  58772. this.directionRandomizer = directionRandomizer;
  58773. }
  58774. /**
  58775. * Called by the particle System when the direction is computed for the created particle.
  58776. * @param worldMatrix is the world matrix of the particle system
  58777. * @param directionToUpdate is the direction vector to update with the result
  58778. * @param particle is the particle we are computed the direction for
  58779. */
  58780. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58781. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58782. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58783. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58784. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58785. direction.x += randX;
  58786. direction.y += randY;
  58787. direction.z += randZ;
  58788. direction.normalize();
  58789. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58790. };
  58791. /**
  58792. * Called by the particle System when the position is computed for the created particle.
  58793. * @param worldMatrix is the world matrix of the particle system
  58794. * @param positionToUpdate is the position vector to update with the result
  58795. * @param particle is the particle we are computed the position for
  58796. */
  58797. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58798. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58799. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58800. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58801. var theta = Math.acos(2 * v - 1);
  58802. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58803. var randY = randRadius * Math.cos(theta);
  58804. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58805. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  58806. };
  58807. /**
  58808. * Clones the current emitter and returns a copy of it
  58809. * @returns the new emitter
  58810. */
  58811. HemisphericParticleEmitter.prototype.clone = function () {
  58812. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  58813. BABYLON.Tools.DeepCopy(this, newOne);
  58814. return newOne;
  58815. };
  58816. /**
  58817. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58818. * @param effect defines the update shader
  58819. */
  58820. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  58821. effect.setFloat("radius", this.radius);
  58822. effect.setFloat("radiusRange", this.radiusRange);
  58823. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58824. };
  58825. /**
  58826. * Returns a string to use to update the GPU particles update shader
  58827. * @returns a string containng the defines string
  58828. */
  58829. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  58830. return "#define HEMISPHERICEMITTER";
  58831. };
  58832. /**
  58833. * Returns the string "HemisphericParticleEmitter"
  58834. * @returns a string containing the class name
  58835. */
  58836. HemisphericParticleEmitter.prototype.getClassName = function () {
  58837. return "HemisphericParticleEmitter";
  58838. };
  58839. /**
  58840. * Serializes the particle system to a JSON object.
  58841. * @returns the JSON object
  58842. */
  58843. HemisphericParticleEmitter.prototype.serialize = function () {
  58844. var serializationObject = {};
  58845. serializationObject.type = this.getClassName();
  58846. serializationObject.radius = this.radius;
  58847. serializationObject.radiusRange = this.radiusRange;
  58848. serializationObject.directionRandomizer = this.directionRandomizer;
  58849. return serializationObject;
  58850. };
  58851. /**
  58852. * Parse properties from a JSON object
  58853. * @param serializationObject defines the JSON object
  58854. */
  58855. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  58856. this.radius = serializationObject.radius;
  58857. this.radiusRange = serializationObject.radiusRange;
  58858. this.directionRandomizer = serializationObject.directionRandomizer;
  58859. };
  58860. return HemisphericParticleEmitter;
  58861. }());
  58862. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  58863. })(BABYLON || (BABYLON = {}));
  58864. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  58865. var BABYLON;
  58866. (function (BABYLON) {
  58867. /**
  58868. * Particle emitter emitting particles from a point.
  58869. * It emits the particles randomly between 2 given directions.
  58870. */
  58871. var PointParticleEmitter = /** @class */ (function () {
  58872. /**
  58873. * Creates a new instance PointParticleEmitter
  58874. */
  58875. function PointParticleEmitter() {
  58876. /**
  58877. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58878. */
  58879. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  58880. /**
  58881. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58882. */
  58883. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  58884. }
  58885. /**
  58886. * Called by the particle System when the direction is computed for the created particle.
  58887. * @param worldMatrix is the world matrix of the particle system
  58888. * @param directionToUpdate is the direction vector to update with the result
  58889. * @param particle is the particle we are computed the direction for
  58890. */
  58891. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58892. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58893. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58894. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58895. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58896. };
  58897. /**
  58898. * Called by the particle System when the position is computed for the created particle.
  58899. * @param worldMatrix is the world matrix of the particle system
  58900. * @param positionToUpdate is the position vector to update with the result
  58901. * @param particle is the particle we are computed the position for
  58902. */
  58903. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58904. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  58905. };
  58906. /**
  58907. * Clones the current emitter and returns a copy of it
  58908. * @returns the new emitter
  58909. */
  58910. PointParticleEmitter.prototype.clone = function () {
  58911. var newOne = new PointParticleEmitter();
  58912. BABYLON.Tools.DeepCopy(this, newOne);
  58913. return newOne;
  58914. };
  58915. /**
  58916. * Called by the GPUParticleSystem to setup the update shader
  58917. * @param effect defines the update shader
  58918. */
  58919. PointParticleEmitter.prototype.applyToShader = function (effect) {
  58920. effect.setVector3("direction1", this.direction1);
  58921. effect.setVector3("direction2", this.direction2);
  58922. };
  58923. /**
  58924. * Returns a string to use to update the GPU particles update shader
  58925. * @returns a string containng the defines string
  58926. */
  58927. PointParticleEmitter.prototype.getEffectDefines = function () {
  58928. return "#define POINTEMITTER";
  58929. };
  58930. /**
  58931. * Returns the string "PointParticleEmitter"
  58932. * @returns a string containing the class name
  58933. */
  58934. PointParticleEmitter.prototype.getClassName = function () {
  58935. return "PointParticleEmitter";
  58936. };
  58937. /**
  58938. * Serializes the particle system to a JSON object.
  58939. * @returns the JSON object
  58940. */
  58941. PointParticleEmitter.prototype.serialize = function () {
  58942. var serializationObject = {};
  58943. serializationObject.type = this.getClassName();
  58944. serializationObject.direction1 = this.direction1.asArray();
  58945. serializationObject.direction2 = this.direction2.asArray();
  58946. return serializationObject;
  58947. };
  58948. /**
  58949. * Parse properties from a JSON object
  58950. * @param serializationObject defines the JSON object
  58951. */
  58952. PointParticleEmitter.prototype.parse = function (serializationObject) {
  58953. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  58954. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  58955. };
  58956. return PointParticleEmitter;
  58957. }());
  58958. BABYLON.PointParticleEmitter = PointParticleEmitter;
  58959. })(BABYLON || (BABYLON = {}));
  58960. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  58961. var BABYLON;
  58962. (function (BABYLON) {
  58963. // Adds the parsers to the scene parsers.
  58964. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  58965. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  58966. if (!individualParser) {
  58967. return;
  58968. }
  58969. // Particles Systems
  58970. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58971. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58972. var parsedParticleSystem = parsedData.particleSystems[index];
  58973. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  58974. }
  58975. }
  58976. });
  58977. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  58978. if (parsedParticleSystem.activeParticleCount) {
  58979. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58980. return ps;
  58981. }
  58982. else {
  58983. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58984. return ps;
  58985. }
  58986. });
  58987. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  58988. if (uniformsNames === void 0) { uniformsNames = []; }
  58989. if (samplers === void 0) { samplers = []; }
  58990. if (defines === void 0) { defines = ""; }
  58991. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  58992. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  58993. if (defines.indexOf(" BILLBOARD") === -1) {
  58994. defines += "\n#define BILLBOARD\n";
  58995. }
  58996. if (samplers.indexOf("diffuseSampler") === -1) {
  58997. samplers.push("diffuseSampler");
  58998. }
  58999. return this.createEffect({
  59000. vertex: "particles",
  59001. fragmentElement: fragmentName
  59002. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  59003. };
  59004. })(BABYLON || (BABYLON = {}));
  59005. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  59006. var BABYLON;
  59007. (function (BABYLON) {
  59008. /**
  59009. * Type of sub emitter
  59010. */
  59011. var SubEmitterType;
  59012. (function (SubEmitterType) {
  59013. /**
  59014. * Attached to the particle over it's lifetime
  59015. */
  59016. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  59017. /**
  59018. * Created when the particle dies
  59019. */
  59020. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  59021. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  59022. /**
  59023. * Sub emitter class used to emit particles from an existing particle
  59024. */
  59025. var SubEmitter = /** @class */ (function () {
  59026. /**
  59027. * Creates a sub emitter
  59028. * @param particleSystem the particle system to be used by the sub emitter
  59029. */
  59030. function SubEmitter(
  59031. /**
  59032. * the particle system to be used by the sub emitter
  59033. */
  59034. particleSystem) {
  59035. this.particleSystem = particleSystem;
  59036. /**
  59037. * Type of the submitter (Default: END)
  59038. */
  59039. this.type = SubEmitterType.END;
  59040. /**
  59041. * 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)
  59042. * Note: This only is supported when using an emitter of type Mesh
  59043. */
  59044. this.inheritDirection = false;
  59045. /**
  59046. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  59047. */
  59048. this.inheritedVelocityAmount = 0;
  59049. }
  59050. /**
  59051. * Clones the sub emitter
  59052. * @returns the cloned sub emitter
  59053. */
  59054. SubEmitter.prototype.clone = function () {
  59055. // Clone particle system
  59056. var emitter = this.particleSystem.emitter;
  59057. if (!emitter) {
  59058. emitter = new BABYLON.Vector3();
  59059. }
  59060. else if (emitter instanceof BABYLON.Vector3) {
  59061. emitter = emitter.clone();
  59062. }
  59063. else if (emitter instanceof BABYLON.AbstractMesh) {
  59064. emitter = new BABYLON.Mesh("", emitter._scene);
  59065. }
  59066. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  59067. // Clone properties
  59068. clone.type = this.type;
  59069. clone.inheritDirection = this.inheritDirection;
  59070. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  59071. clone.particleSystem._disposeEmitterOnDispose = true;
  59072. return clone;
  59073. };
  59074. return SubEmitter;
  59075. }());
  59076. BABYLON.SubEmitter = SubEmitter;
  59077. })(BABYLON || (BABYLON = {}));
  59078. //# sourceMappingURL=babylon.subEmitter.js.map
  59079. var BABYLON;
  59080. (function (BABYLON) {
  59081. var ShaderMaterial = /** @class */ (function (_super) {
  59082. __extends(ShaderMaterial, _super);
  59083. function ShaderMaterial(name, scene, shaderPath, options) {
  59084. var _this = _super.call(this, name, scene) || this;
  59085. _this._textures = {};
  59086. _this._textureArrays = {};
  59087. _this._floats = {};
  59088. _this._ints = {};
  59089. _this._floatsArrays = {};
  59090. _this._colors3 = {};
  59091. _this._colors3Arrays = {};
  59092. _this._colors4 = {};
  59093. _this._vectors2 = {};
  59094. _this._vectors3 = {};
  59095. _this._vectors4 = {};
  59096. _this._matrices = {};
  59097. _this._matrices3x3 = {};
  59098. _this._matrices2x2 = {};
  59099. _this._vectors2Arrays = {};
  59100. _this._vectors3Arrays = {};
  59101. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59102. _this._shaderPath = shaderPath;
  59103. options.needAlphaBlending = options.needAlphaBlending || false;
  59104. options.needAlphaTesting = options.needAlphaTesting || false;
  59105. options.attributes = options.attributes || ["position", "normal", "uv"];
  59106. options.uniforms = options.uniforms || ["worldViewProjection"];
  59107. options.uniformBuffers = options.uniformBuffers || [];
  59108. options.samplers = options.samplers || [];
  59109. options.defines = options.defines || [];
  59110. _this._options = options;
  59111. return _this;
  59112. }
  59113. ShaderMaterial.prototype.getClassName = function () {
  59114. return "ShaderMaterial";
  59115. };
  59116. ShaderMaterial.prototype.needAlphaBlending = function () {
  59117. return this._options.needAlphaBlending;
  59118. };
  59119. ShaderMaterial.prototype.needAlphaTesting = function () {
  59120. return this._options.needAlphaTesting;
  59121. };
  59122. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59123. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59124. this._options.uniforms.push(uniformName);
  59125. }
  59126. };
  59127. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59128. if (this._options.samplers.indexOf(name) === -1) {
  59129. this._options.samplers.push(name);
  59130. }
  59131. this._textures[name] = texture;
  59132. return this;
  59133. };
  59134. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59135. if (this._options.samplers.indexOf(name) === -1) {
  59136. this._options.samplers.push(name);
  59137. }
  59138. this._checkUniform(name);
  59139. this._textureArrays[name] = textures;
  59140. return this;
  59141. };
  59142. ShaderMaterial.prototype.setFloat = function (name, value) {
  59143. this._checkUniform(name);
  59144. this._floats[name] = value;
  59145. return this;
  59146. };
  59147. ShaderMaterial.prototype.setInt = function (name, value) {
  59148. this._checkUniform(name);
  59149. this._ints[name] = value;
  59150. return this;
  59151. };
  59152. ShaderMaterial.prototype.setFloats = function (name, value) {
  59153. this._checkUniform(name);
  59154. this._floatsArrays[name] = value;
  59155. return this;
  59156. };
  59157. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59158. this._checkUniform(name);
  59159. this._colors3[name] = value;
  59160. return this;
  59161. };
  59162. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59163. this._checkUniform(name);
  59164. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59165. color.toArray(arr, arr.length);
  59166. return arr;
  59167. }, []);
  59168. return this;
  59169. };
  59170. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59171. this._checkUniform(name);
  59172. this._colors4[name] = value;
  59173. return this;
  59174. };
  59175. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59176. this._checkUniform(name);
  59177. this._vectors2[name] = value;
  59178. return this;
  59179. };
  59180. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59181. this._checkUniform(name);
  59182. this._vectors3[name] = value;
  59183. return this;
  59184. };
  59185. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59186. this._checkUniform(name);
  59187. this._vectors4[name] = value;
  59188. return this;
  59189. };
  59190. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59191. this._checkUniform(name);
  59192. this._matrices[name] = value;
  59193. return this;
  59194. };
  59195. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59196. this._checkUniform(name);
  59197. this._matrices3x3[name] = value;
  59198. return this;
  59199. };
  59200. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59201. this._checkUniform(name);
  59202. this._matrices2x2[name] = value;
  59203. return this;
  59204. };
  59205. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59206. this._checkUniform(name);
  59207. this._vectors2Arrays[name] = value;
  59208. return this;
  59209. };
  59210. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59211. this._checkUniform(name);
  59212. this._vectors3Arrays[name] = value;
  59213. return this;
  59214. };
  59215. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59216. if (!mesh) {
  59217. return true;
  59218. }
  59219. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59220. return false;
  59221. }
  59222. return false;
  59223. };
  59224. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59225. var scene = this.getScene();
  59226. var engine = scene.getEngine();
  59227. if (!this.checkReadyOnEveryCall) {
  59228. if (this._renderId === scene.getRenderId()) {
  59229. if (this._checkCache(scene, mesh, useInstances)) {
  59230. return true;
  59231. }
  59232. }
  59233. }
  59234. // Instances
  59235. var defines = [];
  59236. var attribs = [];
  59237. var fallbacks = new BABYLON.EffectFallbacks();
  59238. if (useInstances) {
  59239. defines.push("#define INSTANCES");
  59240. }
  59241. for (var index = 0; index < this._options.defines.length; index++) {
  59242. defines.push(this._options.defines[index]);
  59243. }
  59244. for (var index = 0; index < this._options.attributes.length; index++) {
  59245. attribs.push(this._options.attributes[index]);
  59246. }
  59247. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59248. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59249. defines.push("#define VERTEXCOLOR");
  59250. }
  59251. // Bones
  59252. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59253. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59254. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59255. if (mesh.numBoneInfluencers > 4) {
  59256. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59257. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59258. }
  59259. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59260. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59261. fallbacks.addCPUSkinningFallback(0, mesh);
  59262. if (this._options.uniforms.indexOf("mBones") === -1) {
  59263. this._options.uniforms.push("mBones");
  59264. }
  59265. }
  59266. else {
  59267. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59268. }
  59269. // Textures
  59270. for (var name in this._textures) {
  59271. if (!this._textures[name].isReady()) {
  59272. return false;
  59273. }
  59274. }
  59275. // Alpha test
  59276. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59277. defines.push("#define ALPHATEST");
  59278. }
  59279. var previousEffect = this._effect;
  59280. var join = defines.join("\n");
  59281. this._effect = engine.createEffect(this._shaderPath, {
  59282. attributes: attribs,
  59283. uniformsNames: this._options.uniforms,
  59284. uniformBuffersNames: this._options.uniformBuffers,
  59285. samplers: this._options.samplers,
  59286. defines: join,
  59287. fallbacks: fallbacks,
  59288. onCompiled: this.onCompiled,
  59289. onError: this.onError
  59290. }, engine);
  59291. if (!this._effect.isReady()) {
  59292. return false;
  59293. }
  59294. if (previousEffect !== this._effect) {
  59295. scene.resetCachedMaterial();
  59296. }
  59297. this._renderId = scene.getRenderId();
  59298. return true;
  59299. };
  59300. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59301. var scene = this.getScene();
  59302. if (!this._effect) {
  59303. return;
  59304. }
  59305. if (this._options.uniforms.indexOf("world") !== -1) {
  59306. this._effect.setMatrix("world", world);
  59307. }
  59308. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59309. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59310. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59311. }
  59312. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59313. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59314. }
  59315. };
  59316. ShaderMaterial.prototype.bind = function (world, mesh) {
  59317. // Std values
  59318. this.bindOnlyWorldMatrix(world);
  59319. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59320. if (this._options.uniforms.indexOf("view") !== -1) {
  59321. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59322. }
  59323. if (this._options.uniforms.indexOf("projection") !== -1) {
  59324. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59325. }
  59326. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59327. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59328. }
  59329. // Bones
  59330. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59331. var name;
  59332. // Texture
  59333. for (name in this._textures) {
  59334. this._effect.setTexture(name, this._textures[name]);
  59335. }
  59336. // Texture arrays
  59337. for (name in this._textureArrays) {
  59338. this._effect.setTextureArray(name, this._textureArrays[name]);
  59339. }
  59340. // Int
  59341. for (name in this._ints) {
  59342. this._effect.setInt(name, this._ints[name]);
  59343. }
  59344. // Float
  59345. for (name in this._floats) {
  59346. this._effect.setFloat(name, this._floats[name]);
  59347. }
  59348. // Floats
  59349. for (name in this._floatsArrays) {
  59350. this._effect.setArray(name, this._floatsArrays[name]);
  59351. }
  59352. // Color3
  59353. for (name in this._colors3) {
  59354. this._effect.setColor3(name, this._colors3[name]);
  59355. }
  59356. for (name in this._colors3Arrays) {
  59357. this._effect.setArray3(name, this._colors3Arrays[name]);
  59358. }
  59359. // Color4
  59360. for (name in this._colors4) {
  59361. var color = this._colors4[name];
  59362. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59363. }
  59364. // Vector2
  59365. for (name in this._vectors2) {
  59366. this._effect.setVector2(name, this._vectors2[name]);
  59367. }
  59368. // Vector3
  59369. for (name in this._vectors3) {
  59370. this._effect.setVector3(name, this._vectors3[name]);
  59371. }
  59372. // Vector4
  59373. for (name in this._vectors4) {
  59374. this._effect.setVector4(name, this._vectors4[name]);
  59375. }
  59376. // Matrix
  59377. for (name in this._matrices) {
  59378. this._effect.setMatrix(name, this._matrices[name]);
  59379. }
  59380. // Matrix 3x3
  59381. for (name in this._matrices3x3) {
  59382. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59383. }
  59384. // Matrix 2x2
  59385. for (name in this._matrices2x2) {
  59386. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59387. }
  59388. // Vector2Array
  59389. for (name in this._vectors2Arrays) {
  59390. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59391. }
  59392. // Vector3Array
  59393. for (name in this._vectors3Arrays) {
  59394. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59395. }
  59396. }
  59397. this._afterBind(mesh);
  59398. };
  59399. ShaderMaterial.prototype.getActiveTextures = function () {
  59400. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59401. for (var name in this._textures) {
  59402. activeTextures.push(this._textures[name]);
  59403. }
  59404. for (var name in this._textureArrays) {
  59405. var array = this._textureArrays[name];
  59406. for (var index = 0; index < array.length; index++) {
  59407. activeTextures.push(array[index]);
  59408. }
  59409. }
  59410. return activeTextures;
  59411. };
  59412. ShaderMaterial.prototype.hasTexture = function (texture) {
  59413. if (_super.prototype.hasTexture.call(this, texture)) {
  59414. return true;
  59415. }
  59416. for (var name in this._textures) {
  59417. if (this._textures[name] === texture) {
  59418. return true;
  59419. }
  59420. }
  59421. for (var name in this._textureArrays) {
  59422. var array = this._textureArrays[name];
  59423. for (var index = 0; index < array.length; index++) {
  59424. if (array[index] === texture) {
  59425. return true;
  59426. }
  59427. }
  59428. }
  59429. return false;
  59430. };
  59431. ShaderMaterial.prototype.clone = function (name) {
  59432. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59433. return newShaderMaterial;
  59434. };
  59435. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59436. if (forceDisposeTextures) {
  59437. var name;
  59438. for (name in this._textures) {
  59439. this._textures[name].dispose();
  59440. }
  59441. for (name in this._textureArrays) {
  59442. var array = this._textureArrays[name];
  59443. for (var index = 0; index < array.length; index++) {
  59444. array[index].dispose();
  59445. }
  59446. }
  59447. }
  59448. this._textures = {};
  59449. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59450. };
  59451. ShaderMaterial.prototype.serialize = function () {
  59452. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59453. serializationObject.customType = "BABYLON.ShaderMaterial";
  59454. serializationObject.options = this._options;
  59455. serializationObject.shaderPath = this._shaderPath;
  59456. var name;
  59457. // Texture
  59458. serializationObject.textures = {};
  59459. for (name in this._textures) {
  59460. serializationObject.textures[name] = this._textures[name].serialize();
  59461. }
  59462. // Texture arrays
  59463. serializationObject.textureArrays = {};
  59464. for (name in this._textureArrays) {
  59465. serializationObject.textureArrays[name] = [];
  59466. var array = this._textureArrays[name];
  59467. for (var index = 0; index < array.length; index++) {
  59468. serializationObject.textureArrays[name].push(array[index].serialize());
  59469. }
  59470. }
  59471. // Float
  59472. serializationObject.floats = {};
  59473. for (name in this._floats) {
  59474. serializationObject.floats[name] = this._floats[name];
  59475. }
  59476. // Float s
  59477. serializationObject.FloatArrays = {};
  59478. for (name in this._floatsArrays) {
  59479. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59480. }
  59481. // Color3
  59482. serializationObject.colors3 = {};
  59483. for (name in this._colors3) {
  59484. serializationObject.colors3[name] = this._colors3[name].asArray();
  59485. }
  59486. // Color3 array
  59487. serializationObject.colors3Arrays = {};
  59488. for (name in this._colors3Arrays) {
  59489. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59490. }
  59491. // Color4
  59492. serializationObject.colors4 = {};
  59493. for (name in this._colors4) {
  59494. serializationObject.colors4[name] = this._colors4[name].asArray();
  59495. }
  59496. // Vector2
  59497. serializationObject.vectors2 = {};
  59498. for (name in this._vectors2) {
  59499. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59500. }
  59501. // Vector3
  59502. serializationObject.vectors3 = {};
  59503. for (name in this._vectors3) {
  59504. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59505. }
  59506. // Vector4
  59507. serializationObject.vectors4 = {};
  59508. for (name in this._vectors4) {
  59509. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59510. }
  59511. // Matrix
  59512. serializationObject.matrices = {};
  59513. for (name in this._matrices) {
  59514. serializationObject.matrices[name] = this._matrices[name].asArray();
  59515. }
  59516. // Matrix 3x3
  59517. serializationObject.matrices3x3 = {};
  59518. for (name in this._matrices3x3) {
  59519. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59520. }
  59521. // Matrix 2x2
  59522. serializationObject.matrices2x2 = {};
  59523. for (name in this._matrices2x2) {
  59524. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59525. }
  59526. // Vector2Array
  59527. serializationObject.vectors2Arrays = {};
  59528. for (name in this._vectors2Arrays) {
  59529. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59530. }
  59531. // Vector3Array
  59532. serializationObject.vectors3Arrays = {};
  59533. for (name in this._vectors3Arrays) {
  59534. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59535. }
  59536. return serializationObject;
  59537. };
  59538. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59539. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59540. var name;
  59541. // Texture
  59542. for (name in source.textures) {
  59543. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59544. }
  59545. // Texture arrays
  59546. for (name in source.textureArrays) {
  59547. var array = source.textureArrays[name];
  59548. var textureArray = new Array();
  59549. for (var index = 0; index < array.length; index++) {
  59550. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59551. }
  59552. material.setTextureArray(name, textureArray);
  59553. }
  59554. // Float
  59555. for (name in source.floats) {
  59556. material.setFloat(name, source.floats[name]);
  59557. }
  59558. // Float s
  59559. for (name in source.floatsArrays) {
  59560. material.setFloats(name, source.floatsArrays[name]);
  59561. }
  59562. // Color3
  59563. for (name in source.colors3) {
  59564. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59565. }
  59566. // Color3 arrays
  59567. for (name in source.colors3Arrays) {
  59568. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59569. if (i % 3 === 0) {
  59570. arr.push([num]);
  59571. }
  59572. else {
  59573. arr[arr.length - 1].push(num);
  59574. }
  59575. return arr;
  59576. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59577. material.setColor3Array(name, colors);
  59578. }
  59579. // Color4
  59580. for (name in source.colors4) {
  59581. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59582. }
  59583. // Vector2
  59584. for (name in source.vectors2) {
  59585. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59586. }
  59587. // Vector3
  59588. for (name in source.vectors3) {
  59589. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59590. }
  59591. // Vector4
  59592. for (name in source.vectors4) {
  59593. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59594. }
  59595. // Matrix
  59596. for (name in source.matrices) {
  59597. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59598. }
  59599. // Matrix 3x3
  59600. for (name in source.matrices3x3) {
  59601. material.setMatrix3x3(name, source.matrices3x3[name]);
  59602. }
  59603. // Matrix 2x2
  59604. for (name in source.matrices2x2) {
  59605. material.setMatrix2x2(name, source.matrices2x2[name]);
  59606. }
  59607. // Vector2Array
  59608. for (name in source.vectors2Arrays) {
  59609. material.setArray2(name, source.vectors2Arrays[name]);
  59610. }
  59611. // Vector3Array
  59612. for (name in source.vectors3Arrays) {
  59613. material.setArray3(name, source.vectors3Arrays[name]);
  59614. }
  59615. return material;
  59616. };
  59617. return ShaderMaterial;
  59618. }(BABYLON.Material));
  59619. BABYLON.ShaderMaterial = ShaderMaterial;
  59620. })(BABYLON || (BABYLON = {}));
  59621. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59622. var BABYLON;
  59623. (function (BABYLON) {
  59624. var GroundMesh = /** @class */ (function (_super) {
  59625. __extends(GroundMesh, _super);
  59626. function GroundMesh(name, scene) {
  59627. var _this = _super.call(this, name, scene) || this;
  59628. _this.generateOctree = false;
  59629. return _this;
  59630. }
  59631. GroundMesh.prototype.getClassName = function () {
  59632. return "GroundMesh";
  59633. };
  59634. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59635. get: function () {
  59636. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59637. },
  59638. enumerable: true,
  59639. configurable: true
  59640. });
  59641. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59642. get: function () {
  59643. return this._subdivisionsX;
  59644. },
  59645. enumerable: true,
  59646. configurable: true
  59647. });
  59648. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59649. get: function () {
  59650. return this._subdivisionsY;
  59651. },
  59652. enumerable: true,
  59653. configurable: true
  59654. });
  59655. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59656. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59657. this._subdivisionsX = chunksCount;
  59658. this._subdivisionsY = chunksCount;
  59659. this.subdivide(chunksCount);
  59660. // Call the octree system optimization if it is defined.
  59661. var thisAsAny = this;
  59662. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  59663. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59664. }
  59665. };
  59666. /**
  59667. * Returns a height (y) value in the Worl system :
  59668. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59669. * Returns the ground y position if (x, z) are outside the ground surface.
  59670. */
  59671. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59672. var world = this.getWorldMatrix();
  59673. var invMat = BABYLON.Tmp.Matrix[5];
  59674. world.invertToRef(invMat);
  59675. var tmpVect = BABYLON.Tmp.Vector3[8];
  59676. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59677. x = tmpVect.x;
  59678. z = tmpVect.z;
  59679. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59680. return this.position.y;
  59681. }
  59682. if (!this._heightQuads || this._heightQuads.length == 0) {
  59683. this._initHeightQuads();
  59684. this._computeHeightQuads();
  59685. }
  59686. var facet = this._getFacetAt(x, z);
  59687. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59688. // return y in the World system
  59689. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59690. return tmpVect.y;
  59691. };
  59692. /**
  59693. * Returns a normalized vector (Vector3) orthogonal to the ground
  59694. * at the ground coordinates (x, z) expressed in the World system.
  59695. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59696. */
  59697. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59698. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59699. this.getNormalAtCoordinatesToRef(x, z, normal);
  59700. return normal;
  59701. };
  59702. /**
  59703. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59704. * at the ground coordinates (x, z) expressed in the World system.
  59705. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59706. * Returns the GroundMesh.
  59707. */
  59708. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59709. var world = this.getWorldMatrix();
  59710. var tmpMat = BABYLON.Tmp.Matrix[5];
  59711. world.invertToRef(tmpMat);
  59712. var tmpVect = BABYLON.Tmp.Vector3[8];
  59713. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59714. x = tmpVect.x;
  59715. z = tmpVect.z;
  59716. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59717. return this;
  59718. }
  59719. if (!this._heightQuads || this._heightQuads.length == 0) {
  59720. this._initHeightQuads();
  59721. this._computeHeightQuads();
  59722. }
  59723. var facet = this._getFacetAt(x, z);
  59724. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59725. return this;
  59726. };
  59727. /**
  59728. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59729. * if the ground has been updated.
  59730. * This can be used in the render loop.
  59731. * Returns the GroundMesh.
  59732. */
  59733. GroundMesh.prototype.updateCoordinateHeights = function () {
  59734. if (!this._heightQuads || this._heightQuads.length == 0) {
  59735. this._initHeightQuads();
  59736. }
  59737. this._computeHeightQuads();
  59738. return this;
  59739. };
  59740. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59741. GroundMesh.prototype._getFacetAt = function (x, z) {
  59742. // retrieve col and row from x, z coordinates in the ground local system
  59743. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59744. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59745. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59746. var facet;
  59747. if (z < quad.slope.x * x + quad.slope.y) {
  59748. facet = quad.facet1;
  59749. }
  59750. else {
  59751. facet = quad.facet2;
  59752. }
  59753. return facet;
  59754. };
  59755. // Creates and populates the heightMap array with "facet" elements :
  59756. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59757. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59758. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59759. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59760. // Returns the GroundMesh.
  59761. GroundMesh.prototype._initHeightQuads = function () {
  59762. var subdivisionsX = this._subdivisionsX;
  59763. var subdivisionsY = this._subdivisionsY;
  59764. this._heightQuads = new Array();
  59765. for (var row = 0; row < subdivisionsY; row++) {
  59766. for (var col = 0; col < subdivisionsX; col++) {
  59767. 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) };
  59768. this._heightQuads[row * subdivisionsX + col] = quad;
  59769. }
  59770. }
  59771. return this;
  59772. };
  59773. // Compute each quad element values and update the the heightMap array :
  59774. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59775. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59776. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59777. // Returns the GroundMesh.
  59778. GroundMesh.prototype._computeHeightQuads = function () {
  59779. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59780. if (!positions) {
  59781. return this;
  59782. }
  59783. var v1 = BABYLON.Tmp.Vector3[3];
  59784. var v2 = BABYLON.Tmp.Vector3[2];
  59785. var v3 = BABYLON.Tmp.Vector3[1];
  59786. var v4 = BABYLON.Tmp.Vector3[0];
  59787. var v1v2 = BABYLON.Tmp.Vector3[4];
  59788. var v1v3 = BABYLON.Tmp.Vector3[5];
  59789. var v1v4 = BABYLON.Tmp.Vector3[6];
  59790. var norm1 = BABYLON.Tmp.Vector3[7];
  59791. var norm2 = BABYLON.Tmp.Vector3[8];
  59792. var i = 0;
  59793. var j = 0;
  59794. var k = 0;
  59795. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59796. var h = 0;
  59797. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59798. var d2 = 0;
  59799. var subdivisionsX = this._subdivisionsX;
  59800. var subdivisionsY = this._subdivisionsY;
  59801. for (var row = 0; row < subdivisionsY; row++) {
  59802. for (var col = 0; col < subdivisionsX; col++) {
  59803. i = col * 3;
  59804. j = row * (subdivisionsX + 1) * 3;
  59805. k = (row + 1) * (subdivisionsX + 1) * 3;
  59806. v1.x = positions[j + i];
  59807. v1.y = positions[j + i + 1];
  59808. v1.z = positions[j + i + 2];
  59809. v2.x = positions[j + i + 3];
  59810. v2.y = positions[j + i + 4];
  59811. v2.z = positions[j + i + 5];
  59812. v3.x = positions[k + i];
  59813. v3.y = positions[k + i + 1];
  59814. v3.z = positions[k + i + 2];
  59815. v4.x = positions[k + i + 3];
  59816. v4.y = positions[k + i + 4];
  59817. v4.z = positions[k + i + 5];
  59818. // 2D slope V1V4
  59819. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59820. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59821. // facet equations :
  59822. // we compute each facet normal vector
  59823. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59824. // we compute the value d by applying the equation to v1 which belongs to the plane
  59825. // then we store the facet equation in a Vector4
  59826. v2.subtractToRef(v1, v1v2);
  59827. v3.subtractToRef(v1, v1v3);
  59828. v4.subtractToRef(v1, v1v4);
  59829. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59830. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59831. norm1.normalize();
  59832. norm2.normalize();
  59833. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59834. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59835. var quad = this._heightQuads[row * subdivisionsX + col];
  59836. quad.slope.copyFromFloats(cd, h);
  59837. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59838. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59839. }
  59840. }
  59841. return this;
  59842. };
  59843. GroundMesh.prototype.serialize = function (serializationObject) {
  59844. _super.prototype.serialize.call(this, serializationObject);
  59845. serializationObject.subdivisionsX = this._subdivisionsX;
  59846. serializationObject.subdivisionsY = this._subdivisionsY;
  59847. serializationObject.minX = this._minX;
  59848. serializationObject.maxX = this._maxX;
  59849. serializationObject.minZ = this._minZ;
  59850. serializationObject.maxZ = this._maxZ;
  59851. serializationObject.width = this._width;
  59852. serializationObject.height = this._height;
  59853. };
  59854. GroundMesh.Parse = function (parsedMesh, scene) {
  59855. var result = new GroundMesh(parsedMesh.name, scene);
  59856. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59857. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59858. result._minX = parsedMesh.minX;
  59859. result._maxX = parsedMesh.maxX;
  59860. result._minZ = parsedMesh.minZ;
  59861. result._maxZ = parsedMesh.maxZ;
  59862. result._width = parsedMesh.width;
  59863. result._height = parsedMesh.height;
  59864. return result;
  59865. };
  59866. return GroundMesh;
  59867. }(BABYLON.Mesh));
  59868. BABYLON.GroundMesh = GroundMesh;
  59869. })(BABYLON || (BABYLON = {}));
  59870. //# sourceMappingURL=babylon.groundMesh.js.map
  59871. var BABYLON;
  59872. (function (BABYLON) {
  59873. /**
  59874. * Creates an instance based on a source mesh.
  59875. */
  59876. var InstancedMesh = /** @class */ (function (_super) {
  59877. __extends(InstancedMesh, _super);
  59878. function InstancedMesh(name, source) {
  59879. var _this = _super.call(this, name, source.getScene()) || this;
  59880. source.instances.push(_this);
  59881. _this._sourceMesh = source;
  59882. _this.position.copyFrom(source.position);
  59883. _this.rotation.copyFrom(source.rotation);
  59884. _this.scaling.copyFrom(source.scaling);
  59885. if (source.rotationQuaternion) {
  59886. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59887. }
  59888. _this.infiniteDistance = source.infiniteDistance;
  59889. _this.setPivotMatrix(source.getPivotMatrix());
  59890. _this.refreshBoundingInfo();
  59891. _this._syncSubMeshes();
  59892. return _this;
  59893. }
  59894. /**
  59895. * Returns the string "InstancedMesh".
  59896. */
  59897. InstancedMesh.prototype.getClassName = function () {
  59898. return "InstancedMesh";
  59899. };
  59900. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59901. // Methods
  59902. get: function () {
  59903. return this._sourceMesh.receiveShadows;
  59904. },
  59905. enumerable: true,
  59906. configurable: true
  59907. });
  59908. Object.defineProperty(InstancedMesh.prototype, "material", {
  59909. get: function () {
  59910. return this._sourceMesh.material;
  59911. },
  59912. enumerable: true,
  59913. configurable: true
  59914. });
  59915. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59916. get: function () {
  59917. return this._sourceMesh.visibility;
  59918. },
  59919. enumerable: true,
  59920. configurable: true
  59921. });
  59922. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59923. get: function () {
  59924. return this._sourceMesh.skeleton;
  59925. },
  59926. enumerable: true,
  59927. configurable: true
  59928. });
  59929. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59930. get: function () {
  59931. return this._sourceMesh.renderingGroupId;
  59932. },
  59933. set: function (value) {
  59934. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59935. return;
  59936. }
  59937. //no-op with warning
  59938. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59939. },
  59940. enumerable: true,
  59941. configurable: true
  59942. });
  59943. /**
  59944. * Returns the total number of vertices (integer).
  59945. */
  59946. InstancedMesh.prototype.getTotalVertices = function () {
  59947. return this._sourceMesh.getTotalVertices();
  59948. };
  59949. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59950. get: function () {
  59951. return this._sourceMesh;
  59952. },
  59953. enumerable: true,
  59954. configurable: true
  59955. });
  59956. /**
  59957. * Is this node ready to be used/rendered
  59958. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59959. * @return {boolean} is it ready
  59960. */
  59961. InstancedMesh.prototype.isReady = function (completeCheck) {
  59962. if (completeCheck === void 0) { completeCheck = false; }
  59963. return this._sourceMesh.isReady(completeCheck, true);
  59964. };
  59965. /**
  59966. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59967. */
  59968. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59969. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59970. };
  59971. /**
  59972. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59973. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59974. * The `data` are either a numeric array either a Float32Array.
  59975. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59976. * 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).
  59977. * Note that a new underlying VertexBuffer object is created each call.
  59978. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59979. *
  59980. * Possible `kind` values :
  59981. * - BABYLON.VertexBuffer.PositionKind
  59982. * - BABYLON.VertexBuffer.UVKind
  59983. * - BABYLON.VertexBuffer.UV2Kind
  59984. * - BABYLON.VertexBuffer.UV3Kind
  59985. * - BABYLON.VertexBuffer.UV4Kind
  59986. * - BABYLON.VertexBuffer.UV5Kind
  59987. * - BABYLON.VertexBuffer.UV6Kind
  59988. * - BABYLON.VertexBuffer.ColorKind
  59989. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59990. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59991. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59992. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59993. *
  59994. * Returns the Mesh.
  59995. */
  59996. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59997. if (this.sourceMesh) {
  59998. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59999. }
  60000. return this.sourceMesh;
  60001. };
  60002. /**
  60003. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60004. * If the mesh has no geometry, it is simply returned as it is.
  60005. * The `data` are either a numeric array either a Float32Array.
  60006. * No new underlying VertexBuffer object is created.
  60007. * 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.
  60008. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60009. *
  60010. * Possible `kind` values :
  60011. * - BABYLON.VertexBuffer.PositionKind
  60012. * - BABYLON.VertexBuffer.UVKind
  60013. * - BABYLON.VertexBuffer.UV2Kind
  60014. * - BABYLON.VertexBuffer.UV3Kind
  60015. * - BABYLON.VertexBuffer.UV4Kind
  60016. * - BABYLON.VertexBuffer.UV5Kind
  60017. * - BABYLON.VertexBuffer.UV6Kind
  60018. * - BABYLON.VertexBuffer.ColorKind
  60019. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60020. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60021. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60022. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60023. *
  60024. * Returns the Mesh.
  60025. */
  60026. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60027. if (this.sourceMesh) {
  60028. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60029. }
  60030. return this.sourceMesh;
  60031. };
  60032. /**
  60033. * Sets the mesh indices.
  60034. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60035. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60036. * This method creates a new index buffer each call.
  60037. * Returns the Mesh.
  60038. */
  60039. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60040. if (totalVertices === void 0) { totalVertices = null; }
  60041. if (this.sourceMesh) {
  60042. this.sourceMesh.setIndices(indices, totalVertices);
  60043. }
  60044. return this.sourceMesh;
  60045. };
  60046. /**
  60047. * Boolean : True if the mesh owns the requested kind of data.
  60048. */
  60049. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60050. return this._sourceMesh.isVerticesDataPresent(kind);
  60051. };
  60052. /**
  60053. * Returns an array of indices (IndicesArray).
  60054. */
  60055. InstancedMesh.prototype.getIndices = function () {
  60056. return this._sourceMesh.getIndices();
  60057. };
  60058. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60059. get: function () {
  60060. return this._sourceMesh._positions;
  60061. },
  60062. enumerable: true,
  60063. configurable: true
  60064. });
  60065. /**
  60066. * Sets a new updated BoundingInfo to the mesh.
  60067. * Returns the mesh.
  60068. */
  60069. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60070. var meshBB = this._sourceMesh.getBoundingInfo();
  60071. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60072. this._updateBoundingInfo();
  60073. return this;
  60074. };
  60075. /** @hidden */
  60076. InstancedMesh.prototype._preActivate = function () {
  60077. if (this._currentLOD) {
  60078. this._currentLOD._preActivate();
  60079. }
  60080. return this;
  60081. };
  60082. /** @hidden */
  60083. InstancedMesh.prototype._activate = function (renderId) {
  60084. if (this._currentLOD) {
  60085. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60086. }
  60087. return this;
  60088. };
  60089. /**
  60090. * Returns the current associated LOD AbstractMesh.
  60091. */
  60092. InstancedMesh.prototype.getLOD = function (camera) {
  60093. if (!camera) {
  60094. return this;
  60095. }
  60096. var boundingInfo = this.getBoundingInfo();
  60097. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60098. if (this._currentLOD === this.sourceMesh) {
  60099. return this;
  60100. }
  60101. return this._currentLOD;
  60102. };
  60103. /** @hidden */
  60104. InstancedMesh.prototype._syncSubMeshes = function () {
  60105. this.releaseSubMeshes();
  60106. if (this._sourceMesh.subMeshes) {
  60107. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60108. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60109. }
  60110. }
  60111. return this;
  60112. };
  60113. /** @hidden */
  60114. InstancedMesh.prototype._generatePointsArray = function () {
  60115. return this._sourceMesh._generatePointsArray();
  60116. };
  60117. /**
  60118. * Creates a new InstancedMesh from the current mesh.
  60119. * - name (string) : the cloned mesh name
  60120. * - newParent (optional Node) : the optional Node to parent the clone to.
  60121. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60122. *
  60123. * Returns the clone.
  60124. */
  60125. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60126. var result = this._sourceMesh.createInstance(name);
  60127. // Deep copy
  60128. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60129. // Bounding info
  60130. this.refreshBoundingInfo();
  60131. // Parent
  60132. if (newParent) {
  60133. result.parent = newParent;
  60134. }
  60135. if (!doNotCloneChildren) {
  60136. // Children
  60137. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60138. var mesh = this.getScene().meshes[index];
  60139. if (mesh.parent === this) {
  60140. mesh.clone(mesh.name, result);
  60141. }
  60142. }
  60143. }
  60144. result.computeWorldMatrix(true);
  60145. return result;
  60146. };
  60147. /**
  60148. * Disposes the InstancedMesh.
  60149. * Returns nothing.
  60150. */
  60151. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60152. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60153. // Remove from mesh
  60154. var index = this._sourceMesh.instances.indexOf(this);
  60155. this._sourceMesh.instances.splice(index, 1);
  60156. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60157. };
  60158. return InstancedMesh;
  60159. }(BABYLON.AbstractMesh));
  60160. BABYLON.InstancedMesh = InstancedMesh;
  60161. })(BABYLON || (BABYLON = {}));
  60162. //# sourceMappingURL=babylon.instancedMesh.js.map
  60163. var BABYLON;
  60164. (function (BABYLON) {
  60165. var LinesMesh = /** @class */ (function (_super) {
  60166. __extends(LinesMesh, _super);
  60167. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60168. if (scene === void 0) { scene = null; }
  60169. if (parent === void 0) { parent = null; }
  60170. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60171. _this.useVertexColor = useVertexColor;
  60172. _this.useVertexAlpha = useVertexAlpha;
  60173. _this.color = new BABYLON.Color3(1, 1, 1);
  60174. _this.alpha = 1;
  60175. if (source) {
  60176. _this.color = source.color.clone();
  60177. _this.alpha = source.alpha;
  60178. _this.useVertexColor = source.useVertexColor;
  60179. _this.useVertexAlpha = source.useVertexAlpha;
  60180. }
  60181. _this._intersectionThreshold = 0.1;
  60182. var defines = [];
  60183. var options = {
  60184. attributes: [BABYLON.VertexBuffer.PositionKind],
  60185. uniforms: ["world", "viewProjection"],
  60186. needAlphaBlending: true,
  60187. defines: defines
  60188. };
  60189. if (useVertexAlpha === false) {
  60190. options.needAlphaBlending = false;
  60191. }
  60192. if (!useVertexColor) {
  60193. options.uniforms.push("color");
  60194. }
  60195. else {
  60196. options.defines.push("#define VERTEXCOLOR");
  60197. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60198. }
  60199. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60200. return _this;
  60201. }
  60202. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60203. /**
  60204. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60205. * This margin is expressed in world space coordinates, so its value may vary.
  60206. * Default value is 0.1
  60207. * @returns the intersection Threshold value.
  60208. */
  60209. get: function () {
  60210. return this._intersectionThreshold;
  60211. },
  60212. /**
  60213. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60214. * This margin is expressed in world space coordinates, so its value may vary.
  60215. * @param value the new threshold to apply
  60216. */
  60217. set: function (value) {
  60218. if (this._intersectionThreshold === value) {
  60219. return;
  60220. }
  60221. this._intersectionThreshold = value;
  60222. if (this.geometry) {
  60223. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60224. }
  60225. },
  60226. enumerable: true,
  60227. configurable: true
  60228. });
  60229. /**
  60230. * Returns the string "LineMesh"
  60231. */
  60232. LinesMesh.prototype.getClassName = function () {
  60233. return "LinesMesh";
  60234. };
  60235. Object.defineProperty(LinesMesh.prototype, "material", {
  60236. /**
  60237. * @hidden
  60238. */
  60239. get: function () {
  60240. return this._colorShader;
  60241. },
  60242. /**
  60243. * @hidden
  60244. */
  60245. set: function (value) {
  60246. // Do nothing
  60247. },
  60248. enumerable: true,
  60249. configurable: true
  60250. });
  60251. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60252. /**
  60253. * @hidden
  60254. */
  60255. get: function () {
  60256. return false;
  60257. },
  60258. enumerable: true,
  60259. configurable: true
  60260. });
  60261. LinesMesh.prototype.createInstance = function (name) {
  60262. throw new Error("LinesMeshes do not support createInstance.");
  60263. };
  60264. /** @hidden */
  60265. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60266. if (!this._geometry) {
  60267. return this;
  60268. }
  60269. // VBOs
  60270. this._geometry._bind(this._colorShader.getEffect());
  60271. // Color
  60272. if (!this.useVertexColor) {
  60273. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60274. }
  60275. return this;
  60276. };
  60277. /** @hidden */
  60278. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60279. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60280. return this;
  60281. }
  60282. var engine = this.getScene().getEngine();
  60283. // Draw order
  60284. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60285. return this;
  60286. };
  60287. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60288. this._colorShader.dispose();
  60289. _super.prototype.dispose.call(this, doNotRecurse);
  60290. };
  60291. /**
  60292. * Returns a new LineMesh object cloned from the current one.
  60293. */
  60294. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60295. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60296. };
  60297. return LinesMesh;
  60298. }(BABYLON.Mesh));
  60299. BABYLON.LinesMesh = LinesMesh;
  60300. })(BABYLON || (BABYLON = {}));
  60301. //# sourceMappingURL=babylon.linesMesh.js.map
  60302. var BABYLON;
  60303. (function (BABYLON) {
  60304. /**
  60305. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60306. * The underlying implementation relies on an associative array to ensure the best performances.
  60307. * The value can be anything including 'null' but except 'undefined'
  60308. */
  60309. var StringDictionary = /** @class */ (function () {
  60310. function StringDictionary() {
  60311. this._count = 0;
  60312. this._data = {};
  60313. }
  60314. /**
  60315. * This will clear this dictionary and copy the content from the 'source' one.
  60316. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60317. * @param source the dictionary to take the content from and copy to this dictionary
  60318. */
  60319. StringDictionary.prototype.copyFrom = function (source) {
  60320. var _this = this;
  60321. this.clear();
  60322. source.forEach(function (t, v) { return _this.add(t, v); });
  60323. };
  60324. /**
  60325. * Get a value based from its key
  60326. * @param key the given key to get the matching value from
  60327. * @return the value if found, otherwise undefined is returned
  60328. */
  60329. StringDictionary.prototype.get = function (key) {
  60330. var val = this._data[key];
  60331. if (val !== undefined) {
  60332. return val;
  60333. }
  60334. return undefined;
  60335. };
  60336. /**
  60337. * Get a value from its key or add it if it doesn't exist.
  60338. * This method will ensure you that a given key/data will be present in the dictionary.
  60339. * @param key the given key to get the matching value from
  60340. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60341. * The factory will only be invoked if there's no data for the given key.
  60342. * @return the value corresponding to the key.
  60343. */
  60344. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60345. var val = this.get(key);
  60346. if (val !== undefined) {
  60347. return val;
  60348. }
  60349. val = factory(key);
  60350. if (val) {
  60351. this.add(key, val);
  60352. }
  60353. return val;
  60354. };
  60355. /**
  60356. * Get a value from its key if present in the dictionary otherwise add it
  60357. * @param key the key to get the value from
  60358. * @param val if there's no such key/value pair in the dictionary add it with this value
  60359. * @return the value corresponding to the key
  60360. */
  60361. StringDictionary.prototype.getOrAdd = function (key, val) {
  60362. var curVal = this.get(key);
  60363. if (curVal !== undefined) {
  60364. return curVal;
  60365. }
  60366. this.add(key, val);
  60367. return val;
  60368. };
  60369. /**
  60370. * Check if there's a given key in the dictionary
  60371. * @param key the key to check for
  60372. * @return true if the key is present, false otherwise
  60373. */
  60374. StringDictionary.prototype.contains = function (key) {
  60375. return this._data[key] !== undefined;
  60376. };
  60377. /**
  60378. * Add a new key and its corresponding value
  60379. * @param key the key to add
  60380. * @param value the value corresponding to the key
  60381. * @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
  60382. */
  60383. StringDictionary.prototype.add = function (key, value) {
  60384. if (this._data[key] !== undefined) {
  60385. return false;
  60386. }
  60387. this._data[key] = value;
  60388. ++this._count;
  60389. return true;
  60390. };
  60391. StringDictionary.prototype.set = function (key, value) {
  60392. if (this._data[key] === undefined) {
  60393. return false;
  60394. }
  60395. this._data[key] = value;
  60396. return true;
  60397. };
  60398. /**
  60399. * Get the element of the given key and remove it from the dictionary
  60400. * @param key
  60401. */
  60402. StringDictionary.prototype.getAndRemove = function (key) {
  60403. var val = this.get(key);
  60404. if (val !== undefined) {
  60405. delete this._data[key];
  60406. --this._count;
  60407. return val;
  60408. }
  60409. return null;
  60410. };
  60411. /**
  60412. * Remove a key/value from the dictionary.
  60413. * @param key the key to remove
  60414. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  60415. */
  60416. StringDictionary.prototype.remove = function (key) {
  60417. if (this.contains(key)) {
  60418. delete this._data[key];
  60419. --this._count;
  60420. return true;
  60421. }
  60422. return false;
  60423. };
  60424. /**
  60425. * Clear the whole content of the dictionary
  60426. */
  60427. StringDictionary.prototype.clear = function () {
  60428. this._data = {};
  60429. this._count = 0;
  60430. };
  60431. Object.defineProperty(StringDictionary.prototype, "count", {
  60432. get: function () {
  60433. return this._count;
  60434. },
  60435. enumerable: true,
  60436. configurable: true
  60437. });
  60438. /**
  60439. * Execute a callback on each key/val of the dictionary.
  60440. * Note that you can remove any element in this dictionary in the callback implementation
  60441. * @param callback the callback to execute on a given key/value pair
  60442. */
  60443. StringDictionary.prototype.forEach = function (callback) {
  60444. for (var cur in this._data) {
  60445. var val = this._data[cur];
  60446. callback(cur, val);
  60447. }
  60448. };
  60449. /**
  60450. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  60451. * If the callback returns null or undefined the method will iterate to the next key/value pair
  60452. * Note that you can remove any element in this dictionary in the callback implementation
  60453. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  60454. */
  60455. StringDictionary.prototype.first = function (callback) {
  60456. for (var cur in this._data) {
  60457. var val = this._data[cur];
  60458. var res = callback(cur, val);
  60459. if (res) {
  60460. return res;
  60461. }
  60462. }
  60463. return null;
  60464. };
  60465. return StringDictionary;
  60466. }());
  60467. BABYLON.StringDictionary = StringDictionary;
  60468. })(BABYLON || (BABYLON = {}));
  60469. //# sourceMappingURL=babylon.stringDictionary.js.map
  60470. var BABYLON;
  60471. (function (BABYLON) {
  60472. var Debug;
  60473. (function (Debug) {
  60474. /**
  60475. * Class used to render a debug view of a given skeleton
  60476. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  60477. */
  60478. var SkeletonViewer = /** @class */ (function () {
  60479. /**
  60480. * Creates a new SkeletonViewer
  60481. * @param skeleton defines the skeleton to render
  60482. * @param mesh defines the mesh attached to the skeleton
  60483. * @param scene defines the hosting scene
  60484. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  60485. * @param renderingGroupId defines the rendering group id to use with the viewer
  60486. */
  60487. function SkeletonViewer(
  60488. /** defines the skeleton to render */
  60489. skeleton,
  60490. /** defines the mesh attached to the skeleton */
  60491. mesh, scene,
  60492. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  60493. autoUpdateBonesMatrices,
  60494. /** defines the rendering group id to use with the viewer */
  60495. renderingGroupId) {
  60496. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  60497. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  60498. this.skeleton = skeleton;
  60499. this.mesh = mesh;
  60500. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  60501. this.renderingGroupId = renderingGroupId;
  60502. /** Gets or sets the color used to render the skeleton */
  60503. this.color = BABYLON.Color3.White();
  60504. this._debugLines = new Array();
  60505. this._isEnabled = false;
  60506. this._scene = scene;
  60507. this.update();
  60508. this._renderFunction = this.update.bind(this);
  60509. }
  60510. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  60511. get: function () {
  60512. return this._isEnabled;
  60513. },
  60514. /** Gets or sets a boolean indicating if the viewer is enabled */
  60515. set: function (value) {
  60516. if (this._isEnabled === value) {
  60517. return;
  60518. }
  60519. this._isEnabled = value;
  60520. if (value) {
  60521. this._scene.registerBeforeRender(this._renderFunction);
  60522. }
  60523. else {
  60524. this._scene.unregisterBeforeRender(this._renderFunction);
  60525. }
  60526. },
  60527. enumerable: true,
  60528. configurable: true
  60529. });
  60530. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  60531. if (x === void 0) { x = 0; }
  60532. if (y === void 0) { y = 0; }
  60533. if (z === void 0) { z = 0; }
  60534. var tmat = BABYLON.Tmp.Matrix[0];
  60535. var parentBone = bone.getParent();
  60536. tmat.copyFrom(bone.getLocalMatrix());
  60537. if (x !== 0 || y !== 0 || z !== 0) {
  60538. var tmat2 = BABYLON.Tmp.Matrix[1];
  60539. BABYLON.Matrix.IdentityToRef(tmat2);
  60540. tmat2.m[12] = x;
  60541. tmat2.m[13] = y;
  60542. tmat2.m[14] = z;
  60543. tmat2.multiplyToRef(tmat, tmat);
  60544. }
  60545. if (parentBone) {
  60546. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  60547. }
  60548. tmat.multiplyToRef(meshMat, tmat);
  60549. position.x = tmat.m[12];
  60550. position.y = tmat.m[13];
  60551. position.z = tmat.m[14];
  60552. };
  60553. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  60554. var len = bones.length;
  60555. var meshPos = this.mesh.position;
  60556. for (var i = 0; i < len; i++) {
  60557. var bone = bones[i];
  60558. var points = this._debugLines[i];
  60559. if (!points) {
  60560. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60561. this._debugLines[i] = points;
  60562. }
  60563. this._getBonePosition(points[0], bone, meshMat);
  60564. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  60565. points[0].subtractInPlace(meshPos);
  60566. points[1].subtractInPlace(meshPos);
  60567. }
  60568. };
  60569. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  60570. var len = bones.length;
  60571. var boneNum = 0;
  60572. var meshPos = this.mesh.position;
  60573. for (var i = len - 1; i >= 0; i--) {
  60574. var childBone = bones[i];
  60575. var parentBone = childBone.getParent();
  60576. if (!parentBone) {
  60577. continue;
  60578. }
  60579. var points = this._debugLines[boneNum];
  60580. if (!points) {
  60581. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60582. this._debugLines[boneNum] = points;
  60583. }
  60584. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  60585. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  60586. points[0].subtractInPlace(meshPos);
  60587. points[1].subtractInPlace(meshPos);
  60588. boneNum++;
  60589. }
  60590. };
  60591. /** Update the viewer to sync with current skeleton state */
  60592. SkeletonViewer.prototype.update = function () {
  60593. if (this.autoUpdateBonesMatrices) {
  60594. this.skeleton.computeAbsoluteTransforms();
  60595. }
  60596. if (this.skeleton.bones[0].length === undefined) {
  60597. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60598. }
  60599. else {
  60600. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60601. }
  60602. if (!this._debugMesh) {
  60603. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  60604. this._debugMesh.renderingGroupId = this.renderingGroupId;
  60605. }
  60606. else {
  60607. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  60608. }
  60609. this._debugMesh.position.copyFrom(this.mesh.position);
  60610. this._debugMesh.color = this.color;
  60611. };
  60612. /** Release associated resources */
  60613. SkeletonViewer.prototype.dispose = function () {
  60614. if (this._debugMesh) {
  60615. this.isEnabled = false;
  60616. this._debugMesh.dispose();
  60617. this._debugMesh = null;
  60618. }
  60619. };
  60620. return SkeletonViewer;
  60621. }());
  60622. Debug.SkeletonViewer = SkeletonViewer;
  60623. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60624. })(BABYLON || (BABYLON = {}));
  60625. //# sourceMappingURL=babylon.skeletonViewer.js.map
  60626. /**
  60627. * Module Debug contains the (visual) components to debug a scene correctly
  60628. */
  60629. var BABYLON;
  60630. (function (BABYLON) {
  60631. var Debug;
  60632. (function (Debug) {
  60633. /**
  60634. * The Axes viewer will show 3 axes in a specific point in space
  60635. */
  60636. var AxesViewer = /** @class */ (function () {
  60637. /**
  60638. * Creates a new AxesViewer
  60639. * @param scene defines the hosting scene
  60640. * @param scaleLines defines a number used to scale line length (1 by default)
  60641. */
  60642. function AxesViewer(scene, scaleLines) {
  60643. if (scaleLines === void 0) { scaleLines = 1; }
  60644. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60645. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60646. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60647. /**
  60648. * Gets or sets a number used to scale line length
  60649. */
  60650. this.scaleLines = 1;
  60651. this.scaleLines = scaleLines;
  60652. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  60653. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  60654. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  60655. this._xmesh.renderingGroupId = 2;
  60656. this._ymesh.renderingGroupId = 2;
  60657. this._zmesh.renderingGroupId = 2;
  60658. this._xmesh.material.checkReadyOnlyOnce = true;
  60659. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  60660. this._ymesh.material.checkReadyOnlyOnce = true;
  60661. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  60662. this._zmesh.material.checkReadyOnlyOnce = true;
  60663. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  60664. this.scene = scene;
  60665. }
  60666. /**
  60667. * Force the viewer to update
  60668. * @param position defines the position of the viewer
  60669. * @param xaxis defines the x axis of the viewer
  60670. * @param yaxis defines the y axis of the viewer
  60671. * @param zaxis defines the z axis of the viewer
  60672. */
  60673. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  60674. var scaleLines = this.scaleLines;
  60675. if (this._xmesh) {
  60676. this._xmesh.position.copyFrom(position);
  60677. }
  60678. if (this._ymesh) {
  60679. this._ymesh.position.copyFrom(position);
  60680. }
  60681. if (this._zmesh) {
  60682. this._zmesh.position.copyFrom(position);
  60683. }
  60684. var point2 = this._xline[1];
  60685. point2.x = xaxis.x * scaleLines;
  60686. point2.y = xaxis.y * scaleLines;
  60687. point2.z = xaxis.z * scaleLines;
  60688. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  60689. point2 = this._yline[1];
  60690. point2.x = yaxis.x * scaleLines;
  60691. point2.y = yaxis.y * scaleLines;
  60692. point2.z = yaxis.z * scaleLines;
  60693. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  60694. point2 = this._zline[1];
  60695. point2.x = zaxis.x * scaleLines;
  60696. point2.y = zaxis.y * scaleLines;
  60697. point2.z = zaxis.z * scaleLines;
  60698. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  60699. };
  60700. /** Releases resources */
  60701. AxesViewer.prototype.dispose = function () {
  60702. if (this._xmesh) {
  60703. this._xmesh.dispose();
  60704. }
  60705. if (this._ymesh) {
  60706. this._ymesh.dispose();
  60707. }
  60708. if (this._zmesh) {
  60709. this._zmesh.dispose();
  60710. }
  60711. this._xmesh = null;
  60712. this._ymesh = null;
  60713. this._zmesh = null;
  60714. this.scene = null;
  60715. };
  60716. return AxesViewer;
  60717. }());
  60718. Debug.AxesViewer = AxesViewer;
  60719. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60720. })(BABYLON || (BABYLON = {}));
  60721. //# sourceMappingURL=babylon.axesViewer.js.map
  60722. var BABYLON;
  60723. (function (BABYLON) {
  60724. var Debug;
  60725. (function (Debug) {
  60726. /**
  60727. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  60728. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  60729. */
  60730. var BoneAxesViewer = /** @class */ (function (_super) {
  60731. __extends(BoneAxesViewer, _super);
  60732. /**
  60733. * Creates a new BoneAxesViewer
  60734. * @param scene defines the hosting scene
  60735. * @param bone defines the target bone
  60736. * @param mesh defines the target mesh
  60737. * @param scaleLines defines a scaling factor for line length (1 by default)
  60738. */
  60739. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  60740. if (scaleLines === void 0) { scaleLines = 1; }
  60741. var _this = _super.call(this, scene, scaleLines) || this;
  60742. /** Gets current position */
  60743. _this.pos = BABYLON.Vector3.Zero();
  60744. /** Gets direction of X axis */
  60745. _this.xaxis = BABYLON.Vector3.Zero();
  60746. /** Gets direction of Y axis */
  60747. _this.yaxis = BABYLON.Vector3.Zero();
  60748. /** Gets direction of Z axis */
  60749. _this.zaxis = BABYLON.Vector3.Zero();
  60750. _this.mesh = mesh;
  60751. _this.bone = bone;
  60752. return _this;
  60753. }
  60754. /**
  60755. * Force the viewer to update
  60756. */
  60757. BoneAxesViewer.prototype.update = function () {
  60758. if (!this.mesh || !this.bone) {
  60759. return;
  60760. }
  60761. var bone = this.bone;
  60762. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  60763. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  60764. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  60765. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  60766. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  60767. };
  60768. /** Releases resources */
  60769. BoneAxesViewer.prototype.dispose = function () {
  60770. if (this.mesh) {
  60771. this.mesh = null;
  60772. this.bone = null;
  60773. _super.prototype.dispose.call(this);
  60774. }
  60775. };
  60776. return BoneAxesViewer;
  60777. }(Debug.AxesViewer));
  60778. Debug.BoneAxesViewer = BoneAxesViewer;
  60779. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60780. })(BABYLON || (BABYLON = {}));
  60781. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  60782. var BABYLON;
  60783. (function (BABYLON) {
  60784. var RayHelper = /** @class */ (function () {
  60785. function RayHelper(ray) {
  60786. this.ray = ray;
  60787. }
  60788. RayHelper.CreateAndShow = function (ray, scene, color) {
  60789. var helper = new RayHelper(ray);
  60790. helper.show(scene, color);
  60791. return helper;
  60792. };
  60793. RayHelper.prototype.show = function (scene, color) {
  60794. if (!this._renderFunction && this.ray) {
  60795. var ray = this.ray;
  60796. this._renderFunction = this._render.bind(this);
  60797. this._scene = scene;
  60798. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  60799. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  60800. if (this._renderFunction) {
  60801. this._scene.registerBeforeRender(this._renderFunction);
  60802. }
  60803. }
  60804. if (color && this._renderLine) {
  60805. this._renderLine.color.copyFrom(color);
  60806. }
  60807. };
  60808. RayHelper.prototype.hide = function () {
  60809. if (this._renderFunction && this._scene) {
  60810. this._scene.unregisterBeforeRender(this._renderFunction);
  60811. this._scene = null;
  60812. this._renderFunction = null;
  60813. if (this._renderLine) {
  60814. this._renderLine.dispose();
  60815. this._renderLine = null;
  60816. }
  60817. this._renderPoints = [];
  60818. }
  60819. };
  60820. RayHelper.prototype._render = function () {
  60821. var ray = this.ray;
  60822. if (!ray) {
  60823. return;
  60824. }
  60825. var point = this._renderPoints[1];
  60826. var len = Math.min(ray.length, 1000000);
  60827. point.copyFrom(ray.direction);
  60828. point.scaleInPlace(len);
  60829. point.addInPlace(ray.origin);
  60830. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  60831. };
  60832. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  60833. this._attachedToMesh = mesh;
  60834. var ray = this.ray;
  60835. if (!ray) {
  60836. return;
  60837. }
  60838. if (!ray.direction) {
  60839. ray.direction = BABYLON.Vector3.Zero();
  60840. }
  60841. if (!ray.origin) {
  60842. ray.origin = BABYLON.Vector3.Zero();
  60843. }
  60844. if (length) {
  60845. ray.length = length;
  60846. }
  60847. if (!meshSpaceOrigin) {
  60848. meshSpaceOrigin = BABYLON.Vector3.Zero();
  60849. }
  60850. if (!meshSpaceDirection) {
  60851. // -1 so that this will work with Mesh.lookAt
  60852. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  60853. }
  60854. if (!this._meshSpaceDirection) {
  60855. this._meshSpaceDirection = meshSpaceDirection.clone();
  60856. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  60857. }
  60858. else {
  60859. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  60860. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  60861. }
  60862. if (!this._updateToMeshFunction) {
  60863. this._updateToMeshFunction = this._updateToMesh.bind(this);
  60864. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  60865. }
  60866. this._updateToMesh();
  60867. };
  60868. RayHelper.prototype.detachFromMesh = function () {
  60869. if (this._attachedToMesh) {
  60870. if (this._updateToMeshFunction) {
  60871. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  60872. }
  60873. this._attachedToMesh = null;
  60874. this._updateToMeshFunction = null;
  60875. }
  60876. };
  60877. RayHelper.prototype._updateToMesh = function () {
  60878. var ray = this.ray;
  60879. if (!this._attachedToMesh || !ray) {
  60880. return;
  60881. }
  60882. if (this._attachedToMesh._isDisposed) {
  60883. this.detachFromMesh();
  60884. return;
  60885. }
  60886. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  60887. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  60888. };
  60889. RayHelper.prototype.dispose = function () {
  60890. this.hide();
  60891. this.detachFromMesh();
  60892. this.ray = null;
  60893. };
  60894. return RayHelper;
  60895. }());
  60896. BABYLON.RayHelper = RayHelper;
  60897. })(BABYLON || (BABYLON = {}));
  60898. //# sourceMappingURL=babylon.rayHelper.js.map
  60899. var BABYLON;
  60900. (function (BABYLON) {
  60901. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  60902. get: function () {
  60903. if (!this._debugLayer) {
  60904. this._debugLayer = new DebugLayer(this);
  60905. }
  60906. return this._debugLayer;
  60907. },
  60908. enumerable: true,
  60909. configurable: true
  60910. });
  60911. var DebugLayer = /** @class */ (function () {
  60912. function DebugLayer(scene) {
  60913. var _this = this;
  60914. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60915. this.onPropertyChangedObservable = new BABYLON.Observable();
  60916. this._scene = scene;
  60917. this._scene.onDisposeObservable.add(function () {
  60918. // Debug layer
  60919. if (_this._scene._debugLayer) {
  60920. _this._scene._debugLayer.hide();
  60921. }
  60922. });
  60923. }
  60924. /** Creates the inspector window. */
  60925. DebugLayer.prototype._createInspector = function (config) {
  60926. if (config === void 0) { config = {}; }
  60927. var popup = config.popup || false;
  60928. var initialTab = config.initialTab || 0;
  60929. var parentElement = config.parentElement || null;
  60930. if (!this._inspector) {
  60931. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60932. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  60933. } // else nothing to do as instance is already created
  60934. };
  60935. DebugLayer.prototype.isVisible = function () {
  60936. if (!this._inspector) {
  60937. return false;
  60938. }
  60939. return true;
  60940. };
  60941. DebugLayer.prototype.hide = function () {
  60942. if (this._inspector) {
  60943. try {
  60944. this._inspector.dispose();
  60945. }
  60946. catch (e) {
  60947. // If the inspector has been removed directly from the inspector tool
  60948. }
  60949. this.onPropertyChangedObservable.clear();
  60950. this._inspector = null;
  60951. }
  60952. };
  60953. /**
  60954. *
  60955. * Launch the debugLayer.
  60956. *
  60957. * initialTab:
  60958. * | Value | Tab Name |
  60959. * | --- | --- |
  60960. * | 0 | Scene |
  60961. * | 1 | Console |
  60962. * | 2 | Stats |
  60963. * | 3 | Textures |
  60964. * | 4 | Mesh |
  60965. * | 5 | Light |
  60966. * | 6 | Material |
  60967. * | 7 | GLTF |
  60968. * | 8 | GUI |
  60969. * | 9 | Physics |
  60970. * | 10 | Camera |
  60971. * | 11 | Audio |
  60972. *
  60973. */
  60974. DebugLayer.prototype.show = function (config) {
  60975. if (config === void 0) { config = {}; }
  60976. if (typeof this.BJSINSPECTOR == 'undefined') {
  60977. // Load inspector and add it to the DOM
  60978. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  60979. }
  60980. else {
  60981. // Otherwise creates the inspector
  60982. this._createInspector(config);
  60983. }
  60984. };
  60985. /**
  60986. * Gets the active tab
  60987. * @return the index of the active tab or -1 if the inspector is hidden
  60988. */
  60989. DebugLayer.prototype.getActiveTab = function () {
  60990. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  60991. };
  60992. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  60993. return DebugLayer;
  60994. }());
  60995. BABYLON.DebugLayer = DebugLayer;
  60996. })(BABYLON || (BABYLON = {}));
  60997. //# sourceMappingURL=babylon.debugLayer.js.map
  60998. var BABYLON;
  60999. (function (BABYLON) {
  61000. var Debug;
  61001. (function (Debug) {
  61002. /**
  61003. * Used to show the physics impostor around the specific mesh
  61004. */
  61005. var PhysicsViewer = /** @class */ (function () {
  61006. /**
  61007. * Creates a new PhysicsViewer
  61008. * @param scene defines the hosting scene
  61009. */
  61010. function PhysicsViewer(scene) {
  61011. /** @hidden */
  61012. this._impostors = [];
  61013. /** @hidden */
  61014. this._meshes = [];
  61015. /** @hidden */
  61016. this._numMeshes = 0;
  61017. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61018. var physicEngine = this._scene.getPhysicsEngine();
  61019. if (physicEngine) {
  61020. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  61021. }
  61022. }
  61023. /** @hidden */
  61024. PhysicsViewer.prototype._updateDebugMeshes = function () {
  61025. var plugin = this._physicsEnginePlugin;
  61026. for (var i = 0; i < this._numMeshes; i++) {
  61027. var impostor = this._impostors[i];
  61028. if (!impostor) {
  61029. continue;
  61030. }
  61031. if (impostor.isDisposed) {
  61032. this.hideImpostor(this._impostors[i--]);
  61033. }
  61034. else {
  61035. var mesh = this._meshes[i];
  61036. if (mesh && plugin) {
  61037. plugin.syncMeshWithImpostor(mesh, impostor);
  61038. }
  61039. }
  61040. }
  61041. };
  61042. /**
  61043. * Renders a specified physic impostor
  61044. * @param impostor defines the impostor to render
  61045. */
  61046. PhysicsViewer.prototype.showImpostor = function (impostor) {
  61047. if (!this._scene) {
  61048. return;
  61049. }
  61050. for (var i = 0; i < this._numMeshes; i++) {
  61051. if (this._impostors[i] == impostor) {
  61052. return;
  61053. }
  61054. }
  61055. var debugMesh = this._getDebugMesh(impostor, this._scene);
  61056. if (debugMesh) {
  61057. this._impostors[this._numMeshes] = impostor;
  61058. this._meshes[this._numMeshes] = debugMesh;
  61059. if (this._numMeshes === 0) {
  61060. this._renderFunction = this._updateDebugMeshes.bind(this);
  61061. this._scene.registerBeforeRender(this._renderFunction);
  61062. }
  61063. this._numMeshes++;
  61064. }
  61065. };
  61066. /**
  61067. * Hides a specified physic impostor
  61068. * @param impostor defines the impostor to hide
  61069. */
  61070. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  61071. if (!impostor || !this._scene) {
  61072. return;
  61073. }
  61074. var removed = false;
  61075. for (var i = 0; i < this._numMeshes; i++) {
  61076. if (this._impostors[i] == impostor) {
  61077. var mesh = this._meshes[i];
  61078. if (!mesh) {
  61079. continue;
  61080. }
  61081. this._scene.removeMesh(mesh);
  61082. mesh.dispose();
  61083. this._numMeshes--;
  61084. if (this._numMeshes > 0) {
  61085. this._meshes[i] = this._meshes[this._numMeshes];
  61086. this._impostors[i] = this._impostors[this._numMeshes];
  61087. this._meshes[this._numMeshes] = null;
  61088. this._impostors[this._numMeshes] = null;
  61089. }
  61090. else {
  61091. this._meshes[0] = null;
  61092. this._impostors[0] = null;
  61093. }
  61094. removed = true;
  61095. break;
  61096. }
  61097. }
  61098. if (removed && this._numMeshes === 0) {
  61099. this._scene.unregisterBeforeRender(this._renderFunction);
  61100. }
  61101. };
  61102. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  61103. if (!this._debugMaterial) {
  61104. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  61105. this._debugMaterial.wireframe = true;
  61106. }
  61107. return this._debugMaterial;
  61108. };
  61109. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  61110. if (!this._debugBoxMesh) {
  61111. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  61112. this._debugBoxMesh.renderingGroupId = 1;
  61113. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  61114. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  61115. scene.removeMesh(this._debugBoxMesh);
  61116. }
  61117. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  61118. };
  61119. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  61120. if (!this._debugSphereMesh) {
  61121. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  61122. this._debugSphereMesh.renderingGroupId = 1;
  61123. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  61124. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  61125. scene.removeMesh(this._debugSphereMesh);
  61126. }
  61127. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  61128. };
  61129. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  61130. var mesh = null;
  61131. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  61132. mesh = this._getDebugBoxMesh(scene);
  61133. impostor.getBoxSizeToRef(mesh.scaling);
  61134. }
  61135. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  61136. mesh = this._getDebugSphereMesh(scene);
  61137. var radius = impostor.getRadius();
  61138. mesh.scaling.x = radius * 2;
  61139. mesh.scaling.y = radius * 2;
  61140. mesh.scaling.z = radius * 2;
  61141. }
  61142. return mesh;
  61143. };
  61144. /** Releases all resources */
  61145. PhysicsViewer.prototype.dispose = function () {
  61146. for (var i = 0; i < this._numMeshes; i++) {
  61147. this.hideImpostor(this._impostors[i]);
  61148. }
  61149. if (this._debugBoxMesh) {
  61150. this._debugBoxMesh.dispose();
  61151. }
  61152. if (this._debugSphereMesh) {
  61153. this._debugSphereMesh.dispose();
  61154. }
  61155. if (this._debugMaterial) {
  61156. this._debugMaterial.dispose();
  61157. }
  61158. this._impostors.length = 0;
  61159. this._scene = null;
  61160. this._physicsEnginePlugin = null;
  61161. };
  61162. return PhysicsViewer;
  61163. }());
  61164. Debug.PhysicsViewer = PhysicsViewer;
  61165. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61166. })(BABYLON || (BABYLON = {}));
  61167. //# sourceMappingURL=babylon.physicsViewer.js.map
  61168. var BABYLON;
  61169. (function (BABYLON) {
  61170. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  61171. get: function () {
  61172. return this._forceShowBoundingBoxes || false;
  61173. },
  61174. set: function (value) {
  61175. this._forceShowBoundingBoxes = value;
  61176. // Lazyly creates a BB renderer if needed.
  61177. if (value) {
  61178. this.getBoundingBoxRenderer();
  61179. }
  61180. },
  61181. enumerable: true,
  61182. configurable: true
  61183. });
  61184. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  61185. if (!this._boundingBoxRenderer) {
  61186. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  61187. }
  61188. return this._boundingBoxRenderer;
  61189. };
  61190. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  61191. get: function () {
  61192. return this._showBoundingBox || false;
  61193. },
  61194. set: function (value) {
  61195. this._showBoundingBox = value;
  61196. // Lazyly creates a BB renderer if needed.
  61197. if (value) {
  61198. this.getScene().getBoundingBoxRenderer();
  61199. }
  61200. },
  61201. enumerable: true,
  61202. configurable: true
  61203. });
  61204. var BoundingBoxRenderer = /** @class */ (function () {
  61205. function BoundingBoxRenderer(scene) {
  61206. /**
  61207. * The component name helpfull to identify the component in the list of scene components.
  61208. */
  61209. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  61210. this.frontColor = new BABYLON.Color3(1, 1, 1);
  61211. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  61212. this.showBackLines = true;
  61213. this.renderList = new BABYLON.SmartArray(32);
  61214. this._vertexBuffers = {};
  61215. this.scene = scene;
  61216. scene._addComponent(this);
  61217. }
  61218. /**
  61219. * Registers the component in a given scene
  61220. */
  61221. BoundingBoxRenderer.prototype.register = function () {
  61222. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  61223. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  61224. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  61225. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  61226. };
  61227. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  61228. if (mesh.showSubMeshesBoundingBox) {
  61229. var boundingInfo = subMesh.getBoundingInfo();
  61230. if (boundingInfo !== null && boundingInfo !== undefined) {
  61231. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  61232. this.renderList.push(boundingInfo.boundingBox);
  61233. }
  61234. }
  61235. };
  61236. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  61237. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  61238. var boundingInfo = sourceMesh.getBoundingInfo();
  61239. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  61240. this.renderList.push(boundingInfo.boundingBox);
  61241. }
  61242. };
  61243. BoundingBoxRenderer.prototype._prepareRessources = function () {
  61244. if (this._colorShader) {
  61245. return;
  61246. }
  61247. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  61248. attributes: [BABYLON.VertexBuffer.PositionKind],
  61249. uniforms: ["world", "viewProjection", "color"]
  61250. });
  61251. var engine = this.scene.getEngine();
  61252. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  61253. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  61254. this._createIndexBuffer();
  61255. };
  61256. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  61257. var engine = this.scene.getEngine();
  61258. 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]);
  61259. };
  61260. /**
  61261. * Rebuilds the elements related to this component in case of
  61262. * context lost for instance.
  61263. */
  61264. BoundingBoxRenderer.prototype.rebuild = function () {
  61265. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61266. if (vb) {
  61267. vb._rebuild();
  61268. }
  61269. this._createIndexBuffer();
  61270. };
  61271. BoundingBoxRenderer.prototype.reset = function () {
  61272. this.renderList.reset();
  61273. };
  61274. /**
  61275. * Render the bounding boxes of a specific rendering group
  61276. * @param renderingGroupId defines the rendering group to render
  61277. */
  61278. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  61279. if (this.renderList.length === 0) {
  61280. return;
  61281. }
  61282. this._prepareRessources();
  61283. if (!this._colorShader.isReady()) {
  61284. return;
  61285. }
  61286. var engine = this.scene.getEngine();
  61287. engine.setDepthWrite(false);
  61288. this._colorShader._preBind();
  61289. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  61290. var boundingBox = this.renderList.data[boundingBoxIndex];
  61291. if (boundingBox._tag !== renderingGroupId) {
  61292. continue;
  61293. }
  61294. var min = boundingBox.minimum;
  61295. var max = boundingBox.maximum;
  61296. var diff = max.subtract(min);
  61297. var median = min.add(diff.scale(0.5));
  61298. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61299. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61300. .multiply(boundingBox.getWorldMatrix());
  61301. // VBOs
  61302. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61303. if (this.showBackLines) {
  61304. // Back
  61305. engine.setDepthFunctionToGreaterOrEqual();
  61306. this.scene.resetCachedMaterial();
  61307. this._colorShader.setColor4("color", this.backColor.toColor4());
  61308. this._colorShader.bind(worldMatrix);
  61309. // Draw order
  61310. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61311. }
  61312. // Front
  61313. engine.setDepthFunctionToLess();
  61314. this.scene.resetCachedMaterial();
  61315. this._colorShader.setColor4("color", this.frontColor.toColor4());
  61316. this._colorShader.bind(worldMatrix);
  61317. // Draw order
  61318. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61319. }
  61320. this._colorShader.unbind();
  61321. engine.setDepthFunctionToLessOrEqual();
  61322. engine.setDepthWrite(true);
  61323. };
  61324. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  61325. this._prepareRessources();
  61326. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  61327. return;
  61328. }
  61329. var engine = this.scene.getEngine();
  61330. engine.setDepthWrite(false);
  61331. engine.setColorWrite(false);
  61332. this._colorShader._preBind();
  61333. var boundingBox = mesh._boundingInfo.boundingBox;
  61334. var min = boundingBox.minimum;
  61335. var max = boundingBox.maximum;
  61336. var diff = max.subtract(min);
  61337. var median = min.add(diff.scale(0.5));
  61338. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61339. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61340. .multiply(boundingBox.getWorldMatrix());
  61341. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61342. engine.setDepthFunctionToLess();
  61343. this.scene.resetCachedMaterial();
  61344. this._colorShader.bind(worldMatrix);
  61345. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61346. this._colorShader.unbind();
  61347. engine.setDepthFunctionToLessOrEqual();
  61348. engine.setDepthWrite(true);
  61349. engine.setColorWrite(true);
  61350. };
  61351. BoundingBoxRenderer.prototype.dispose = function () {
  61352. if (!this._colorShader) {
  61353. return;
  61354. }
  61355. this.renderList.dispose();
  61356. this._colorShader.dispose();
  61357. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61358. if (buffer) {
  61359. buffer.dispose();
  61360. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61361. }
  61362. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  61363. };
  61364. return BoundingBoxRenderer;
  61365. }());
  61366. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  61367. })(BABYLON || (BABYLON = {}));
  61368. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  61369. var BABYLON;
  61370. (function (BABYLON) {
  61371. BABYLON.Engine.prototype.createTransformFeedback = function () {
  61372. return this._gl.createTransformFeedback();
  61373. };
  61374. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  61375. this._gl.deleteTransformFeedback(value);
  61376. };
  61377. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  61378. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  61379. };
  61380. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  61381. if (usePoints === void 0) { usePoints = true; }
  61382. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  61383. };
  61384. BABYLON.Engine.prototype.endTransformFeedback = function () {
  61385. this._gl.endTransformFeedback();
  61386. };
  61387. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  61388. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  61389. };
  61390. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  61391. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  61392. };
  61393. })(BABYLON || (BABYLON = {}));
  61394. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  61395. var BABYLON;
  61396. (function (BABYLON) {
  61397. /**
  61398. * This represents a GPU particle system in Babylon
  61399. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  61400. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  61401. */
  61402. var GPUParticleSystem = /** @class */ (function (_super) {
  61403. __extends(GPUParticleSystem, _super);
  61404. /**
  61405. * Instantiates a GPU particle system.
  61406. * 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.
  61407. * @param name The name of the particle system
  61408. * @param options The options used to create the system
  61409. * @param scene The scene the particle system belongs to
  61410. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  61411. */
  61412. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  61413. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  61414. var _this = _super.call(this, name) || this;
  61415. /**
  61416. * The layer mask we are rendering the particles through.
  61417. */
  61418. _this.layerMask = 0x0FFFFFFF;
  61419. _this._accumulatedCount = 0;
  61420. _this._targetIndex = 0;
  61421. _this._currentRenderId = -1;
  61422. _this._started = false;
  61423. _this._stopped = false;
  61424. _this._timeDelta = 0;
  61425. _this._attributesStrideSize = 21;
  61426. _this._actualFrame = 0;
  61427. _this._rawTextureWidth = 256;
  61428. /**
  61429. * An event triggered when the system is disposed.
  61430. */
  61431. _this.onDisposeObservable = new BABYLON.Observable();
  61432. /**
  61433. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  61434. * to override the particles.
  61435. */
  61436. _this.forceDepthWrite = false;
  61437. _this._preWarmDone = false;
  61438. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61439. // Setup the default processing configuration to the scene.
  61440. _this._attachImageProcessingConfiguration(null);
  61441. _this._engine = _this._scene.getEngine();
  61442. if (!options.randomTextureSize) {
  61443. delete options.randomTextureSize;
  61444. }
  61445. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  61446. var optionsAsNumber = options;
  61447. if (isFinite(optionsAsNumber)) {
  61448. fullOptions.capacity = optionsAsNumber;
  61449. }
  61450. _this._capacity = fullOptions.capacity;
  61451. _this._activeCount = fullOptions.capacity;
  61452. _this._currentActiveCount = 0;
  61453. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  61454. _this._scene.particleSystems.push(_this);
  61455. _this._updateEffectOptions = {
  61456. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  61457. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  61458. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  61459. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  61460. uniformBuffersNames: [],
  61461. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  61462. defines: "",
  61463. fallbacks: null,
  61464. onCompiled: null,
  61465. onError: null,
  61466. indexParameters: null,
  61467. maxSimultaneousLights: 0,
  61468. transformFeedbackVaryings: []
  61469. };
  61470. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  61471. // Random data
  61472. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  61473. var d = [];
  61474. for (var i = 0; i < maxTextureSize; ++i) {
  61475. d.push(Math.random());
  61476. d.push(Math.random());
  61477. d.push(Math.random());
  61478. d.push(Math.random());
  61479. }
  61480. _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);
  61481. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61482. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61483. d = [];
  61484. for (var i = 0; i < maxTextureSize; ++i) {
  61485. d.push(Math.random());
  61486. d.push(Math.random());
  61487. d.push(Math.random());
  61488. d.push(Math.random());
  61489. }
  61490. _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);
  61491. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61492. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61493. _this._randomTextureSize = maxTextureSize;
  61494. return _this;
  61495. }
  61496. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  61497. /**
  61498. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  61499. */
  61500. get: function () {
  61501. if (!BABYLON.Engine.LastCreatedEngine) {
  61502. return false;
  61503. }
  61504. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  61505. },
  61506. enumerable: true,
  61507. configurable: true
  61508. });
  61509. /**
  61510. * Gets the maximum number of particles active at the same time.
  61511. * @returns The max number of active particles.
  61512. */
  61513. GPUParticleSystem.prototype.getCapacity = function () {
  61514. return this._capacity;
  61515. };
  61516. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  61517. /**
  61518. * Gets or set the number of active particles
  61519. */
  61520. get: function () {
  61521. return this._activeCount;
  61522. },
  61523. set: function (value) {
  61524. this._activeCount = Math.min(value, this._capacity);
  61525. },
  61526. enumerable: true,
  61527. configurable: true
  61528. });
  61529. /**
  61530. * Is this system ready to be used/rendered
  61531. * @return true if the system is ready
  61532. */
  61533. GPUParticleSystem.prototype.isReady = function () {
  61534. if (!this._updateEffect) {
  61535. this._recreateUpdateEffect();
  61536. this._recreateRenderEffect();
  61537. return false;
  61538. }
  61539. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  61540. return false;
  61541. }
  61542. return true;
  61543. };
  61544. /**
  61545. * Gets if the system has been started. (Note: this will still be true after stop is called)
  61546. * @returns True if it has been started, otherwise false.
  61547. */
  61548. GPUParticleSystem.prototype.isStarted = function () {
  61549. return this._started;
  61550. };
  61551. /**
  61552. * Starts the particle system and begins to emit
  61553. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  61554. */
  61555. GPUParticleSystem.prototype.start = function (delay) {
  61556. var _this = this;
  61557. if (delay === void 0) { delay = this.startDelay; }
  61558. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  61559. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  61560. }
  61561. if (delay) {
  61562. setTimeout(function () {
  61563. _this.start(0);
  61564. }, delay);
  61565. return;
  61566. }
  61567. this._started = true;
  61568. this._stopped = false;
  61569. this._preWarmDone = false;
  61570. };
  61571. /**
  61572. * Stops the particle system.
  61573. */
  61574. GPUParticleSystem.prototype.stop = function () {
  61575. this._stopped = true;
  61576. };
  61577. /**
  61578. * Remove all active particles
  61579. */
  61580. GPUParticleSystem.prototype.reset = function () {
  61581. this._releaseBuffers();
  61582. this._releaseVAOs();
  61583. this._currentActiveCount = 0;
  61584. this._targetIndex = 0;
  61585. };
  61586. /**
  61587. * Returns the string "GPUParticleSystem"
  61588. * @returns a string containing the class name
  61589. */
  61590. GPUParticleSystem.prototype.getClassName = function () {
  61591. return "GPUParticleSystem";
  61592. };
  61593. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  61594. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  61595. this._releaseBuffers();
  61596. return this;
  61597. };
  61598. /**
  61599. * Adds a new color gradient
  61600. * @param gradient defines the gradient to use (between 0 and 1)
  61601. * @param color defines the color to affect to the specified gradient
  61602. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  61603. * @returns the current particle system
  61604. */
  61605. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  61606. if (!this._colorGradients) {
  61607. this._colorGradients = [];
  61608. }
  61609. var colorGradient = new BABYLON.ColorGradient();
  61610. colorGradient.gradient = gradient;
  61611. colorGradient.color1 = color1;
  61612. this._colorGradients.push(colorGradient);
  61613. this._colorGradients.sort(function (a, b) {
  61614. if (a.gradient < b.gradient) {
  61615. return -1;
  61616. }
  61617. else if (a.gradient > b.gradient) {
  61618. return 1;
  61619. }
  61620. return 0;
  61621. });
  61622. if (this._colorGradientsTexture) {
  61623. this._colorGradientsTexture.dispose();
  61624. this._colorGradientsTexture = null;
  61625. }
  61626. this._releaseBuffers();
  61627. return this;
  61628. };
  61629. /**
  61630. * Remove a specific color gradient
  61631. * @param gradient defines the gradient to remove
  61632. * @returns the current particle system
  61633. */
  61634. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  61635. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  61636. this._colorGradientsTexture = null;
  61637. return this;
  61638. };
  61639. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  61640. var valueGradient = new BABYLON.FactorGradient();
  61641. valueGradient.gradient = gradient;
  61642. valueGradient.factor1 = factor;
  61643. factorGradients.push(valueGradient);
  61644. factorGradients.sort(function (a, b) {
  61645. if (a.gradient < b.gradient) {
  61646. return -1;
  61647. }
  61648. else if (a.gradient > b.gradient) {
  61649. return 1;
  61650. }
  61651. return 0;
  61652. });
  61653. this._releaseBuffers();
  61654. };
  61655. /**
  61656. * Adds a new size gradient
  61657. * @param gradient defines the gradient to use (between 0 and 1)
  61658. * @param factor defines the size factor to affect to the specified gradient
  61659. * @returns the current particle system
  61660. */
  61661. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  61662. if (!this._sizeGradients) {
  61663. this._sizeGradients = [];
  61664. }
  61665. this._addFactorGradient(this._sizeGradients, gradient, factor);
  61666. if (this._sizeGradientsTexture) {
  61667. this._sizeGradientsTexture.dispose();
  61668. this._sizeGradientsTexture = null;
  61669. }
  61670. this._releaseBuffers();
  61671. return this;
  61672. };
  61673. /**
  61674. * Remove a specific size gradient
  61675. * @param gradient defines the gradient to remove
  61676. * @returns the current particle system
  61677. */
  61678. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  61679. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  61680. this._sizeGradientsTexture = null;
  61681. return this;
  61682. };
  61683. /**
  61684. * Adds a new angular speed gradient
  61685. * @param gradient defines the gradient to use (between 0 and 1)
  61686. * @param factor defines the angular speed to affect to the specified gradient
  61687. * @returns the current particle system
  61688. */
  61689. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  61690. if (!this._angularSpeedGradients) {
  61691. this._angularSpeedGradients = [];
  61692. }
  61693. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  61694. if (this._angularSpeedGradientsTexture) {
  61695. this._angularSpeedGradientsTexture.dispose();
  61696. this._angularSpeedGradientsTexture = null;
  61697. }
  61698. this._releaseBuffers();
  61699. return this;
  61700. };
  61701. /**
  61702. * Remove a specific angular speed gradient
  61703. * @param gradient defines the gradient to remove
  61704. * @returns the current particle system
  61705. */
  61706. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  61707. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  61708. this._angularSpeedGradientsTexture = null;
  61709. return this;
  61710. };
  61711. /**
  61712. * Adds a new velocity gradient
  61713. * @param gradient defines the gradient to use (between 0 and 1)
  61714. * @param factor defines the velocity to affect to the specified gradient
  61715. * @returns the current particle system
  61716. */
  61717. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  61718. if (!this._velocityGradients) {
  61719. this._velocityGradients = [];
  61720. }
  61721. this._addFactorGradient(this._velocityGradients, gradient, factor);
  61722. if (this._velocityGradientsTexture) {
  61723. this._velocityGradientsTexture.dispose();
  61724. this._velocityGradientsTexture = null;
  61725. }
  61726. this._releaseBuffers();
  61727. return this;
  61728. };
  61729. /**
  61730. * Remove a specific velocity gradient
  61731. * @param gradient defines the gradient to remove
  61732. * @returns the current particle system
  61733. */
  61734. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  61735. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  61736. this._velocityGradientsTexture = null;
  61737. return this;
  61738. };
  61739. /**
  61740. * Adds a new limit velocity gradient
  61741. * @param gradient defines the gradient to use (between 0 and 1)
  61742. * @param factor defines the limit velocity value to affect to the specified gradient
  61743. * @returns the current particle system
  61744. */
  61745. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  61746. if (!this._limitVelocityGradients) {
  61747. this._limitVelocityGradients = [];
  61748. }
  61749. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  61750. if (this._limitVelocityGradientsTexture) {
  61751. this._limitVelocityGradientsTexture.dispose();
  61752. this._limitVelocityGradientsTexture = null;
  61753. }
  61754. this._releaseBuffers();
  61755. return this;
  61756. };
  61757. /**
  61758. * Remove a specific limit velocity gradient
  61759. * @param gradient defines the gradient to remove
  61760. * @returns the current particle system
  61761. */
  61762. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  61763. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  61764. this._limitVelocityGradientsTexture = null;
  61765. return this;
  61766. };
  61767. /**
  61768. * Adds a new drag gradient
  61769. * @param gradient defines the gradient to use (between 0 and 1)
  61770. * @param factor defines the drag value to affect to the specified gradient
  61771. * @returns the current particle system
  61772. */
  61773. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  61774. if (!this._dragGradients) {
  61775. this._dragGradients = [];
  61776. }
  61777. this._addFactorGradient(this._dragGradients, gradient, factor);
  61778. if (this._dragGradientsTexture) {
  61779. this._dragGradientsTexture.dispose();
  61780. this._dragGradientsTexture = null;
  61781. }
  61782. this._releaseBuffers();
  61783. return this;
  61784. };
  61785. /**
  61786. * Remove a specific drag gradient
  61787. * @param gradient defines the gradient to remove
  61788. * @returns the current particle system
  61789. */
  61790. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  61791. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  61792. this._dragGradientsTexture = null;
  61793. return this;
  61794. };
  61795. /**
  61796. * Not supported by GPUParticleSystem
  61797. * @param gradient defines the gradient to use (between 0 and 1)
  61798. * @param factor defines the emit rate value to affect to the specified gradient
  61799. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61800. * @returns the current particle system
  61801. */
  61802. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  61803. // Do nothing as emit rate is not supported by GPUParticleSystem
  61804. return this;
  61805. };
  61806. /**
  61807. * Not supported by GPUParticleSystem
  61808. * @param gradient defines the gradient to remove
  61809. * @returns the current particle system
  61810. */
  61811. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  61812. // Do nothing as emit rate is not supported by GPUParticleSystem
  61813. return this;
  61814. };
  61815. /**
  61816. * Not supported by GPUParticleSystem
  61817. * @param gradient defines the gradient to use (between 0 and 1)
  61818. * @param factor defines the start size value to affect to the specified gradient
  61819. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61820. * @returns the current particle system
  61821. */
  61822. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  61823. // Do nothing as start size is not supported by GPUParticleSystem
  61824. return this;
  61825. };
  61826. /**
  61827. * Not supported by GPUParticleSystem
  61828. * @param gradient defines the gradient to remove
  61829. * @returns the current particle system
  61830. */
  61831. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  61832. // Do nothing as start size is not supported by GPUParticleSystem
  61833. return this;
  61834. };
  61835. /**
  61836. * Not supported by GPUParticleSystem
  61837. * @param gradient defines the gradient to use (between 0 and 1)
  61838. * @param min defines the color remap minimal range
  61839. * @param max defines the color remap maximal range
  61840. * @returns the current particle system
  61841. */
  61842. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  61843. // Do nothing as start size is not supported by GPUParticleSystem
  61844. return this;
  61845. };
  61846. /**
  61847. * Not supported by GPUParticleSystem
  61848. * @param gradient defines the gradient to remove
  61849. * @returns the current particle system
  61850. */
  61851. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  61852. // Do nothing as start size is not supported by GPUParticleSystem
  61853. return this;
  61854. };
  61855. /**
  61856. * Not supported by GPUParticleSystem
  61857. * @param gradient defines the gradient to use (between 0 and 1)
  61858. * @param min defines the alpha remap minimal range
  61859. * @param max defines the alpha remap maximal range
  61860. * @returns the current particle system
  61861. */
  61862. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  61863. // Do nothing as start size is not supported by GPUParticleSystem
  61864. return this;
  61865. };
  61866. /**
  61867. * Not supported by GPUParticleSystem
  61868. * @param gradient defines the gradient to remove
  61869. * @returns the current particle system
  61870. */
  61871. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  61872. // Do nothing as start size is not supported by GPUParticleSystem
  61873. return this;
  61874. };
  61875. /**
  61876. * Not supported by GPUParticleSystem
  61877. * @param gradient defines the gradient to use (between 0 and 1)
  61878. * @param color defines the color to affect to the specified gradient
  61879. * @returns the current particle system
  61880. */
  61881. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  61882. //Not supported by GPUParticleSystem
  61883. return this;
  61884. };
  61885. /**
  61886. * Not supported by GPUParticleSystem
  61887. * @param gradient defines the gradient to remove
  61888. * @returns the current particle system
  61889. */
  61890. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  61891. //Not supported by GPUParticleSystem
  61892. return this;
  61893. };
  61894. /**
  61895. * Not supported by GPUParticleSystem
  61896. * @returns the list of ramp gradients
  61897. */
  61898. GPUParticleSystem.prototype.getRampGradients = function () {
  61899. return null;
  61900. };
  61901. GPUParticleSystem.prototype._reset = function () {
  61902. this._releaseBuffers();
  61903. };
  61904. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  61905. var updateVertexBuffers = {};
  61906. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  61907. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  61908. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  61909. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  61910. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  61911. var offset = 12;
  61912. if (!this._colorGradientsTexture) {
  61913. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  61914. offset += 4;
  61915. }
  61916. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  61917. offset += 3;
  61918. if (!this._isBillboardBased) {
  61919. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  61920. offset += 3;
  61921. }
  61922. if (this._angularSpeedGradientsTexture) {
  61923. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  61924. offset += 1;
  61925. }
  61926. else {
  61927. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  61928. offset += 2;
  61929. }
  61930. if (this._isAnimationSheetEnabled) {
  61931. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  61932. offset += 1;
  61933. if (this.spriteRandomStartCell) {
  61934. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  61935. offset += 1;
  61936. }
  61937. }
  61938. if (this.noiseTexture) {
  61939. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  61940. offset += 3;
  61941. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  61942. offset += 3;
  61943. }
  61944. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  61945. this._engine.bindArrayBuffer(null);
  61946. return vao;
  61947. };
  61948. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  61949. var renderVertexBuffers = {};
  61950. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  61951. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  61952. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  61953. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  61954. var offset = 12;
  61955. if (!this._colorGradientsTexture) {
  61956. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  61957. offset += 4;
  61958. }
  61959. offset += 3; // Direction
  61960. if (!this._isBillboardBased) {
  61961. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  61962. offset += 3;
  61963. }
  61964. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  61965. if (this._angularSpeedGradientsTexture) {
  61966. offset++;
  61967. }
  61968. else {
  61969. offset += 2;
  61970. }
  61971. if (this._isAnimationSheetEnabled) {
  61972. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  61973. offset += 1;
  61974. if (this.spriteRandomStartCell) {
  61975. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  61976. offset += 1;
  61977. }
  61978. }
  61979. if (this.noiseTexture) {
  61980. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  61981. offset += 3;
  61982. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  61983. offset += 3;
  61984. }
  61985. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  61986. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  61987. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  61988. this._engine.bindArrayBuffer(null);
  61989. return vao;
  61990. };
  61991. GPUParticleSystem.prototype._initialize = function (force) {
  61992. if (force === void 0) { force = false; }
  61993. if (this._buffer0 && !force) {
  61994. return;
  61995. }
  61996. var engine = this._scene.getEngine();
  61997. var data = new Array();
  61998. if (!this.isBillboardBased) {
  61999. this._attributesStrideSize += 3;
  62000. }
  62001. if (this._colorGradientsTexture) {
  62002. this._attributesStrideSize -= 4;
  62003. }
  62004. if (this._angularSpeedGradientsTexture) {
  62005. this._attributesStrideSize -= 1;
  62006. }
  62007. if (this._isAnimationSheetEnabled) {
  62008. this._attributesStrideSize += 1;
  62009. if (this.spriteRandomStartCell) {
  62010. this._attributesStrideSize += 1;
  62011. }
  62012. }
  62013. if (this.noiseTexture) {
  62014. this._attributesStrideSize += 6;
  62015. }
  62016. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  62017. // position
  62018. data.push(0.0);
  62019. data.push(0.0);
  62020. data.push(0.0);
  62021. // Age and life
  62022. data.push(0.0); // create the particle as a dead one to create a new one at start
  62023. data.push(0.0);
  62024. // Seed
  62025. data.push(Math.random());
  62026. data.push(Math.random());
  62027. data.push(Math.random());
  62028. data.push(Math.random());
  62029. // Size
  62030. data.push(0.0);
  62031. data.push(0.0);
  62032. data.push(0.0);
  62033. if (!this._colorGradientsTexture) {
  62034. // color
  62035. data.push(0.0);
  62036. data.push(0.0);
  62037. data.push(0.0);
  62038. data.push(0.0);
  62039. }
  62040. // direction
  62041. data.push(0.0);
  62042. data.push(0.0);
  62043. data.push(0.0);
  62044. if (!this.isBillboardBased) {
  62045. // initialDirection
  62046. data.push(0.0);
  62047. data.push(0.0);
  62048. data.push(0.0);
  62049. }
  62050. // angle
  62051. data.push(0.0);
  62052. if (!this._angularSpeedGradientsTexture) {
  62053. data.push(0.0);
  62054. }
  62055. if (this._isAnimationSheetEnabled) {
  62056. data.push(0.0);
  62057. if (this.spriteRandomStartCell) {
  62058. data.push(0.0);
  62059. }
  62060. }
  62061. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  62062. data.push(Math.random());
  62063. data.push(Math.random());
  62064. data.push(Math.random());
  62065. data.push(Math.random());
  62066. data.push(Math.random());
  62067. data.push(Math.random());
  62068. }
  62069. }
  62070. // Sprite data
  62071. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  62072. -0.5, 0.5, 0, 1,
  62073. -0.5, -0.5, 0, 0,
  62074. 0.5, -0.5, 1, 0]);
  62075. // Buffers
  62076. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  62077. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  62078. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  62079. // Update VAO
  62080. this._updateVAO = [];
  62081. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  62082. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  62083. // Render VAO
  62084. this._renderVAO = [];
  62085. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  62086. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  62087. // Links
  62088. this._sourceBuffer = this._buffer0;
  62089. this._targetBuffer = this._buffer1;
  62090. };
  62091. /** @hidden */
  62092. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  62093. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  62094. if (this._isBillboardBased) {
  62095. defines += "\n#define BILLBOARD";
  62096. }
  62097. if (this._colorGradientsTexture) {
  62098. defines += "\n#define COLORGRADIENTS";
  62099. }
  62100. if (this._sizeGradientsTexture) {
  62101. defines += "\n#define SIZEGRADIENTS";
  62102. }
  62103. if (this._angularSpeedGradientsTexture) {
  62104. defines += "\n#define ANGULARSPEEDGRADIENTS";
  62105. }
  62106. if (this._velocityGradientsTexture) {
  62107. defines += "\n#define VELOCITYGRADIENTS";
  62108. }
  62109. if (this._limitVelocityGradientsTexture) {
  62110. defines += "\n#define LIMITVELOCITYGRADIENTS";
  62111. }
  62112. if (this._dragGradientsTexture) {
  62113. defines += "\n#define DRAGGRADIENTS";
  62114. }
  62115. if (this.isAnimationSheetEnabled) {
  62116. defines += "\n#define ANIMATESHEET";
  62117. if (this.spriteRandomStartCell) {
  62118. defines += "\n#define ANIMATESHEETRANDOMSTART";
  62119. }
  62120. }
  62121. if (this.noiseTexture) {
  62122. defines += "\n#define NOISE";
  62123. }
  62124. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  62125. return;
  62126. }
  62127. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  62128. if (!this._colorGradientsTexture) {
  62129. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  62130. }
  62131. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  62132. if (!this._isBillboardBased) {
  62133. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  62134. }
  62135. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  62136. if (this.isAnimationSheetEnabled) {
  62137. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  62138. if (this.spriteRandomStartCell) {
  62139. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  62140. }
  62141. }
  62142. if (this.noiseTexture) {
  62143. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  62144. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  62145. }
  62146. this._updateEffectOptions.defines = defines;
  62147. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  62148. };
  62149. /** @hidden */
  62150. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  62151. var defines = "";
  62152. if (this._scene.clipPlane) {
  62153. defines = "\n#define CLIPPLANE";
  62154. }
  62155. if (this._scene.clipPlane2) {
  62156. defines = "\n#define CLIPPLANE2";
  62157. }
  62158. if (this._scene.clipPlane3) {
  62159. defines = "\n#define CLIPPLANE3";
  62160. }
  62161. if (this._scene.clipPlane4) {
  62162. defines = "\n#define CLIPPLANE4";
  62163. }
  62164. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  62165. defines = "\n#define BLENDMULTIPLYMODE";
  62166. }
  62167. if (this._isBillboardBased) {
  62168. defines += "\n#define BILLBOARD";
  62169. switch (this.billboardMode) {
  62170. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  62171. defines += "\n#define BILLBOARDY";
  62172. break;
  62173. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  62174. default:
  62175. break;
  62176. }
  62177. }
  62178. if (this._colorGradientsTexture) {
  62179. defines += "\n#define COLORGRADIENTS";
  62180. }
  62181. if (this.isAnimationSheetEnabled) {
  62182. defines += "\n#define ANIMATESHEET";
  62183. }
  62184. if (this._imageProcessingConfiguration) {
  62185. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  62186. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  62187. }
  62188. if (this._renderEffect && this._renderEffect.defines === defines) {
  62189. return;
  62190. }
  62191. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  62192. var samplers = ["textureSampler", "colorGradientSampler"];
  62193. if (BABYLON.ImageProcessingConfiguration) {
  62194. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  62195. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  62196. }
  62197. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  62198. };
  62199. /**
  62200. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  62201. * @param preWarm defines if we are in the pre-warmimg phase
  62202. */
  62203. GPUParticleSystem.prototype.animate = function (preWarm) {
  62204. if (preWarm === void 0) { preWarm = false; }
  62205. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  62206. this._actualFrame += this._timeDelta;
  62207. if (!this._stopped) {
  62208. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  62209. this.stop();
  62210. }
  62211. }
  62212. };
  62213. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  62214. var texture = this[textureName];
  62215. if (!factorGradients || !factorGradients.length || texture) {
  62216. return;
  62217. }
  62218. var data = new Float32Array(this._rawTextureWidth);
  62219. for (var x = 0; x < this._rawTextureWidth; x++) {
  62220. var ratio = x / this._rawTextureWidth;
  62221. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  62222. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  62223. });
  62224. }
  62225. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  62226. };
  62227. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  62228. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  62229. };
  62230. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  62231. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  62232. };
  62233. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  62234. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  62235. };
  62236. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  62237. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  62238. };
  62239. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  62240. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  62241. };
  62242. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  62243. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  62244. return;
  62245. }
  62246. var data = new Uint8Array(this._rawTextureWidth * 4);
  62247. var tmpColor = BABYLON.Tmp.Color4[0];
  62248. for (var x = 0; x < this._rawTextureWidth; x++) {
  62249. var ratio = x / this._rawTextureWidth;
  62250. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  62251. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  62252. data[x * 4] = tmpColor.r * 255;
  62253. data[x * 4 + 1] = tmpColor.g * 255;
  62254. data[x * 4 + 2] = tmpColor.b * 255;
  62255. data[x * 4 + 3] = tmpColor.a * 255;
  62256. });
  62257. }
  62258. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  62259. };
  62260. /**
  62261. * Renders the particle system in its current state
  62262. * @param preWarm defines if the system should only update the particles but not render them
  62263. * @returns the current number of particles
  62264. */
  62265. GPUParticleSystem.prototype.render = function (preWarm) {
  62266. if (preWarm === void 0) { preWarm = false; }
  62267. if (!this._started) {
  62268. return 0;
  62269. }
  62270. this._createColorGradientTexture();
  62271. this._createSizeGradientTexture();
  62272. this._createAngularSpeedGradientTexture();
  62273. this._createVelocityGradientTexture();
  62274. this._createLimitVelocityGradientTexture();
  62275. this._createDragGradientTexture();
  62276. this._recreateUpdateEffect();
  62277. this._recreateRenderEffect();
  62278. if (!this.isReady()) {
  62279. return 0;
  62280. }
  62281. if (!preWarm) {
  62282. if (!this._preWarmDone && this.preWarmCycles) {
  62283. for (var index = 0; index < this.preWarmCycles; index++) {
  62284. this.animate(true);
  62285. this.render(true);
  62286. }
  62287. this._preWarmDone = true;
  62288. }
  62289. if (this._currentRenderId === this._scene.getRenderId()) {
  62290. return 0;
  62291. }
  62292. this._currentRenderId = this._scene.getRenderId();
  62293. }
  62294. // Get everything ready to render
  62295. this._initialize();
  62296. this._accumulatedCount += this.emitRate * this._timeDelta;
  62297. if (this._accumulatedCount > 1) {
  62298. var intPart = this._accumulatedCount | 0;
  62299. this._accumulatedCount -= intPart;
  62300. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  62301. }
  62302. if (!this._currentActiveCount) {
  62303. return 0;
  62304. }
  62305. // Enable update effect
  62306. this._engine.enableEffect(this._updateEffect);
  62307. this._engine.setState(false);
  62308. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  62309. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  62310. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  62311. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  62312. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  62313. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  62314. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  62315. if (!this._colorGradientsTexture) {
  62316. this._updateEffect.setDirectColor4("color1", this.color1);
  62317. this._updateEffect.setDirectColor4("color2", this.color2);
  62318. }
  62319. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  62320. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  62321. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  62322. this._updateEffect.setVector3("gravity", this.gravity);
  62323. if (this._sizeGradientsTexture) {
  62324. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  62325. }
  62326. if (this._angularSpeedGradientsTexture) {
  62327. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  62328. }
  62329. if (this._velocityGradientsTexture) {
  62330. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  62331. }
  62332. if (this._limitVelocityGradientsTexture) {
  62333. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  62334. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  62335. }
  62336. if (this._dragGradientsTexture) {
  62337. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  62338. }
  62339. if (this.particleEmitterType) {
  62340. this.particleEmitterType.applyToShader(this._updateEffect);
  62341. }
  62342. if (this._isAnimationSheetEnabled) {
  62343. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  62344. }
  62345. if (this.noiseTexture) {
  62346. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  62347. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  62348. }
  62349. var emitterWM;
  62350. if (this.emitter.position) {
  62351. var emitterMesh = this.emitter;
  62352. emitterWM = emitterMesh.getWorldMatrix();
  62353. }
  62354. else {
  62355. var emitterPosition = this.emitter;
  62356. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  62357. }
  62358. this._updateEffect.setMatrix("emitterWM", emitterWM);
  62359. // Bind source VAO
  62360. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  62361. // Update
  62362. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  62363. this._engine.setRasterizerState(false);
  62364. this._engine.beginTransformFeedback(true);
  62365. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  62366. this._engine.endTransformFeedback();
  62367. this._engine.setRasterizerState(true);
  62368. this._engine.bindTransformFeedbackBuffer(null);
  62369. if (!preWarm) {
  62370. // Enable render effect
  62371. this._engine.enableEffect(this._renderEffect);
  62372. var viewMatrix = this._scene.getViewMatrix();
  62373. this._renderEffect.setMatrix("view", viewMatrix);
  62374. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  62375. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  62376. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  62377. if (this._colorGradientsTexture) {
  62378. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  62379. }
  62380. else {
  62381. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  62382. }
  62383. if (this._isAnimationSheetEnabled && this.particleTexture) {
  62384. var baseSize = this.particleTexture.getBaseSize();
  62385. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  62386. }
  62387. if (this._isBillboardBased) {
  62388. var camera = this._scene.activeCamera;
  62389. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  62390. }
  62391. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  62392. var invView = viewMatrix.clone();
  62393. invView.invert();
  62394. this._renderEffect.setMatrix("invView", invView);
  62395. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  62396. }
  62397. // image processing
  62398. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  62399. this._imageProcessingConfiguration.bind(this._renderEffect);
  62400. }
  62401. // Draw order
  62402. switch (this.blendMode) {
  62403. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  62404. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  62405. break;
  62406. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  62407. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  62408. break;
  62409. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  62410. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  62411. break;
  62412. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  62413. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  62414. break;
  62415. }
  62416. if (this.forceDepthWrite) {
  62417. this._engine.setDepthWrite(true);
  62418. }
  62419. // Bind source VAO
  62420. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  62421. // Render
  62422. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  62423. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62424. }
  62425. // Switch VAOs
  62426. this._targetIndex++;
  62427. if (this._targetIndex === 2) {
  62428. this._targetIndex = 0;
  62429. }
  62430. // Switch buffers
  62431. var tmpBuffer = this._sourceBuffer;
  62432. this._sourceBuffer = this._targetBuffer;
  62433. this._targetBuffer = tmpBuffer;
  62434. return this._currentActiveCount;
  62435. };
  62436. /**
  62437. * Rebuilds the particle system
  62438. */
  62439. GPUParticleSystem.prototype.rebuild = function () {
  62440. this._initialize(true);
  62441. };
  62442. GPUParticleSystem.prototype._releaseBuffers = function () {
  62443. if (this._buffer0) {
  62444. this._buffer0.dispose();
  62445. this._buffer0 = null;
  62446. }
  62447. if (this._buffer1) {
  62448. this._buffer1.dispose();
  62449. this._buffer1 = null;
  62450. }
  62451. if (this._spriteBuffer) {
  62452. this._spriteBuffer.dispose();
  62453. this._spriteBuffer = null;
  62454. }
  62455. };
  62456. GPUParticleSystem.prototype._releaseVAOs = function () {
  62457. if (!this._updateVAO) {
  62458. return;
  62459. }
  62460. for (var index = 0; index < this._updateVAO.length; index++) {
  62461. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  62462. }
  62463. this._updateVAO = [];
  62464. for (var index = 0; index < this._renderVAO.length; index++) {
  62465. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  62466. }
  62467. this._renderVAO = [];
  62468. };
  62469. /**
  62470. * Disposes the particle system and free the associated resources
  62471. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  62472. */
  62473. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  62474. if (disposeTexture === void 0) { disposeTexture = true; }
  62475. var index = this._scene.particleSystems.indexOf(this);
  62476. if (index > -1) {
  62477. this._scene.particleSystems.splice(index, 1);
  62478. }
  62479. this._releaseBuffers();
  62480. this._releaseVAOs();
  62481. if (this._colorGradientsTexture) {
  62482. this._colorGradientsTexture.dispose();
  62483. this._colorGradientsTexture = null;
  62484. }
  62485. if (this._sizeGradientsTexture) {
  62486. this._sizeGradientsTexture.dispose();
  62487. this._sizeGradientsTexture = null;
  62488. }
  62489. if (this._angularSpeedGradientsTexture) {
  62490. this._angularSpeedGradientsTexture.dispose();
  62491. this._angularSpeedGradientsTexture = null;
  62492. }
  62493. if (this._velocityGradientsTexture) {
  62494. this._velocityGradientsTexture.dispose();
  62495. this._velocityGradientsTexture = null;
  62496. }
  62497. if (this._limitVelocityGradientsTexture) {
  62498. this._limitVelocityGradientsTexture.dispose();
  62499. this._limitVelocityGradientsTexture = null;
  62500. }
  62501. if (this._dragGradientsTexture) {
  62502. this._dragGradientsTexture.dispose();
  62503. this._dragGradientsTexture = null;
  62504. }
  62505. if (this._randomTexture) {
  62506. this._randomTexture.dispose();
  62507. this._randomTexture = null;
  62508. }
  62509. if (this._randomTexture2) {
  62510. this._randomTexture2.dispose();
  62511. this._randomTexture2 = null;
  62512. }
  62513. if (disposeTexture && this.particleTexture) {
  62514. this.particleTexture.dispose();
  62515. this.particleTexture = null;
  62516. }
  62517. if (disposeTexture && this.noiseTexture) {
  62518. this.noiseTexture.dispose();
  62519. this.noiseTexture = null;
  62520. }
  62521. // Callback
  62522. this.onDisposeObservable.notifyObservers(this);
  62523. this.onDisposeObservable.clear();
  62524. };
  62525. /**
  62526. * Clones the particle system.
  62527. * @param name The name of the cloned object
  62528. * @param newEmitter The new emitter to use
  62529. * @returns the cloned particle system
  62530. */
  62531. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  62532. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  62533. BABYLON.Tools.DeepCopy(this, result);
  62534. if (newEmitter === undefined) {
  62535. newEmitter = this.emitter;
  62536. }
  62537. result.emitter = newEmitter;
  62538. if (this.particleTexture) {
  62539. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  62540. }
  62541. return result;
  62542. };
  62543. /**
  62544. * Serializes the particle system to a JSON object.
  62545. * @returns the JSON object
  62546. */
  62547. GPUParticleSystem.prototype.serialize = function () {
  62548. var serializationObject = {};
  62549. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  62550. serializationObject.activeParticleCount = this.activeParticleCount;
  62551. return serializationObject;
  62552. };
  62553. /**
  62554. * Parses a JSON object to create a GPU particle system.
  62555. * @param parsedParticleSystem The JSON object to parse
  62556. * @param scene The scene to create the particle system in
  62557. * @param rootUrl The root url to use to load external dependencies like texture
  62558. * @returns the parsed GPU particle system
  62559. */
  62560. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  62561. var name = parsedParticleSystem.name;
  62562. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  62563. if (parsedParticleSystem.activeParticleCount) {
  62564. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  62565. }
  62566. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  62567. return particleSystem;
  62568. };
  62569. return GPUParticleSystem;
  62570. }(BABYLON.BaseParticleSystem));
  62571. BABYLON.GPUParticleSystem = GPUParticleSystem;
  62572. })(BABYLON || (BABYLON = {}));
  62573. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  62574. var BABYLON;
  62575. (function (BABYLON) {
  62576. /**
  62577. * Represents one particle of a solid particle system.
  62578. */
  62579. var SolidParticle = /** @class */ (function () {
  62580. /**
  62581. * Creates a Solid Particle object.
  62582. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  62583. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  62584. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  62585. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  62586. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  62587. * @param shapeId (integer) is the model shape identifier in the SPS.
  62588. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  62589. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  62590. */
  62591. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  62592. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  62593. /**
  62594. * particle global index
  62595. */
  62596. this.idx = 0;
  62597. /**
  62598. * The color of the particle
  62599. */
  62600. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  62601. /**
  62602. * The world space position of the particle.
  62603. */
  62604. this.position = BABYLON.Vector3.Zero();
  62605. /**
  62606. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  62607. */
  62608. this.rotation = BABYLON.Vector3.Zero();
  62609. /**
  62610. * The scaling of the particle.
  62611. */
  62612. this.scaling = BABYLON.Vector3.One();
  62613. /**
  62614. * The uvs of the particle.
  62615. */
  62616. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  62617. /**
  62618. * The current speed of the particle.
  62619. */
  62620. this.velocity = BABYLON.Vector3.Zero();
  62621. /**
  62622. * The pivot point in the particle local space.
  62623. */
  62624. this.pivot = BABYLON.Vector3.Zero();
  62625. /**
  62626. * Must the particle be translated from its pivot point in its local space ?
  62627. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  62628. * Default : false
  62629. */
  62630. this.translateFromPivot = false;
  62631. /**
  62632. * Is the particle active or not ?
  62633. */
  62634. this.alive = true;
  62635. /**
  62636. * Is the particle visible or not ?
  62637. */
  62638. this.isVisible = true;
  62639. /**
  62640. * Index of this particle in the global "positions" array (Internal use)
  62641. * @hidden
  62642. */
  62643. this._pos = 0;
  62644. /**
  62645. * @hidden Index of this particle in the global "indices" array (Internal use)
  62646. */
  62647. this._ind = 0;
  62648. /**
  62649. * ModelShape id of this particle
  62650. */
  62651. this.shapeId = 0;
  62652. /**
  62653. * Index of the particle in its shape id (Internal use)
  62654. */
  62655. this.idxInShape = 0;
  62656. /**
  62657. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  62658. */
  62659. this._stillInvisible = false;
  62660. /**
  62661. * @hidden Last computed particle rotation matrix
  62662. */
  62663. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  62664. /**
  62665. * Parent particle Id, if any.
  62666. * Default null.
  62667. */
  62668. this.parentId = null;
  62669. /**
  62670. * @hidden Internal global position in the SPS.
  62671. */
  62672. this._globalPosition = BABYLON.Vector3.Zero();
  62673. this.idx = particleIndex;
  62674. this._pos = positionIndex;
  62675. this._ind = indiceIndex;
  62676. this._model = model;
  62677. this.shapeId = shapeId;
  62678. this.idxInShape = idxInShape;
  62679. this._sps = sps;
  62680. if (modelBoundingInfo) {
  62681. this._modelBoundingInfo = modelBoundingInfo;
  62682. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  62683. }
  62684. }
  62685. Object.defineProperty(SolidParticle.prototype, "scale", {
  62686. /**
  62687. * Legacy support, changed scale to scaling
  62688. */
  62689. get: function () {
  62690. return this.scaling;
  62691. },
  62692. /**
  62693. * Legacy support, changed scale to scaling
  62694. */
  62695. set: function (scale) {
  62696. this.scaling = scale;
  62697. },
  62698. enumerable: true,
  62699. configurable: true
  62700. });
  62701. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  62702. /**
  62703. * Legacy support, changed quaternion to rotationQuaternion
  62704. */
  62705. get: function () {
  62706. return this.rotationQuaternion;
  62707. },
  62708. /**
  62709. * Legacy support, changed quaternion to rotationQuaternion
  62710. */
  62711. set: function (q) {
  62712. this.rotationQuaternion = q;
  62713. },
  62714. enumerable: true,
  62715. configurable: true
  62716. });
  62717. /**
  62718. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  62719. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  62720. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  62721. * @returns true if it intersects
  62722. */
  62723. SolidParticle.prototype.intersectsMesh = function (target) {
  62724. if (!this._boundingInfo || !target._boundingInfo) {
  62725. return false;
  62726. }
  62727. if (this._sps._bSphereOnly) {
  62728. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  62729. }
  62730. return this._boundingInfo.intersects(target._boundingInfo, false);
  62731. };
  62732. return SolidParticle;
  62733. }());
  62734. BABYLON.SolidParticle = SolidParticle;
  62735. /**
  62736. * Represents the shape of the model used by one particle of a solid particle system.
  62737. * SPS internal tool, don't use it manually.
  62738. */
  62739. var ModelShape = /** @class */ (function () {
  62740. /**
  62741. * 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.
  62742. * SPS internal tool, don't use it manually.
  62743. * @hidden
  62744. */
  62745. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  62746. /**
  62747. * length of the shape in the model indices array (internal use)
  62748. * @hidden
  62749. */
  62750. this._indicesLength = 0;
  62751. this.shapeID = id;
  62752. this._shape = shape;
  62753. this._indicesLength = indicesLength;
  62754. this._shapeUV = shapeUV;
  62755. this._positionFunction = posFunction;
  62756. this._vertexFunction = vtxFunction;
  62757. }
  62758. return ModelShape;
  62759. }());
  62760. BABYLON.ModelShape = ModelShape;
  62761. /**
  62762. * Represents a Depth Sorted Particle in the solid particle system.
  62763. */
  62764. var DepthSortedParticle = /** @class */ (function () {
  62765. function DepthSortedParticle() {
  62766. /**
  62767. * Index of the particle in the "indices" array
  62768. */
  62769. this.ind = 0;
  62770. /**
  62771. * Length of the particle shape in the "indices" array
  62772. */
  62773. this.indicesLength = 0;
  62774. /**
  62775. * Squared distance from the particle to the camera
  62776. */
  62777. this.sqDistance = 0.0;
  62778. }
  62779. return DepthSortedParticle;
  62780. }());
  62781. BABYLON.DepthSortedParticle = DepthSortedParticle;
  62782. })(BABYLON || (BABYLON = {}));
  62783. //# sourceMappingURL=babylon.solidParticle.js.map
  62784. var BABYLON;
  62785. (function (BABYLON) {
  62786. /**
  62787. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  62788. *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.
  62789. * The SPS is also a particle system. It provides some methods to manage the particles.
  62790. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  62791. *
  62792. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  62793. */
  62794. var SolidParticleSystem = /** @class */ (function () {
  62795. /**
  62796. * Creates a SPS (Solid Particle System) object.
  62797. * @param name (String) is the SPS name, this will be the underlying mesh name.
  62798. * @param scene (Scene) is the scene in which the SPS is added.
  62799. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  62800. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  62801. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  62802. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  62803. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  62804. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  62805. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  62806. */
  62807. function SolidParticleSystem(name, scene, options) {
  62808. /**
  62809. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  62810. * Example : var p = SPS.particles[i];
  62811. */
  62812. this.particles = new Array();
  62813. /**
  62814. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  62815. */
  62816. this.nbParticles = 0;
  62817. /**
  62818. * If the particles must ever face the camera (default false). Useful for planar particles.
  62819. */
  62820. this.billboard = false;
  62821. /**
  62822. * Recompute normals when adding a shape
  62823. */
  62824. this.recomputeNormals = true;
  62825. /**
  62826. * This a counter ofr your own usage. It's not set by any SPS functions.
  62827. */
  62828. this.counter = 0;
  62829. /**
  62830. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  62831. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  62832. */
  62833. this.vars = {};
  62834. /**
  62835. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  62836. * @hidden
  62837. */
  62838. this._bSphereOnly = false;
  62839. /**
  62840. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  62841. * @hidden
  62842. */
  62843. this._bSphereRadiusFactor = 1.0;
  62844. this._positions = new Array();
  62845. this._indices = new Array();
  62846. this._normals = new Array();
  62847. this._colors = new Array();
  62848. this._uvs = new Array();
  62849. this._index = 0; // indices index
  62850. this._updatable = true;
  62851. this._pickable = false;
  62852. this._isVisibilityBoxLocked = false;
  62853. this._alwaysVisible = false;
  62854. this._depthSort = false;
  62855. this._shapeCounter = 0;
  62856. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  62857. this._color = new BABYLON.Color4(0, 0, 0, 0);
  62858. this._computeParticleColor = true;
  62859. this._computeParticleTexture = true;
  62860. this._computeParticleRotation = true;
  62861. this._computeParticleVertex = false;
  62862. this._computeBoundingBox = false;
  62863. this._depthSortParticles = true;
  62864. this._cam_axisZ = BABYLON.Vector3.Zero();
  62865. this._cam_axisY = BABYLON.Vector3.Zero();
  62866. this._cam_axisX = BABYLON.Vector3.Zero();
  62867. this._axisZ = BABYLON.Axis.Z;
  62868. this._camDir = BABYLON.Vector3.Zero();
  62869. this._camInvertedPosition = BABYLON.Vector3.Zero();
  62870. this._rotMatrix = new BABYLON.Matrix();
  62871. this._invertMatrix = new BABYLON.Matrix();
  62872. this._rotated = BABYLON.Vector3.Zero();
  62873. this._quaternion = new BABYLON.Quaternion();
  62874. this._vertex = BABYLON.Vector3.Zero();
  62875. this._normal = BABYLON.Vector3.Zero();
  62876. this._yaw = 0.0;
  62877. this._pitch = 0.0;
  62878. this._roll = 0.0;
  62879. this._halfroll = 0.0;
  62880. this._halfpitch = 0.0;
  62881. this._halfyaw = 0.0;
  62882. this._sinRoll = 0.0;
  62883. this._cosRoll = 0.0;
  62884. this._sinPitch = 0.0;
  62885. this._cosPitch = 0.0;
  62886. this._sinYaw = 0.0;
  62887. this._cosYaw = 0.0;
  62888. this._mustUnrotateFixedNormals = false;
  62889. this._minimum = BABYLON.Vector3.Zero();
  62890. this._maximum = BABYLON.Vector3.Zero();
  62891. this._minBbox = BABYLON.Vector3.Zero();
  62892. this._maxBbox = BABYLON.Vector3.Zero();
  62893. this._particlesIntersect = false;
  62894. this._depthSortFunction = function (p1, p2) {
  62895. return (p2.sqDistance - p1.sqDistance);
  62896. };
  62897. this._needs32Bits = false;
  62898. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  62899. this._scaledPivot = BABYLON.Vector3.Zero();
  62900. this._particleHasParent = false;
  62901. this.name = name;
  62902. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62903. this._camera = scene.activeCamera;
  62904. this._pickable = options ? options.isPickable : false;
  62905. this._depthSort = options ? options.enableDepthSort : false;
  62906. this._particlesIntersect = options ? options.particleIntersection : false;
  62907. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  62908. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  62909. if (options && options.updatable !== undefined) {
  62910. this._updatable = options.updatable;
  62911. }
  62912. else {
  62913. this._updatable = true;
  62914. }
  62915. if (this._pickable) {
  62916. this.pickedParticles = [];
  62917. }
  62918. if (this._depthSort) {
  62919. this.depthSortedParticles = [];
  62920. }
  62921. }
  62922. /**
  62923. * Builds the SPS underlying mesh. Returns a standard Mesh.
  62924. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  62925. * @returns the created mesh
  62926. */
  62927. SolidParticleSystem.prototype.buildMesh = function () {
  62928. if (this.nbParticles === 0) {
  62929. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  62930. this.addShape(triangle, 1);
  62931. triangle.dispose();
  62932. }
  62933. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  62934. this._positions32 = new Float32Array(this._positions);
  62935. this._uvs32 = new Float32Array(this._uvs);
  62936. this._colors32 = new Float32Array(this._colors);
  62937. if (this.recomputeNormals) {
  62938. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  62939. }
  62940. this._normals32 = new Float32Array(this._normals);
  62941. this._fixedNormal32 = new Float32Array(this._normals);
  62942. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  62943. this._unrotateFixedNormals();
  62944. }
  62945. var vertexData = new BABYLON.VertexData();
  62946. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  62947. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  62948. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  62949. if (this._uvs32.length > 0) {
  62950. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  62951. }
  62952. if (this._colors32.length > 0) {
  62953. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  62954. }
  62955. var mesh = new BABYLON.Mesh(this.name, this._scene);
  62956. vertexData.applyToMesh(mesh, this._updatable);
  62957. this.mesh = mesh;
  62958. this.mesh.isPickable = this._pickable;
  62959. // free memory
  62960. if (!this._depthSort) {
  62961. this._indices = null;
  62962. }
  62963. this._positions = null;
  62964. this._normals = null;
  62965. this._uvs = null;
  62966. this._colors = null;
  62967. if (!this._updatable) {
  62968. this.particles.length = 0;
  62969. }
  62970. return mesh;
  62971. };
  62972. /**
  62973. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  62974. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  62975. * Thus the particles generated from `digest()` have their property `position` set yet.
  62976. * @param mesh ( Mesh ) is the mesh to be digested
  62977. * @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
  62978. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  62979. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  62980. * @returns the current SPS
  62981. */
  62982. SolidParticleSystem.prototype.digest = function (mesh, options) {
  62983. var size = (options && options.facetNb) || 1;
  62984. var number = (options && options.number) || 0;
  62985. var delta = (options && options.delta) || 0;
  62986. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62987. var meshInd = mesh.getIndices();
  62988. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62989. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62990. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62991. var f = 0; // facet counter
  62992. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  62993. // compute size from number
  62994. if (number) {
  62995. number = (number > totalFacets) ? totalFacets : number;
  62996. size = Math.round(totalFacets / number);
  62997. delta = 0;
  62998. }
  62999. else {
  63000. size = (size > totalFacets) ? totalFacets : size;
  63001. }
  63002. var facetPos = []; // submesh positions
  63003. var facetInd = []; // submesh indices
  63004. var facetUV = []; // submesh UV
  63005. var facetCol = []; // submesh colors
  63006. var barycenter = BABYLON.Vector3.Zero();
  63007. var sizeO = size;
  63008. while (f < totalFacets) {
  63009. size = sizeO + Math.floor((1 + delta) * Math.random());
  63010. if (f > totalFacets - size) {
  63011. size = totalFacets - f;
  63012. }
  63013. // reset temp arrays
  63014. facetPos.length = 0;
  63015. facetInd.length = 0;
  63016. facetUV.length = 0;
  63017. facetCol.length = 0;
  63018. // iterate over "size" facets
  63019. var fi = 0;
  63020. for (var j = f * 3; j < (f + size) * 3; j++) {
  63021. facetInd.push(fi);
  63022. var i = meshInd[j];
  63023. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  63024. if (meshUV) {
  63025. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  63026. }
  63027. if (meshCol) {
  63028. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  63029. }
  63030. fi++;
  63031. }
  63032. // create a model shape for each single particle
  63033. var idx = this.nbParticles;
  63034. var shape = this._posToShape(facetPos);
  63035. var shapeUV = this._uvsToShapeUV(facetUV);
  63036. // compute the barycenter of the shape
  63037. var v;
  63038. for (v = 0; v < shape.length; v++) {
  63039. barycenter.addInPlace(shape[v]);
  63040. }
  63041. barycenter.scaleInPlace(1 / shape.length);
  63042. // shift the shape from its barycenter to the origin
  63043. for (v = 0; v < shape.length; v++) {
  63044. shape[v].subtractInPlace(barycenter);
  63045. }
  63046. var bInfo;
  63047. if (this._particlesIntersect) {
  63048. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  63049. }
  63050. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  63051. // add the particle in the SPS
  63052. var currentPos = this._positions.length;
  63053. var currentInd = this._indices.length;
  63054. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  63055. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  63056. // initialize the particle position
  63057. this.particles[this.nbParticles].position.addInPlace(barycenter);
  63058. this._index += shape.length;
  63059. idx++;
  63060. this.nbParticles++;
  63061. this._shapeCounter++;
  63062. f += size;
  63063. }
  63064. return this;
  63065. };
  63066. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  63067. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  63068. var index = 0;
  63069. var idx = 0;
  63070. for (var p = 0; p < this.particles.length; p++) {
  63071. this._particle = this.particles[p];
  63072. this._shape = this._particle._model._shape;
  63073. if (this._particle.rotationQuaternion) {
  63074. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  63075. }
  63076. else {
  63077. this._yaw = this._particle.rotation.y;
  63078. this._pitch = this._particle.rotation.x;
  63079. this._roll = this._particle.rotation.z;
  63080. this._quaternionRotationYPR();
  63081. }
  63082. this._quaternionToRotationMatrix();
  63083. this._rotMatrix.invertToRef(this._invertMatrix);
  63084. for (var pt = 0; pt < this._shape.length; pt++) {
  63085. idx = index + pt * 3;
  63086. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  63087. this._fixedNormal32[idx] = this._normal.x;
  63088. this._fixedNormal32[idx + 1] = this._normal.y;
  63089. this._fixedNormal32[idx + 2] = this._normal.z;
  63090. }
  63091. index = idx + 3;
  63092. }
  63093. };
  63094. //reset copy
  63095. SolidParticleSystem.prototype._resetCopy = function () {
  63096. this._copy.position.x = 0;
  63097. this._copy.position.y = 0;
  63098. this._copy.position.z = 0;
  63099. this._copy.rotation.x = 0;
  63100. this._copy.rotation.y = 0;
  63101. this._copy.rotation.z = 0;
  63102. this._copy.rotationQuaternion = null;
  63103. this._copy.scaling.x = 1.0;
  63104. this._copy.scaling.y = 1.0;
  63105. this._copy.scaling.z = 1.0;
  63106. this._copy.uvs.x = 0;
  63107. this._copy.uvs.y = 0;
  63108. this._copy.uvs.z = 1.0;
  63109. this._copy.uvs.w = 1.0;
  63110. this._copy.color = null;
  63111. this._copy.translateFromPivot = false;
  63112. };
  63113. // _meshBuilder : inserts the shape model in the global SPS mesh
  63114. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  63115. var i;
  63116. var u = 0;
  63117. var c = 0;
  63118. var n = 0;
  63119. this._resetCopy();
  63120. if (options && options.positionFunction) { // call to custom positionFunction
  63121. options.positionFunction(this._copy, idx, idxInShape);
  63122. this._mustUnrotateFixedNormals = true;
  63123. }
  63124. if (this._copy.rotationQuaternion) {
  63125. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  63126. }
  63127. else {
  63128. this._yaw = this._copy.rotation.y;
  63129. this._pitch = this._copy.rotation.x;
  63130. this._roll = this._copy.rotation.z;
  63131. this._quaternionRotationYPR();
  63132. }
  63133. this._quaternionToRotationMatrix();
  63134. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  63135. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  63136. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  63137. if (this._copy.translateFromPivot) {
  63138. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  63139. }
  63140. else {
  63141. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  63142. }
  63143. for (i = 0; i < shape.length; i++) {
  63144. this._vertex.x = shape[i].x;
  63145. this._vertex.y = shape[i].y;
  63146. this._vertex.z = shape[i].z;
  63147. if (options && options.vertexFunction) {
  63148. options.vertexFunction(this._copy, this._vertex, i);
  63149. }
  63150. this._vertex.x *= this._copy.scaling.x;
  63151. this._vertex.y *= this._copy.scaling.y;
  63152. this._vertex.z *= this._copy.scaling.z;
  63153. this._vertex.x -= this._scaledPivot.x;
  63154. this._vertex.y -= this._scaledPivot.y;
  63155. this._vertex.z -= this._scaledPivot.z;
  63156. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  63157. this._rotated.addInPlace(this._pivotBackTranslation);
  63158. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  63159. if (meshUV) {
  63160. 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);
  63161. u += 2;
  63162. }
  63163. if (this._copy.color) {
  63164. this._color = this._copy.color;
  63165. }
  63166. else if (meshCol && meshCol[c] !== undefined) {
  63167. this._color.r = meshCol[c];
  63168. this._color.g = meshCol[c + 1];
  63169. this._color.b = meshCol[c + 2];
  63170. this._color.a = meshCol[c + 3];
  63171. }
  63172. else {
  63173. this._color.r = 1.0;
  63174. this._color.g = 1.0;
  63175. this._color.b = 1.0;
  63176. this._color.a = 1.0;
  63177. }
  63178. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  63179. c += 4;
  63180. if (!this.recomputeNormals && meshNor) {
  63181. this._normal.x = meshNor[n];
  63182. this._normal.y = meshNor[n + 1];
  63183. this._normal.z = meshNor[n + 2];
  63184. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  63185. normals.push(this._normal.x, this._normal.y, this._normal.z);
  63186. n += 3;
  63187. }
  63188. }
  63189. for (i = 0; i < meshInd.length; i++) {
  63190. var current_ind = p + meshInd[i];
  63191. indices.push(current_ind);
  63192. if (current_ind > 65535) {
  63193. this._needs32Bits = true;
  63194. }
  63195. }
  63196. if (this._pickable) {
  63197. var nbfaces = meshInd.length / 3;
  63198. for (i = 0; i < nbfaces; i++) {
  63199. this.pickedParticles.push({ idx: idx, faceId: i });
  63200. }
  63201. }
  63202. if (this._depthSort) {
  63203. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  63204. }
  63205. return this._copy;
  63206. };
  63207. // returns a shape array from positions array
  63208. SolidParticleSystem.prototype._posToShape = function (positions) {
  63209. var shape = [];
  63210. for (var i = 0; i < positions.length; i += 3) {
  63211. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  63212. }
  63213. return shape;
  63214. };
  63215. // returns a shapeUV array from a Vector4 uvs
  63216. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  63217. var shapeUV = [];
  63218. if (uvs) {
  63219. for (var i = 0; i < uvs.length; i++)
  63220. shapeUV.push(uvs[i]);
  63221. }
  63222. return shapeUV;
  63223. };
  63224. // adds a new particle object in the particles array
  63225. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  63226. if (bInfo === void 0) { bInfo = null; }
  63227. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  63228. this.particles.push(sp);
  63229. return sp;
  63230. };
  63231. /**
  63232. * Adds some particles to the SPS from the model shape. Returns the shape id.
  63233. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  63234. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  63235. * @param nb (positive integer) the number of particles to be created from this model
  63236. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  63237. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  63238. * @returns the number of shapes in the system
  63239. */
  63240. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  63241. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63242. var meshInd = mesh.getIndices();
  63243. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63244. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63245. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63246. var bbInfo;
  63247. if (this._particlesIntersect) {
  63248. bbInfo = mesh.getBoundingInfo();
  63249. }
  63250. var shape = this._posToShape(meshPos);
  63251. var shapeUV = this._uvsToShapeUV(meshUV);
  63252. var posfunc = options ? options.positionFunction : null;
  63253. var vtxfunc = options ? options.vertexFunction : null;
  63254. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  63255. // particles
  63256. var sp;
  63257. var currentCopy;
  63258. var idx = this.nbParticles;
  63259. for (var i = 0; i < nb; i++) {
  63260. var currentPos = this._positions.length;
  63261. var currentInd = this._indices.length;
  63262. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  63263. if (this._updatable) {
  63264. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  63265. sp.position.copyFrom(currentCopy.position);
  63266. sp.rotation.copyFrom(currentCopy.rotation);
  63267. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  63268. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  63269. }
  63270. if (currentCopy.color && sp.color) {
  63271. sp.color.copyFrom(currentCopy.color);
  63272. }
  63273. sp.scaling.copyFrom(currentCopy.scaling);
  63274. sp.uvs.copyFrom(currentCopy.uvs);
  63275. }
  63276. this._index += shape.length;
  63277. idx++;
  63278. }
  63279. this.nbParticles += nb;
  63280. this._shapeCounter++;
  63281. return this._shapeCounter - 1;
  63282. };
  63283. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  63284. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  63285. this._resetCopy();
  63286. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  63287. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  63288. }
  63289. if (this._copy.rotationQuaternion) {
  63290. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  63291. }
  63292. else {
  63293. this._yaw = this._copy.rotation.y;
  63294. this._pitch = this._copy.rotation.x;
  63295. this._roll = this._copy.rotation.z;
  63296. this._quaternionRotationYPR();
  63297. }
  63298. this._quaternionToRotationMatrix();
  63299. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  63300. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  63301. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  63302. if (this._copy.translateFromPivot) {
  63303. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  63304. }
  63305. else {
  63306. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  63307. }
  63308. this._shape = particle._model._shape;
  63309. for (var pt = 0; pt < this._shape.length; pt++) {
  63310. this._vertex.x = this._shape[pt].x;
  63311. this._vertex.y = this._shape[pt].y;
  63312. this._vertex.z = this._shape[pt].z;
  63313. if (particle._model._vertexFunction) {
  63314. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  63315. }
  63316. this._vertex.x *= this._copy.scaling.x;
  63317. this._vertex.y *= this._copy.scaling.y;
  63318. this._vertex.z *= this._copy.scaling.z;
  63319. this._vertex.x -= this._scaledPivot.x;
  63320. this._vertex.y -= this._scaledPivot.y;
  63321. this._vertex.z -= this._scaledPivot.z;
  63322. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  63323. this._rotated.addInPlace(this._pivotBackTranslation);
  63324. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  63325. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  63326. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  63327. }
  63328. particle.position.x = 0.0;
  63329. particle.position.y = 0.0;
  63330. particle.position.z = 0.0;
  63331. particle.rotation.x = 0.0;
  63332. particle.rotation.y = 0.0;
  63333. particle.rotation.z = 0.0;
  63334. particle.rotationQuaternion = null;
  63335. particle.scaling.x = 1.0;
  63336. particle.scaling.y = 1.0;
  63337. particle.scaling.z = 1.0;
  63338. particle.uvs.x = 0.0;
  63339. particle.uvs.y = 0.0;
  63340. particle.uvs.z = 1.0;
  63341. particle.uvs.w = 1.0;
  63342. particle.pivot.x = 0.0;
  63343. particle.pivot.y = 0.0;
  63344. particle.pivot.z = 0.0;
  63345. particle.translateFromPivot = false;
  63346. particle.parentId = null;
  63347. };
  63348. /**
  63349. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  63350. * @returns the SPS.
  63351. */
  63352. SolidParticleSystem.prototype.rebuildMesh = function () {
  63353. for (var p = 0; p < this.particles.length; p++) {
  63354. this._rebuildParticle(this.particles[p]);
  63355. }
  63356. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63357. return this;
  63358. };
  63359. /**
  63360. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  63361. * This method calls `updateParticle()` for each particle of the SPS.
  63362. * For an animated SPS, it is usually called within the render loop.
  63363. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  63364. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  63365. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  63366. * @returns the SPS.
  63367. */
  63368. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  63369. if (start === void 0) { start = 0; }
  63370. if (end === void 0) { end = this.nbParticles - 1; }
  63371. if (update === void 0) { update = true; }
  63372. if (!this._updatable) {
  63373. return this;
  63374. }
  63375. // custom beforeUpdate
  63376. this.beforeUpdateParticles(start, end, update);
  63377. this._cam_axisX.x = 1.0;
  63378. this._cam_axisX.y = 0.0;
  63379. this._cam_axisX.z = 0.0;
  63380. this._cam_axisY.x = 0.0;
  63381. this._cam_axisY.y = 1.0;
  63382. this._cam_axisY.z = 0.0;
  63383. this._cam_axisZ.x = 0.0;
  63384. this._cam_axisZ.y = 0.0;
  63385. this._cam_axisZ.z = 1.0;
  63386. // cases when the World Matrix is to be computed first
  63387. if (this.billboard || this._depthSort) {
  63388. this.mesh.computeWorldMatrix(true);
  63389. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  63390. }
  63391. // if the particles will always face the camera
  63392. if (this.billboard) {
  63393. // compute the camera position and un-rotate it by the current mesh rotation
  63394. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  63395. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  63396. this._cam_axisZ.normalize();
  63397. // same for camera up vector extracted from the cam view matrix
  63398. var view = this._camera.getViewMatrix(true);
  63399. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  63400. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  63401. this._cam_axisY.normalize();
  63402. this._cam_axisX.normalize();
  63403. }
  63404. // if depthSort, compute the camera global position in the mesh local system
  63405. if (this._depthSort) {
  63406. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  63407. }
  63408. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  63409. var idx = 0; // current position index in the global array positions32
  63410. var index = 0; // position start index in the global array positions32 of the current particle
  63411. var colidx = 0; // current color index in the global array colors32
  63412. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  63413. var uvidx = 0; // current uv index in the global array uvs32
  63414. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  63415. var pt = 0; // current index in the particle model shape
  63416. if (this.mesh.isFacetDataEnabled) {
  63417. this._computeBoundingBox = true;
  63418. }
  63419. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  63420. if (this._computeBoundingBox) {
  63421. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  63422. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  63423. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  63424. }
  63425. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  63426. if (this.mesh._boundingInfo) {
  63427. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  63428. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  63429. }
  63430. }
  63431. }
  63432. // particle loop
  63433. index = this.particles[start]._pos;
  63434. var vpos = (index / 3) | 0;
  63435. colorIndex = vpos * 4;
  63436. uvIndex = vpos * 2;
  63437. for (var p = start; p <= end; p++) {
  63438. this._particle = this.particles[p];
  63439. this._shape = this._particle._model._shape;
  63440. this._shapeUV = this._particle._model._shapeUV;
  63441. // call to custom user function to update the particle properties
  63442. this.updateParticle(this._particle);
  63443. // camera-particle distance for depth sorting
  63444. if (this._depthSort && this._depthSortParticles) {
  63445. var dsp = this.depthSortedParticles[p];
  63446. dsp.ind = this._particle._ind;
  63447. dsp.indicesLength = this._particle._model._indicesLength;
  63448. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  63449. }
  63450. // skip the computations for inactive or already invisible particles
  63451. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  63452. // increment indexes for the next particle
  63453. pt = this._shape.length;
  63454. index += pt * 3;
  63455. colorIndex += pt * 4;
  63456. uvIndex += pt * 2;
  63457. continue;
  63458. }
  63459. if (this._particle.isVisible) {
  63460. this._particle._stillInvisible = false; // un-mark permanent invisibility
  63461. this._particleHasParent = (this._particle.parentId !== null);
  63462. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  63463. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  63464. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  63465. // particle rotation matrix
  63466. if (this.billboard) {
  63467. this._particle.rotation.x = 0.0;
  63468. this._particle.rotation.y = 0.0;
  63469. }
  63470. if (this._computeParticleRotation || this.billboard) {
  63471. if (this._particle.rotationQuaternion) {
  63472. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  63473. }
  63474. else {
  63475. this._yaw = this._particle.rotation.y;
  63476. this._pitch = this._particle.rotation.x;
  63477. this._roll = this._particle.rotation.z;
  63478. this._quaternionRotationYPR();
  63479. }
  63480. this._quaternionToRotationMatrix();
  63481. }
  63482. if (this._particleHasParent) {
  63483. this._parent = this.particles[this._particle.parentId];
  63484. 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];
  63485. 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];
  63486. 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];
  63487. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  63488. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  63489. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  63490. if (this._computeParticleRotation || this.billboard) {
  63491. 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];
  63492. 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];
  63493. 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];
  63494. 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];
  63495. 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];
  63496. 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];
  63497. 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];
  63498. 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];
  63499. 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];
  63500. }
  63501. }
  63502. else {
  63503. this._particle._globalPosition.x = this._particle.position.x;
  63504. this._particle._globalPosition.y = this._particle.position.y;
  63505. this._particle._globalPosition.z = this._particle.position.z;
  63506. if (this._computeParticleRotation || this.billboard) {
  63507. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  63508. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  63509. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  63510. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  63511. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  63512. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  63513. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  63514. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  63515. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  63516. }
  63517. }
  63518. if (this._particle.translateFromPivot) {
  63519. this._pivotBackTranslation.x = 0.0;
  63520. this._pivotBackTranslation.y = 0.0;
  63521. this._pivotBackTranslation.z = 0.0;
  63522. }
  63523. else {
  63524. this._pivotBackTranslation.x = this._scaledPivot.x;
  63525. this._pivotBackTranslation.y = this._scaledPivot.y;
  63526. this._pivotBackTranslation.z = this._scaledPivot.z;
  63527. }
  63528. // particle vertex loop
  63529. for (pt = 0; pt < this._shape.length; pt++) {
  63530. idx = index + pt * 3;
  63531. colidx = colorIndex + pt * 4;
  63532. uvidx = uvIndex + pt * 2;
  63533. this._vertex.x = this._shape[pt].x;
  63534. this._vertex.y = this._shape[pt].y;
  63535. this._vertex.z = this._shape[pt].z;
  63536. if (this._computeParticleVertex) {
  63537. this.updateParticleVertex(this._particle, this._vertex, pt);
  63538. }
  63539. // positions
  63540. this._vertex.x *= this._particle.scaling.x;
  63541. this._vertex.y *= this._particle.scaling.y;
  63542. this._vertex.z *= this._particle.scaling.z;
  63543. this._vertex.x -= this._scaledPivot.x;
  63544. this._vertex.y -= this._scaledPivot.y;
  63545. this._vertex.z -= this._scaledPivot.z;
  63546. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63547. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63548. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63549. this._rotated.x += this._pivotBackTranslation.x;
  63550. this._rotated.y += this._pivotBackTranslation.y;
  63551. this._rotated.z += this._pivotBackTranslation.z;
  63552. 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;
  63553. 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;
  63554. 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;
  63555. if (this._computeBoundingBox) {
  63556. if (this._positions32[idx] < this._minimum.x) {
  63557. this._minimum.x = this._positions32[idx];
  63558. }
  63559. if (this._positions32[idx] > this._maximum.x) {
  63560. this._maximum.x = this._positions32[idx];
  63561. }
  63562. if (this._positions32[idx + 1] < this._minimum.y) {
  63563. this._minimum.y = this._positions32[idx + 1];
  63564. }
  63565. if (this._positions32[idx + 1] > this._maximum.y) {
  63566. this._maximum.y = this._positions32[idx + 1];
  63567. }
  63568. if (this._positions32[idx + 2] < this._minimum.z) {
  63569. this._minimum.z = this._positions32[idx + 2];
  63570. }
  63571. if (this._positions32[idx + 2] > this._maximum.z) {
  63572. this._maximum.z = this._positions32[idx + 2];
  63573. }
  63574. }
  63575. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  63576. if (!this._computeParticleVertex) {
  63577. this._normal.x = this._fixedNormal32[idx];
  63578. this._normal.y = this._fixedNormal32[idx + 1];
  63579. this._normal.z = this._fixedNormal32[idx + 2];
  63580. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  63581. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  63582. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  63583. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  63584. 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;
  63585. 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;
  63586. }
  63587. if (this._computeParticleColor && this._particle.color) {
  63588. this._colors32[colidx] = this._particle.color.r;
  63589. this._colors32[colidx + 1] = this._particle.color.g;
  63590. this._colors32[colidx + 2] = this._particle.color.b;
  63591. this._colors32[colidx + 3] = this._particle.color.a;
  63592. }
  63593. if (this._computeParticleTexture) {
  63594. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63595. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63596. }
  63597. }
  63598. }
  63599. // particle just set invisible : scaled to zero and positioned at the origin
  63600. else {
  63601. this._particle._stillInvisible = true; // mark the particle as invisible
  63602. for (pt = 0; pt < this._shape.length; pt++) {
  63603. idx = index + pt * 3;
  63604. colidx = colorIndex + pt * 4;
  63605. uvidx = uvIndex + pt * 2;
  63606. this._positions32[idx] = 0.0;
  63607. this._positions32[idx + 1] = 0.0;
  63608. this._positions32[idx + 2] = 0.0;
  63609. this._normals32[idx] = 0.0;
  63610. this._normals32[idx + 1] = 0.0;
  63611. this._normals32[idx + 2] = 0.0;
  63612. if (this._computeParticleColor && this._particle.color) {
  63613. this._colors32[colidx] = this._particle.color.r;
  63614. this._colors32[colidx + 1] = this._particle.color.g;
  63615. this._colors32[colidx + 2] = this._particle.color.b;
  63616. this._colors32[colidx + 3] = this._particle.color.a;
  63617. }
  63618. if (this._computeParticleTexture) {
  63619. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63620. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63621. }
  63622. }
  63623. }
  63624. // if the particle intersections must be computed : update the bbInfo
  63625. if (this._particlesIntersect) {
  63626. var bInfo = this._particle._boundingInfo;
  63627. var bBox = bInfo.boundingBox;
  63628. var bSphere = bInfo.boundingSphere;
  63629. if (!this._bSphereOnly) {
  63630. // place, scale and rotate the particle bbox within the SPS local system, then update it
  63631. for (var b = 0; b < bBox.vectors.length; b++) {
  63632. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  63633. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  63634. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  63635. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63636. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63637. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63638. 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;
  63639. 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;
  63640. 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;
  63641. }
  63642. bBox._update(this.mesh._worldMatrix);
  63643. }
  63644. // place and scale the particle bouding sphere in the SPS local system, then update it
  63645. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  63646. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  63647. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  63648. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  63649. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  63650. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  63651. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  63652. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  63653. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  63654. 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));
  63655. bSphere._update(this.mesh._worldMatrix);
  63656. }
  63657. // increment indexes for the next particle
  63658. index = idx + 3;
  63659. colorIndex = colidx + 4;
  63660. uvIndex = uvidx + 2;
  63661. }
  63662. // if the VBO must be updated
  63663. if (update) {
  63664. if (this._computeParticleColor) {
  63665. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  63666. }
  63667. if (this._computeParticleTexture) {
  63668. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  63669. }
  63670. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63671. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  63672. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  63673. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  63674. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  63675. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  63676. for (var i = 0; i < this._normals32.length; i++) {
  63677. this._fixedNormal32[i] = this._normals32[i];
  63678. }
  63679. }
  63680. if (!this.mesh.areNormalsFrozen) {
  63681. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  63682. }
  63683. }
  63684. if (this._depthSort && this._depthSortParticles) {
  63685. this.depthSortedParticles.sort(this._depthSortFunction);
  63686. var dspl = this.depthSortedParticles.length;
  63687. var sorted = 0;
  63688. var lind = 0;
  63689. var sind = 0;
  63690. var sid = 0;
  63691. for (sorted = 0; sorted < dspl; sorted++) {
  63692. lind = this.depthSortedParticles[sorted].indicesLength;
  63693. sind = this.depthSortedParticles[sorted].ind;
  63694. for (var i = 0; i < lind; i++) {
  63695. this._indices32[sid] = this._indices[sind + i];
  63696. sid++;
  63697. }
  63698. }
  63699. this.mesh.updateIndices(this._indices32);
  63700. }
  63701. }
  63702. if (this._computeBoundingBox) {
  63703. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  63704. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  63705. }
  63706. this.afterUpdateParticles(start, end, update);
  63707. return this;
  63708. };
  63709. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  63710. this._halfroll = this._roll * 0.5;
  63711. this._halfpitch = this._pitch * 0.5;
  63712. this._halfyaw = this._yaw * 0.5;
  63713. this._sinRoll = Math.sin(this._halfroll);
  63714. this._cosRoll = Math.cos(this._halfroll);
  63715. this._sinPitch = Math.sin(this._halfpitch);
  63716. this._cosPitch = Math.cos(this._halfpitch);
  63717. this._sinYaw = Math.sin(this._halfyaw);
  63718. this._cosYaw = Math.cos(this._halfyaw);
  63719. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  63720. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  63721. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  63722. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  63723. };
  63724. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  63725. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  63726. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  63727. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  63728. this._rotMatrix.m[3] = 0;
  63729. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  63730. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  63731. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  63732. this._rotMatrix.m[7] = 0;
  63733. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  63734. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  63735. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  63736. this._rotMatrix.m[11] = 0;
  63737. this._rotMatrix.m[12] = 0;
  63738. this._rotMatrix.m[13] = 0;
  63739. this._rotMatrix.m[14] = 0;
  63740. this._rotMatrix.m[15] = 1.0;
  63741. };
  63742. /**
  63743. * Disposes the SPS.
  63744. */
  63745. SolidParticleSystem.prototype.dispose = function () {
  63746. this.mesh.dispose();
  63747. this.vars = null;
  63748. // drop references to internal big arrays for the GC
  63749. this._positions = null;
  63750. this._indices = null;
  63751. this._normals = null;
  63752. this._uvs = null;
  63753. this._colors = null;
  63754. this._indices32 = null;
  63755. this._positions32 = null;
  63756. this._normals32 = null;
  63757. this._fixedNormal32 = null;
  63758. this._uvs32 = null;
  63759. this._colors32 = null;
  63760. this.pickedParticles = null;
  63761. };
  63762. /**
  63763. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  63764. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63765. * @returns the SPS.
  63766. */
  63767. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  63768. if (!this._isVisibilityBoxLocked) {
  63769. this.mesh.refreshBoundingInfo();
  63770. }
  63771. return this;
  63772. };
  63773. /**
  63774. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  63775. * @param size the size (float) of the visibility box
  63776. * note : this doesn't lock the SPS mesh bounding box.
  63777. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63778. */
  63779. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  63780. var vis = size / 2;
  63781. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  63782. };
  63783. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  63784. /**
  63785. * Gets whether the SPS as always visible or not
  63786. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63787. */
  63788. get: function () {
  63789. return this._alwaysVisible;
  63790. },
  63791. /**
  63792. * Sets the SPS as always visible or not
  63793. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63794. */
  63795. set: function (val) {
  63796. this._alwaysVisible = val;
  63797. this.mesh.alwaysSelectAsActiveMesh = val;
  63798. },
  63799. enumerable: true,
  63800. configurable: true
  63801. });
  63802. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  63803. /**
  63804. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63805. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63806. */
  63807. get: function () {
  63808. return this._isVisibilityBoxLocked;
  63809. },
  63810. /**
  63811. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63812. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63813. */
  63814. set: function (val) {
  63815. this._isVisibilityBoxLocked = val;
  63816. var boundingInfo = this.mesh.getBoundingInfo();
  63817. boundingInfo.isLocked = val;
  63818. },
  63819. enumerable: true,
  63820. configurable: true
  63821. });
  63822. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  63823. /**
  63824. * Gets if `setParticles()` computes the particle rotations or not.
  63825. * Default value : true. The SPS is faster when it's set to false.
  63826. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63827. */
  63828. get: function () {
  63829. return this._computeParticleRotation;
  63830. },
  63831. /**
  63832. * Tells to `setParticles()` to compute the particle rotations or not.
  63833. * Default value : true. The SPS is faster when it's set to false.
  63834. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63835. */
  63836. set: function (val) {
  63837. this._computeParticleRotation = val;
  63838. },
  63839. enumerable: true,
  63840. configurable: true
  63841. });
  63842. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  63843. /**
  63844. * Gets if `setParticles()` computes the particle colors or not.
  63845. * Default value : true. The SPS is faster when it's set to false.
  63846. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63847. */
  63848. get: function () {
  63849. return this._computeParticleColor;
  63850. },
  63851. /**
  63852. * Tells to `setParticles()` to compute the particle colors or not.
  63853. * Default value : true. The SPS is faster when it's set to false.
  63854. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63855. */
  63856. set: function (val) {
  63857. this._computeParticleColor = val;
  63858. },
  63859. enumerable: true,
  63860. configurable: true
  63861. });
  63862. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  63863. /**
  63864. * Gets if `setParticles()` computes the particle textures or not.
  63865. * Default value : true. The SPS is faster when it's set to false.
  63866. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  63867. */
  63868. get: function () {
  63869. return this._computeParticleTexture;
  63870. },
  63871. set: function (val) {
  63872. this._computeParticleTexture = val;
  63873. },
  63874. enumerable: true,
  63875. configurable: true
  63876. });
  63877. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  63878. /**
  63879. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  63880. * Default value : false. The SPS is faster when it's set to false.
  63881. * Note : the particle custom vertex positions aren't stored values.
  63882. */
  63883. get: function () {
  63884. return this._computeParticleVertex;
  63885. },
  63886. /**
  63887. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  63888. * Default value : false. The SPS is faster when it's set to false.
  63889. * Note : the particle custom vertex positions aren't stored values.
  63890. */
  63891. set: function (val) {
  63892. this._computeParticleVertex = val;
  63893. },
  63894. enumerable: true,
  63895. configurable: true
  63896. });
  63897. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  63898. /**
  63899. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  63900. */
  63901. get: function () {
  63902. return this._computeBoundingBox;
  63903. },
  63904. /**
  63905. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  63906. */
  63907. set: function (val) {
  63908. this._computeBoundingBox = val;
  63909. },
  63910. enumerable: true,
  63911. configurable: true
  63912. });
  63913. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  63914. /**
  63915. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  63916. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  63917. * Default : `true`
  63918. */
  63919. get: function () {
  63920. return this._depthSortParticles;
  63921. },
  63922. /**
  63923. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  63924. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  63925. * Default : `true`
  63926. */
  63927. set: function (val) {
  63928. this._depthSortParticles = val;
  63929. },
  63930. enumerable: true,
  63931. configurable: true
  63932. });
  63933. // =======================================================================
  63934. // Particle behavior logic
  63935. // these following methods may be overwritten by the user to fit his needs
  63936. /**
  63937. * This function does nothing. It may be overwritten to set all the particle first values.
  63938. * The SPS doesn't call this function, you may have to call it by your own.
  63939. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63940. */
  63941. SolidParticleSystem.prototype.initParticles = function () {
  63942. };
  63943. /**
  63944. * This function does nothing. It may be overwritten to recycle a particle.
  63945. * The SPS doesn't call this function, you may have to call it by your own.
  63946. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63947. * @param particle The particle to recycle
  63948. * @returns the recycled particle
  63949. */
  63950. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  63951. return particle;
  63952. };
  63953. /**
  63954. * Updates a particle : this function should be overwritten by the user.
  63955. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  63956. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63957. * @example : just set a particle position or velocity and recycle conditions
  63958. * @param particle The particle to update
  63959. * @returns the updated particle
  63960. */
  63961. SolidParticleSystem.prototype.updateParticle = function (particle) {
  63962. return particle;
  63963. };
  63964. /**
  63965. * Updates a vertex of a particle : it can be overwritten by the user.
  63966. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  63967. * @param particle the current particle
  63968. * @param vertex the current index of the current particle
  63969. * @param pt the index of the current vertex in the particle shape
  63970. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  63971. * @example : just set a vertex particle position
  63972. * @returns the updated vertex
  63973. */
  63974. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  63975. return vertex;
  63976. };
  63977. /**
  63978. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  63979. * This does nothing and may be overwritten by the user.
  63980. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63981. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63982. * @param update the boolean update value actually passed to setParticles()
  63983. */
  63984. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  63985. };
  63986. /**
  63987. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  63988. * This will be passed three parameters.
  63989. * This does nothing and may be overwritten by the user.
  63990. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63991. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63992. * @param update the boolean update value actually passed to setParticles()
  63993. */
  63994. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  63995. };
  63996. return SolidParticleSystem;
  63997. }());
  63998. BABYLON.SolidParticleSystem = SolidParticleSystem;
  63999. })(BABYLON || (BABYLON = {}));
  64000. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  64001. var BABYLON;
  64002. (function (BABYLON) {
  64003. /**
  64004. * Class containing static functions to help procedurally build meshes
  64005. */
  64006. var MeshBuilder = /** @class */ (function () {
  64007. function MeshBuilder() {
  64008. }
  64009. MeshBuilder.updateSideOrientation = function (orientation) {
  64010. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  64011. return BABYLON.Mesh.DOUBLESIDE;
  64012. }
  64013. if (orientation === undefined || orientation === null) {
  64014. return BABYLON.Mesh.FRONTSIDE;
  64015. }
  64016. return orientation;
  64017. };
  64018. /**
  64019. * Creates a box mesh
  64020. * * The parameter `size` sets the size (float) of each box side (default 1)
  64021. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  64022. * * 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)
  64023. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  64024. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64025. * * 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
  64026. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64027. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  64028. * @param name defines the name of the mesh
  64029. * @param options defines the options used to create the mesh
  64030. * @param scene defines the hosting scene
  64031. * @returns the box mesh
  64032. */
  64033. MeshBuilder.CreateBox = function (name, options, scene) {
  64034. if (scene === void 0) { scene = null; }
  64035. var box = new BABYLON.Mesh(name, scene);
  64036. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64037. box._originalBuilderSideOrientation = options.sideOrientation;
  64038. var vertexData = BABYLON.VertexData.CreateBox(options);
  64039. vertexData.applyToMesh(box, options.updatable);
  64040. return box;
  64041. };
  64042. /**
  64043. * Creates a sphere mesh
  64044. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  64045. * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`)
  64046. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  64047. * * 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
  64048. * * 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)
  64049. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64050. * * 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
  64051. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64052. * @param name defines the name of the mesh
  64053. * @param options defines the options used to create the mesh
  64054. * @param scene defines the hosting scene
  64055. * @returns the sphere mesh
  64056. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  64057. */
  64058. MeshBuilder.CreateSphere = function (name, options, scene) {
  64059. var sphere = new BABYLON.Mesh(name, scene);
  64060. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64061. sphere._originalBuilderSideOrientation = options.sideOrientation;
  64062. var vertexData = BABYLON.VertexData.CreateSphere(options);
  64063. vertexData.applyToMesh(sphere, options.updatable);
  64064. return sphere;
  64065. };
  64066. /**
  64067. * Creates a plane polygonal mesh. By default, this is a disc
  64068. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  64069. * * 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
  64070. * * 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
  64071. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64072. * * 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
  64073. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64074. * @param name defines the name of the mesh
  64075. * @param options defines the options used to create the mesh
  64076. * @param scene defines the hosting scene
  64077. * @returns the plane polygonal mesh
  64078. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  64079. */
  64080. MeshBuilder.CreateDisc = function (name, options, scene) {
  64081. if (scene === void 0) { scene = null; }
  64082. var disc = new BABYLON.Mesh(name, scene);
  64083. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64084. disc._originalBuilderSideOrientation = options.sideOrientation;
  64085. var vertexData = BABYLON.VertexData.CreateDisc(options);
  64086. vertexData.applyToMesh(disc, options.updatable);
  64087. return disc;
  64088. };
  64089. /**
  64090. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  64091. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  64092. * * 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`)
  64093. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  64094. * * 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
  64095. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64096. * * 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
  64097. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64098. * @param name defines the name of the mesh
  64099. * @param options defines the options used to create the mesh
  64100. * @param scene defines the hosting scene
  64101. * @returns the icosahedron mesh
  64102. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  64103. */
  64104. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  64105. var sphere = new BABYLON.Mesh(name, scene);
  64106. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64107. sphere._originalBuilderSideOrientation = options.sideOrientation;
  64108. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  64109. vertexData.applyToMesh(sphere, options.updatable);
  64110. return sphere;
  64111. };
  64112. ;
  64113. /**
  64114. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  64115. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  64116. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  64117. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  64118. * * 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
  64119. * * 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
  64120. * * 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
  64121. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64122. * * 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
  64123. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64124. * * 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
  64125. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  64126. * * 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
  64127. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  64128. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64129. * @param name defines the name of the mesh
  64130. * @param options defines the options used to create the mesh
  64131. * @param scene defines the hosting scene
  64132. * @returns the ribbon mesh
  64133. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  64134. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64135. */
  64136. MeshBuilder.CreateRibbon = function (name, options, scene) {
  64137. if (scene === void 0) { scene = null; }
  64138. var pathArray = options.pathArray;
  64139. var closeArray = options.closeArray;
  64140. var closePath = options.closePath;
  64141. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64142. var instance = options.instance;
  64143. var updatable = options.updatable;
  64144. if (instance) { // existing ribbon instance update
  64145. // positionFunction : ribbon case
  64146. // only pathArray and sideOrientation parameters are taken into account for positions update
  64147. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  64148. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  64149. var positionFunction = function (positions) {
  64150. var minlg = pathArray[0].length;
  64151. var i = 0;
  64152. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  64153. for (var si = 1; si <= ns; si++) {
  64154. for (var p = 0; p < pathArray.length; p++) {
  64155. var path = pathArray[p];
  64156. var l = path.length;
  64157. minlg = (minlg < l) ? minlg : l;
  64158. var j = 0;
  64159. while (j < minlg) {
  64160. positions[i] = path[j].x;
  64161. positions[i + 1] = path[j].y;
  64162. positions[i + 2] = path[j].z;
  64163. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  64164. BABYLON.Tmp.Vector3[0].x = path[j].x;
  64165. }
  64166. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  64167. BABYLON.Tmp.Vector3[1].x = path[j].x;
  64168. }
  64169. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  64170. BABYLON.Tmp.Vector3[0].y = path[j].y;
  64171. }
  64172. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  64173. BABYLON.Tmp.Vector3[1].y = path[j].y;
  64174. }
  64175. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  64176. BABYLON.Tmp.Vector3[0].z = path[j].z;
  64177. }
  64178. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  64179. BABYLON.Tmp.Vector3[1].z = path[j].z;
  64180. }
  64181. j++;
  64182. i += 3;
  64183. }
  64184. if (instance._closePath) {
  64185. positions[i] = path[0].x;
  64186. positions[i + 1] = path[0].y;
  64187. positions[i + 2] = path[0].z;
  64188. i += 3;
  64189. }
  64190. }
  64191. }
  64192. };
  64193. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64194. positionFunction(positions);
  64195. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  64196. instance._boundingInfo.update(instance._worldMatrix);
  64197. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  64198. if (options.colors) {
  64199. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64200. for (var c = 0; c < options.colors.length; c++) {
  64201. colors[c * 4] = options.colors[c].r;
  64202. colors[c * 4 + 1] = options.colors[c].g;
  64203. colors[c * 4 + 2] = options.colors[c].b;
  64204. colors[c * 4 + 3] = options.colors[c].a;
  64205. }
  64206. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  64207. }
  64208. if (options.uvs) {
  64209. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64210. for (var i = 0; i < options.uvs.length; i++) {
  64211. uvs[i * 2] = options.uvs[i].x;
  64212. uvs[i * 2 + 1] = options.uvs[i].y;
  64213. }
  64214. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  64215. }
  64216. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  64217. var indices = instance.getIndices();
  64218. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64219. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  64220. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  64221. if (instance._closePath) {
  64222. var indexFirst = 0;
  64223. var indexLast = 0;
  64224. for (var p = 0; p < pathArray.length; p++) {
  64225. indexFirst = instance._idx[p] * 3;
  64226. if (p + 1 < pathArray.length) {
  64227. indexLast = (instance._idx[p + 1] - 1) * 3;
  64228. }
  64229. else {
  64230. indexLast = normals.length - 3;
  64231. }
  64232. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  64233. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  64234. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  64235. normals[indexLast] = normals[indexFirst];
  64236. normals[indexLast + 1] = normals[indexFirst + 1];
  64237. normals[indexLast + 2] = normals[indexFirst + 2];
  64238. }
  64239. }
  64240. if (!(instance.areNormalsFrozen)) {
  64241. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  64242. }
  64243. }
  64244. return instance;
  64245. }
  64246. else { // new ribbon creation
  64247. var ribbon = new BABYLON.Mesh(name, scene);
  64248. ribbon._originalBuilderSideOrientation = sideOrientation;
  64249. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  64250. if (closePath) {
  64251. ribbon._idx = vertexData._idx;
  64252. }
  64253. ribbon._closePath = closePath;
  64254. ribbon._closeArray = closeArray;
  64255. vertexData.applyToMesh(ribbon, updatable);
  64256. return ribbon;
  64257. }
  64258. };
  64259. /**
  64260. * Creates a cylinder or a cone mesh
  64261. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  64262. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  64263. * * 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.
  64264. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  64265. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  64266. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  64267. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  64268. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  64269. * * 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).
  64270. * * 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
  64271. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  64272. * * 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
  64273. * * 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.
  64274. * * If `enclose` is false, a ring surface is one element.
  64275. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  64276. * * 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
  64277. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64278. * * 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
  64279. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64280. * @param name defines the name of the mesh
  64281. * @param options defines the options used to create the mesh
  64282. * @param scene defines the hosting scene
  64283. * @returns the cylinder mesh
  64284. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  64285. */
  64286. MeshBuilder.CreateCylinder = function (name, options, scene) {
  64287. var cylinder = new BABYLON.Mesh(name, scene);
  64288. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64289. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  64290. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  64291. vertexData.applyToMesh(cylinder, options.updatable);
  64292. return cylinder;
  64293. };
  64294. /**
  64295. * Creates a torus mesh
  64296. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  64297. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  64298. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  64299. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64300. * * 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
  64301. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64302. * @param name defines the name of the mesh
  64303. * @param options defines the options used to create the mesh
  64304. * @param scene defines the hosting scene
  64305. * @returns the torus mesh
  64306. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  64307. */
  64308. MeshBuilder.CreateTorus = function (name, options, scene) {
  64309. var torus = new BABYLON.Mesh(name, scene);
  64310. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64311. torus._originalBuilderSideOrientation = options.sideOrientation;
  64312. var vertexData = BABYLON.VertexData.CreateTorus(options);
  64313. vertexData.applyToMesh(torus, options.updatable);
  64314. return torus;
  64315. };
  64316. /**
  64317. * Creates a torus knot mesh
  64318. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  64319. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  64320. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  64321. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  64322. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64323. * * 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
  64324. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64325. * @param name defines the name of the mesh
  64326. * @param options defines the options used to create the mesh
  64327. * @param scene defines the hosting scene
  64328. * @returns the torus knot mesh
  64329. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  64330. */
  64331. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  64332. var torusKnot = new BABYLON.Mesh(name, scene);
  64333. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64334. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  64335. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  64336. vertexData.applyToMesh(torusKnot, options.updatable);
  64337. return torusKnot;
  64338. };
  64339. /**
  64340. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  64341. * * 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
  64342. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  64343. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  64344. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  64345. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  64346. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  64347. * * 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
  64348. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  64349. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64350. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  64351. * @param name defines the name of the new line system
  64352. * @param options defines the options used to create the line system
  64353. * @param scene defines the hosting scene
  64354. * @returns a new line system mesh
  64355. */
  64356. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  64357. var instance = options.instance;
  64358. var lines = options.lines;
  64359. var colors = options.colors;
  64360. if (instance) { // lines update
  64361. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64362. var vertexColor;
  64363. var lineColors;
  64364. if (colors) {
  64365. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64366. }
  64367. var i = 0;
  64368. var c = 0;
  64369. for (var l = 0; l < lines.length; l++) {
  64370. var points = lines[l];
  64371. for (var p = 0; p < points.length; p++) {
  64372. positions[i] = points[p].x;
  64373. positions[i + 1] = points[p].y;
  64374. positions[i + 2] = points[p].z;
  64375. if (colors && vertexColor) {
  64376. lineColors = colors[l];
  64377. vertexColor[c] = lineColors[p].r;
  64378. vertexColor[c + 1] = lineColors[p].g;
  64379. vertexColor[c + 2] = lineColors[p].b;
  64380. vertexColor[c + 3] = lineColors[p].a;
  64381. c += 4;
  64382. }
  64383. i += 3;
  64384. }
  64385. }
  64386. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  64387. if (colors && vertexColor) {
  64388. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  64389. }
  64390. return instance;
  64391. }
  64392. // line system creation
  64393. var useVertexColor = (colors) ? true : false;
  64394. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  64395. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  64396. vertexData.applyToMesh(lineSystem, options.updatable);
  64397. return lineSystem;
  64398. };
  64399. /**
  64400. * Creates a line mesh
  64401. * 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
  64402. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  64403. * * The parameter `points` is an array successive Vector3
  64404. * * 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
  64405. * * The optional parameter `colors` is an array of successive Color4, one per line point
  64406. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  64407. * * When updating an instance, remember that only point positions can change, not the number of points
  64408. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64409. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  64410. * @param name defines the name of the new line system
  64411. * @param options defines the options used to create the line system
  64412. * @param scene defines the hosting scene
  64413. * @returns a new line mesh
  64414. */
  64415. MeshBuilder.CreateLines = function (name, options, scene) {
  64416. if (scene === void 0) { scene = null; }
  64417. var colors = (options.colors) ? [options.colors] : null;
  64418. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  64419. return lines;
  64420. };
  64421. /**
  64422. * Creates a dashed line mesh
  64423. * * 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
  64424. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  64425. * * The parameter `points` is an array successive Vector3
  64426. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  64427. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  64428. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  64429. * * 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
  64430. * * When updating an instance, remember that only point positions can change, not the number of points
  64431. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64432. * @param name defines the name of the mesh
  64433. * @param options defines the options used to create the mesh
  64434. * @param scene defines the hosting scene
  64435. * @returns the dashed line mesh
  64436. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  64437. */
  64438. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  64439. if (scene === void 0) { scene = null; }
  64440. var points = options.points;
  64441. var instance = options.instance;
  64442. var gapSize = options.gapSize || 1;
  64443. var dashSize = options.dashSize || 3;
  64444. if (instance) { // dashed lines update
  64445. var positionFunction = function (positions) {
  64446. var curvect = BABYLON.Vector3.Zero();
  64447. var nbSeg = positions.length / 6;
  64448. var lg = 0;
  64449. var nb = 0;
  64450. var shft = 0;
  64451. var dashshft = 0;
  64452. var curshft = 0;
  64453. var p = 0;
  64454. var i = 0;
  64455. var j = 0;
  64456. for (i = 0; i < points.length - 1; i++) {
  64457. points[i + 1].subtractToRef(points[i], curvect);
  64458. lg += curvect.length();
  64459. }
  64460. shft = lg / nbSeg;
  64461. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  64462. for (i = 0; i < points.length - 1; i++) {
  64463. points[i + 1].subtractToRef(points[i], curvect);
  64464. nb = Math.floor(curvect.length() / shft);
  64465. curvect.normalize();
  64466. j = 0;
  64467. while (j < nb && p < positions.length) {
  64468. curshft = shft * j;
  64469. positions[p] = points[i].x + curshft * curvect.x;
  64470. positions[p + 1] = points[i].y + curshft * curvect.y;
  64471. positions[p + 2] = points[i].z + curshft * curvect.z;
  64472. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  64473. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  64474. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  64475. p += 6;
  64476. j++;
  64477. }
  64478. }
  64479. while (p < positions.length) {
  64480. positions[p] = points[i].x;
  64481. positions[p + 1] = points[i].y;
  64482. positions[p + 2] = points[i].z;
  64483. p += 3;
  64484. }
  64485. };
  64486. instance.updateMeshPositions(positionFunction, false);
  64487. return instance;
  64488. }
  64489. // dashed lines creation
  64490. var dashedLines = new BABYLON.LinesMesh(name, scene);
  64491. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  64492. vertexData.applyToMesh(dashedLines, options.updatable);
  64493. dashedLines.dashSize = dashSize;
  64494. dashedLines.gapSize = gapSize;
  64495. return dashedLines;
  64496. };
  64497. /**
  64498. * 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.
  64499. * * 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.
  64500. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  64501. * * 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.
  64502. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  64503. * * 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
  64504. * * 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
  64505. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  64506. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64507. * * 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
  64508. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  64509. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64510. * @param name defines the name of the mesh
  64511. * @param options defines the options used to create the mesh
  64512. * @param scene defines the hosting scene
  64513. * @returns the extruded shape mesh
  64514. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64515. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64516. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64517. */
  64518. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  64519. if (scene === void 0) { scene = null; }
  64520. var path = options.path;
  64521. var shape = options.shape;
  64522. var scale = options.scale || 1;
  64523. var rotation = options.rotation || 0;
  64524. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  64525. var updatable = options.updatable;
  64526. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64527. var instance = options.instance || null;
  64528. var invertUV = options.invertUV || false;
  64529. 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);
  64530. };
  64531. /**
  64532. * Creates an custom extruded shape mesh.
  64533. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  64534. * * 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.
  64535. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  64536. * * 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
  64537. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  64538. * * 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
  64539. * * It must returns a float value that will be the scale value applied to the shape on each path point
  64540. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  64541. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  64542. * * 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
  64543. * * 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
  64544. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  64545. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64546. * * 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
  64547. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64548. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64549. * @param name defines the name of the mesh
  64550. * @param options defines the options used to create the mesh
  64551. * @param scene defines the hosting scene
  64552. * @returns the custom extruded shape mesh
  64553. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  64554. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64555. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64556. */
  64557. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  64558. var path = options.path;
  64559. var shape = options.shape;
  64560. var scaleFunction = options.scaleFunction || (function () { return 1; });
  64561. var rotationFunction = options.rotationFunction || (function () { return 0; });
  64562. var ribbonCloseArray = options.ribbonCloseArray || false;
  64563. var ribbonClosePath = options.ribbonClosePath || false;
  64564. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  64565. var updatable = options.updatable;
  64566. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64567. var instance = options.instance;
  64568. var invertUV = options.invertUV || false;
  64569. 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);
  64570. };
  64571. /**
  64572. * Creates lathe mesh.
  64573. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  64574. * * 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
  64575. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  64576. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  64577. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  64578. * * 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
  64579. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  64580. * * 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
  64581. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64582. * * 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
  64583. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64584. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64585. * @param name defines the name of the mesh
  64586. * @param options defines the options used to create the mesh
  64587. * @param scene defines the hosting scene
  64588. * @returns the lathe mesh
  64589. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  64590. */
  64591. MeshBuilder.CreateLathe = function (name, options, scene) {
  64592. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  64593. var closed = (options.closed === undefined) ? true : options.closed;
  64594. var shape = options.shape;
  64595. var radius = options.radius || 1;
  64596. var tessellation = options.tessellation || 64;
  64597. var clip = options.clip || 0;
  64598. var updatable = options.updatable;
  64599. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64600. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64601. var pi2 = Math.PI * 2;
  64602. var paths = new Array();
  64603. var invertUV = options.invertUV || false;
  64604. var i = 0;
  64605. var p = 0;
  64606. var step = pi2 / tessellation * arc;
  64607. var rotated;
  64608. var path = new Array();
  64609. for (i = 0; i <= tessellation - clip; i++) {
  64610. var path = [];
  64611. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  64612. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  64613. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  64614. }
  64615. for (p = 0; p < shape.length; p++) {
  64616. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  64617. path.push(rotated);
  64618. }
  64619. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  64620. 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));
  64621. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  64622. }
  64623. paths.push(path);
  64624. }
  64625. // lathe ribbon
  64626. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  64627. return lathe;
  64628. };
  64629. /**
  64630. * Creates a plane mesh
  64631. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  64632. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  64633. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  64634. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64635. * * 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
  64636. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64637. * @param name defines the name of the mesh
  64638. * @param options defines the options used to create the mesh
  64639. * @param scene defines the hosting scene
  64640. * @returns the plane mesh
  64641. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64642. */
  64643. MeshBuilder.CreatePlane = function (name, options, scene) {
  64644. var plane = new BABYLON.Mesh(name, scene);
  64645. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64646. plane._originalBuilderSideOrientation = options.sideOrientation;
  64647. var vertexData = BABYLON.VertexData.CreatePlane(options);
  64648. vertexData.applyToMesh(plane, options.updatable);
  64649. if (options.sourcePlane) {
  64650. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  64651. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  64652. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  64653. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  64654. plane.rotate(vectorProduct, product);
  64655. }
  64656. }
  64657. return plane;
  64658. };
  64659. /**
  64660. * Creates a ground mesh
  64661. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  64662. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  64663. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64664. * @param name defines the name of the mesh
  64665. * @param options defines the options used to create the mesh
  64666. * @param scene defines the hosting scene
  64667. * @returns the ground mesh
  64668. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64669. */
  64670. MeshBuilder.CreateGround = function (name, options, scene) {
  64671. var ground = new BABYLON.GroundMesh(name, scene);
  64672. ground._setReady(false);
  64673. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  64674. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  64675. ground._width = options.width || 1;
  64676. ground._height = options.height || 1;
  64677. ground._maxX = ground._width / 2;
  64678. ground._maxZ = ground._height / 2;
  64679. ground._minX = -ground._maxX;
  64680. ground._minZ = -ground._maxZ;
  64681. var vertexData = BABYLON.VertexData.CreateGround(options);
  64682. vertexData.applyToMesh(ground, options.updatable);
  64683. ground._setReady(true);
  64684. return ground;
  64685. };
  64686. /**
  64687. * Creates a tiled ground mesh
  64688. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  64689. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  64690. * * 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
  64691. * * 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
  64692. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64693. * @param name defines the name of the mesh
  64694. * @param options defines the options used to create the mesh
  64695. * @param scene defines the hosting scene
  64696. * @returns the tiled ground mesh
  64697. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  64698. */
  64699. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  64700. var tiledGround = new BABYLON.Mesh(name, scene);
  64701. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  64702. vertexData.applyToMesh(tiledGround, options.updatable);
  64703. return tiledGround;
  64704. };
  64705. /**
  64706. * Creates a ground mesh from a height map
  64707. * * The parameter `url` sets the URL of the height map image resource.
  64708. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  64709. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  64710. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  64711. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  64712. * * 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.
  64713. * * 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).
  64714. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  64715. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64716. * @param name defines the name of the mesh
  64717. * @param url defines the url to the height map
  64718. * @param options defines the options used to create the mesh
  64719. * @param scene defines the hosting scene
  64720. * @returns the ground mesh
  64721. * @see http://doc.babylonjs.com/babylon101/height_map
  64722. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  64723. */
  64724. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  64725. var width = options.width || 10.0;
  64726. var height = options.height || 10.0;
  64727. var subdivisions = options.subdivisions || 1 | 0;
  64728. var minHeight = options.minHeight || 0.0;
  64729. var maxHeight = options.maxHeight || 1.0;
  64730. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  64731. var alphaFilter = options.alphaFilter || 0.0;
  64732. var updatable = options.updatable;
  64733. var onReady = options.onReady;
  64734. var ground = new BABYLON.GroundMesh(name, scene);
  64735. ground._subdivisionsX = subdivisions;
  64736. ground._subdivisionsY = subdivisions;
  64737. ground._width = width;
  64738. ground._height = height;
  64739. ground._maxX = ground._width / 2.0;
  64740. ground._maxZ = ground._height / 2.0;
  64741. ground._minX = -ground._maxX;
  64742. ground._minZ = -ground._maxZ;
  64743. ground._setReady(false);
  64744. var onload = function (img) {
  64745. // Getting height map data
  64746. var canvas = document.createElement("canvas");
  64747. var context = canvas.getContext("2d");
  64748. if (!context) {
  64749. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  64750. }
  64751. if (scene.isDisposed) {
  64752. return;
  64753. }
  64754. var bufferWidth = img.width;
  64755. var bufferHeight = img.height;
  64756. canvas.width = bufferWidth;
  64757. canvas.height = bufferHeight;
  64758. context.drawImage(img, 0, 0);
  64759. // Create VertexData from map data
  64760. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  64761. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  64762. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  64763. width: width, height: height,
  64764. subdivisions: subdivisions,
  64765. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  64766. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  64767. alphaFilter: alphaFilter
  64768. });
  64769. vertexData.applyToMesh(ground, updatable);
  64770. //execute ready callback, if set
  64771. if (onReady) {
  64772. onReady(ground);
  64773. }
  64774. ground._setReady(true);
  64775. };
  64776. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  64777. return ground;
  64778. };
  64779. /**
  64780. * Creates a polygon mesh
  64781. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  64782. * * 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
  64783. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64784. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64785. * * 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)
  64786. * * Remember you can only change the shape positions, not their number when updating a polygon
  64787. * @param name defines the name of the mesh
  64788. * @param options defines the options used to create the mesh
  64789. * @param scene defines the hosting scene
  64790. * @returns the polygon mesh
  64791. */
  64792. MeshBuilder.CreatePolygon = function (name, options, scene) {
  64793. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64794. var shape = options.shape;
  64795. var holes = options.holes || [];
  64796. var depth = options.depth || 0;
  64797. var contours = [];
  64798. var hole = [];
  64799. for (var i = 0; i < shape.length; i++) {
  64800. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  64801. }
  64802. var epsilon = 0.00000001;
  64803. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  64804. contours.pop();
  64805. }
  64806. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  64807. for (var hNb = 0; hNb < holes.length; hNb++) {
  64808. hole = [];
  64809. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  64810. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  64811. }
  64812. polygonTriangulation.addHole(hole);
  64813. }
  64814. var polygon = polygonTriangulation.build(options.updatable, depth);
  64815. polygon._originalBuilderSideOrientation = options.sideOrientation;
  64816. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  64817. vertexData.applyToMesh(polygon, options.updatable);
  64818. return polygon;
  64819. };
  64820. ;
  64821. /**
  64822. * Creates an extruded polygon mesh, with depth in the Y direction.
  64823. * * 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)
  64824. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  64825. * @param name defines the name of the mesh
  64826. * @param options defines the options used to create the mesh
  64827. * @param scene defines the hosting scene
  64828. * @returns the polygon mesh
  64829. */
  64830. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  64831. return MeshBuilder.CreatePolygon(name, options, scene);
  64832. };
  64833. ;
  64834. /**
  64835. * Creates a tube mesh.
  64836. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  64837. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  64838. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  64839. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  64840. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  64841. * * 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)
  64842. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  64843. * * 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
  64844. * * 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
  64845. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64846. * * 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
  64847. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64848. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64849. * @param name defines the name of the mesh
  64850. * @param options defines the options used to create the mesh
  64851. * @param scene defines the hosting scene
  64852. * @returns the tube mesh
  64853. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64854. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  64855. */
  64856. MeshBuilder.CreateTube = function (name, options, scene) {
  64857. var path = options.path;
  64858. var instance = options.instance;
  64859. var radius = 1.0;
  64860. if (instance) {
  64861. radius = instance.radius;
  64862. }
  64863. if (options.radius !== undefined) {
  64864. radius = options.radius;
  64865. }
  64866. ;
  64867. var tessellation = options.tessellation || 64 | 0;
  64868. var radiusFunction = options.radiusFunction || null;
  64869. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64870. var invertUV = options.invertUV || false;
  64871. var updatable = options.updatable;
  64872. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64873. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  64874. // tube geometry
  64875. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  64876. var tangents = path3D.getTangents();
  64877. var normals = path3D.getNormals();
  64878. var distances = path3D.getDistances();
  64879. var pi2 = Math.PI * 2;
  64880. var step = pi2 / tessellation * arc;
  64881. var returnRadius = function () { return radius; };
  64882. var radiusFunctionFinal = radiusFunction || returnRadius;
  64883. var circlePath;
  64884. var rad;
  64885. var normal;
  64886. var rotated;
  64887. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  64888. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  64889. for (var i = 0; i < path.length; i++) {
  64890. rad = radiusFunctionFinal(i, distances[i]); // current radius
  64891. circlePath = Array(); // current circle array
  64892. normal = normals[i]; // current normal
  64893. for (var t = 0; t < tessellation; t++) {
  64894. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  64895. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  64896. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  64897. rotated.scaleInPlace(rad).addInPlace(path[i]);
  64898. circlePath[t] = rotated;
  64899. }
  64900. circlePaths[index] = circlePath;
  64901. index++;
  64902. }
  64903. // cap
  64904. var capPath = function (nbPoints, pathIndex) {
  64905. var pointCap = Array();
  64906. for (var i = 0; i < nbPoints; i++) {
  64907. pointCap.push(path[pathIndex]);
  64908. }
  64909. return pointCap;
  64910. };
  64911. switch (cap) {
  64912. case BABYLON.Mesh.NO_CAP:
  64913. break;
  64914. case BABYLON.Mesh.CAP_START:
  64915. circlePaths[0] = capPath(tessellation, 0);
  64916. circlePaths[1] = circlePaths[2].slice(0);
  64917. break;
  64918. case BABYLON.Mesh.CAP_END:
  64919. circlePaths[index] = circlePaths[index - 1].slice(0);
  64920. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  64921. break;
  64922. case BABYLON.Mesh.CAP_ALL:
  64923. circlePaths[0] = capPath(tessellation, 0);
  64924. circlePaths[1] = circlePaths[2].slice(0);
  64925. circlePaths[index] = circlePaths[index - 1].slice(0);
  64926. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  64927. break;
  64928. default:
  64929. break;
  64930. }
  64931. return circlePaths;
  64932. };
  64933. var path3D;
  64934. var pathArray;
  64935. if (instance) { // tube update
  64936. var arc = options.arc || instance.arc;
  64937. path3D = (instance.path3D).update(path);
  64938. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  64939. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  64940. instance.path3D = path3D;
  64941. instance.pathArray = pathArray;
  64942. instance.arc = arc;
  64943. instance.radius = radius;
  64944. return instance;
  64945. }
  64946. // tube creation
  64947. path3D = new BABYLON.Path3D(path);
  64948. var newPathArray = new Array();
  64949. cap = (cap < 0 || cap > 3) ? 0 : cap;
  64950. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  64951. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  64952. tube.pathArray = pathArray;
  64953. tube.path3D = path3D;
  64954. tube.tessellation = tessellation;
  64955. tube.cap = cap;
  64956. tube.arc = options.arc;
  64957. tube.radius = radius;
  64958. return tube;
  64959. };
  64960. /**
  64961. * Creates a polyhedron mesh
  64962. * * 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
  64963. * * The parameter `size` (positive float, default 1) sets the polygon size
  64964. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  64965. * * 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`
  64966. * * 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
  64967. * * 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)`)
  64968. * * 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
  64969. * * 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
  64970. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64971. * * 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
  64972. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64973. * @param name defines the name of the mesh
  64974. * @param options defines the options used to create the mesh
  64975. * @param scene defines the hosting scene
  64976. * @returns the polyhedron mesh
  64977. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  64978. */
  64979. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  64980. var polyhedron = new BABYLON.Mesh(name, scene);
  64981. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64982. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  64983. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  64984. vertexData.applyToMesh(polyhedron, options.updatable);
  64985. return polyhedron;
  64986. };
  64987. /**
  64988. * Creates a decal mesh.
  64989. * 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
  64990. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  64991. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  64992. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  64993. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  64994. * @param name defines the name of the mesh
  64995. * @param sourceMesh defines the mesh where the decal must be applied
  64996. * @param options defines the options used to create the mesh
  64997. * @param scene defines the hosting scene
  64998. * @returns the decal mesh
  64999. * @see http://doc.babylonjs.com/how_to/decals
  65000. */
  65001. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  65002. var indices = sourceMesh.getIndices();
  65003. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65004. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65005. var position = options.position || BABYLON.Vector3.Zero();
  65006. var normal = options.normal || BABYLON.Vector3.Up();
  65007. var size = options.size || BABYLON.Vector3.One();
  65008. var angle = options.angle || 0;
  65009. // Getting correct rotation
  65010. if (!normal) {
  65011. var target = new BABYLON.Vector3(0, 0, 1);
  65012. var camera = sourceMesh.getScene().activeCamera;
  65013. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  65014. normal = camera.globalPosition.subtract(cameraWorldTarget);
  65015. }
  65016. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  65017. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  65018. var pitch = Math.atan2(normal.y, len);
  65019. // Matrix
  65020. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  65021. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  65022. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  65023. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  65024. var vertexData = new BABYLON.VertexData();
  65025. vertexData.indices = [];
  65026. vertexData.positions = [];
  65027. vertexData.normals = [];
  65028. vertexData.uvs = [];
  65029. var currentVertexDataIndex = 0;
  65030. var extractDecalVector3 = function (indexId) {
  65031. var result = new BABYLON.PositionNormalVertex();
  65032. if (!indices || !positions || !normals) {
  65033. return result;
  65034. }
  65035. var vertexId = indices[indexId];
  65036. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  65037. // Send vector to decal local world
  65038. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  65039. // Get normal
  65040. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  65041. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  65042. return result;
  65043. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  65044. var clip = function (vertices, axis) {
  65045. if (vertices.length === 0) {
  65046. return vertices;
  65047. }
  65048. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  65049. var clipVertices = function (v0, v1) {
  65050. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  65051. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  65052. };
  65053. var result = new Array();
  65054. for (var index = 0; index < vertices.length; index += 3) {
  65055. var v1Out;
  65056. var v2Out;
  65057. var v3Out;
  65058. var total = 0;
  65059. var nV1 = null;
  65060. var nV2 = null;
  65061. var nV3 = null;
  65062. var nV4 = null;
  65063. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  65064. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  65065. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  65066. v1Out = d1 > 0;
  65067. v2Out = d2 > 0;
  65068. v3Out = d3 > 0;
  65069. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  65070. switch (total) {
  65071. case 0:
  65072. result.push(vertices[index]);
  65073. result.push(vertices[index + 1]);
  65074. result.push(vertices[index + 2]);
  65075. break;
  65076. case 1:
  65077. if (v1Out) {
  65078. nV1 = vertices[index + 1];
  65079. nV2 = vertices[index + 2];
  65080. nV3 = clipVertices(vertices[index], nV1);
  65081. nV4 = clipVertices(vertices[index], nV2);
  65082. }
  65083. if (v2Out) {
  65084. nV1 = vertices[index];
  65085. nV2 = vertices[index + 2];
  65086. nV3 = clipVertices(vertices[index + 1], nV1);
  65087. nV4 = clipVertices(vertices[index + 1], nV2);
  65088. result.push(nV3);
  65089. result.push(nV2.clone());
  65090. result.push(nV1.clone());
  65091. result.push(nV2.clone());
  65092. result.push(nV3.clone());
  65093. result.push(nV4);
  65094. break;
  65095. }
  65096. if (v3Out) {
  65097. nV1 = vertices[index];
  65098. nV2 = vertices[index + 1];
  65099. nV3 = clipVertices(vertices[index + 2], nV1);
  65100. nV4 = clipVertices(vertices[index + 2], nV2);
  65101. }
  65102. if (nV1 && nV2 && nV3 && nV4) {
  65103. result.push(nV1.clone());
  65104. result.push(nV2.clone());
  65105. result.push(nV3);
  65106. result.push(nV4);
  65107. result.push(nV3.clone());
  65108. result.push(nV2.clone());
  65109. }
  65110. break;
  65111. case 2:
  65112. if (!v1Out) {
  65113. nV1 = vertices[index].clone();
  65114. nV2 = clipVertices(nV1, vertices[index + 1]);
  65115. nV3 = clipVertices(nV1, vertices[index + 2]);
  65116. result.push(nV1);
  65117. result.push(nV2);
  65118. result.push(nV3);
  65119. }
  65120. if (!v2Out) {
  65121. nV1 = vertices[index + 1].clone();
  65122. nV2 = clipVertices(nV1, vertices[index + 2]);
  65123. nV3 = clipVertices(nV1, vertices[index]);
  65124. result.push(nV1);
  65125. result.push(nV2);
  65126. result.push(nV3);
  65127. }
  65128. if (!v3Out) {
  65129. nV1 = vertices[index + 2].clone();
  65130. nV2 = clipVertices(nV1, vertices[index]);
  65131. nV3 = clipVertices(nV1, vertices[index + 1]);
  65132. result.push(nV1);
  65133. result.push(nV2);
  65134. result.push(nV3);
  65135. }
  65136. break;
  65137. case 3:
  65138. break;
  65139. }
  65140. }
  65141. return result;
  65142. };
  65143. for (var index = 0; index < indices.length; index += 3) {
  65144. var faceVertices = new Array();
  65145. faceVertices.push(extractDecalVector3(index));
  65146. faceVertices.push(extractDecalVector3(index + 1));
  65147. faceVertices.push(extractDecalVector3(index + 2));
  65148. // Clip
  65149. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  65150. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  65151. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  65152. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  65153. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  65154. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  65155. if (faceVertices.length === 0) {
  65156. continue;
  65157. }
  65158. // Add UVs and get back to world
  65159. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  65160. var vertex = faceVertices[vIndex];
  65161. //TODO check for Int32Array | Uint32Array | Uint16Array
  65162. vertexData.indices.push(currentVertexDataIndex);
  65163. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  65164. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  65165. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  65166. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  65167. currentVertexDataIndex++;
  65168. }
  65169. }
  65170. // Return mesh
  65171. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  65172. vertexData.applyToMesh(decal);
  65173. decal.position = position.clone();
  65174. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  65175. return decal;
  65176. };
  65177. // Privates
  65178. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  65179. // extrusion geometry
  65180. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  65181. var tangents = path3D.getTangents();
  65182. var normals = path3D.getNormals();
  65183. var binormals = path3D.getBinormals();
  65184. var distances = path3D.getDistances();
  65185. var angle = 0;
  65186. var returnScale = function () { return scale !== null ? scale : 1; };
  65187. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  65188. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  65189. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  65190. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  65191. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  65192. for (var i = 0; i < curve.length; i++) {
  65193. var shapePath = new Array();
  65194. var angleStep = rotate(i, distances[i]);
  65195. var scaleRatio = scl(i, distances[i]);
  65196. for (var p = 0; p < shape.length; p++) {
  65197. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  65198. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  65199. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  65200. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  65201. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  65202. shapePath[p] = rotated;
  65203. }
  65204. shapePaths[index] = shapePath;
  65205. angle += angleStep;
  65206. index++;
  65207. }
  65208. // cap
  65209. var capPath = function (shapePath) {
  65210. var pointCap = Array();
  65211. var barycenter = BABYLON.Vector3.Zero();
  65212. var i;
  65213. for (i = 0; i < shapePath.length; i++) {
  65214. barycenter.addInPlace(shapePath[i]);
  65215. }
  65216. barycenter.scaleInPlace(1.0 / shapePath.length);
  65217. for (i = 0; i < shapePath.length; i++) {
  65218. pointCap.push(barycenter);
  65219. }
  65220. return pointCap;
  65221. };
  65222. switch (cap) {
  65223. case BABYLON.Mesh.NO_CAP:
  65224. break;
  65225. case BABYLON.Mesh.CAP_START:
  65226. shapePaths[0] = capPath(shapePaths[2]);
  65227. shapePaths[1] = shapePaths[2];
  65228. break;
  65229. case BABYLON.Mesh.CAP_END:
  65230. shapePaths[index] = shapePaths[index - 1];
  65231. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  65232. break;
  65233. case BABYLON.Mesh.CAP_ALL:
  65234. shapePaths[0] = capPath(shapePaths[2]);
  65235. shapePaths[1] = shapePaths[2];
  65236. shapePaths[index] = shapePaths[index - 1];
  65237. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  65238. break;
  65239. default:
  65240. break;
  65241. }
  65242. return shapePaths;
  65243. };
  65244. var path3D;
  65245. var pathArray;
  65246. if (instance) { // instance update
  65247. path3D = (instance.path3D).update(curve);
  65248. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  65249. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  65250. return instance;
  65251. }
  65252. // extruded shape creation
  65253. path3D = new BABYLON.Path3D(curve);
  65254. var newShapePaths = new Array();
  65255. cap = (cap < 0 || cap > 3) ? 0 : cap;
  65256. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  65257. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  65258. extrudedGeneric.pathArray = pathArray;
  65259. extrudedGeneric.path3D = path3D;
  65260. extrudedGeneric.cap = cap;
  65261. return extrudedGeneric;
  65262. };
  65263. return MeshBuilder;
  65264. }());
  65265. BABYLON.MeshBuilder = MeshBuilder;
  65266. })(BABYLON || (BABYLON = {}));
  65267. //# sourceMappingURL=babylon.meshBuilder.js.map
  65268. var BABYLON;
  65269. (function (BABYLON) {
  65270. /**
  65271. * Draco compression (https://google.github.io/draco/)
  65272. *
  65273. * This class wraps the Draco module.
  65274. *
  65275. * **Encoder**
  65276. *
  65277. * The encoder is not currently implemented.
  65278. *
  65279. * **Decoder**
  65280. *
  65281. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  65282. *
  65283. * To update the configuration, use the following code:
  65284. * ```javascript
  65285. * BABYLON.DracoCompression.Configuration = {
  65286. * decoder: {
  65287. * wasmUrl: "<url to the WebAssembly library>",
  65288. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  65289. * fallbackUrl: "<url to the fallback JavaScript library>",
  65290. * }
  65291. * };
  65292. * ```
  65293. *
  65294. * 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.
  65295. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  65296. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  65297. *
  65298. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  65299. * ```javascript
  65300. * var dracoCompression = new BABYLON.DracoCompression();
  65301. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  65302. * [BABYLON.VertexBuffer.PositionKind]: 0
  65303. * });
  65304. * ```
  65305. *
  65306. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  65307. */
  65308. var DracoCompression = /** @class */ (function () {
  65309. /**
  65310. * Constructor
  65311. */
  65312. function DracoCompression() {
  65313. }
  65314. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  65315. /**
  65316. * Returns true if the decoder is available.
  65317. */
  65318. get: function () {
  65319. if (typeof DracoDecoderModule !== "undefined") {
  65320. return true;
  65321. }
  65322. var decoder = DracoCompression.Configuration.decoder;
  65323. if (decoder) {
  65324. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  65325. return true;
  65326. }
  65327. if (decoder.fallbackUrl) {
  65328. return true;
  65329. }
  65330. }
  65331. return false;
  65332. },
  65333. enumerable: true,
  65334. configurable: true
  65335. });
  65336. /**
  65337. * Stop all async operations and release resources.
  65338. */
  65339. DracoCompression.prototype.dispose = function () {
  65340. };
  65341. /**
  65342. * Decode Draco compressed mesh data to vertex data.
  65343. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  65344. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  65345. * @returns A promise that resolves with the decoded vertex data
  65346. */
  65347. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  65348. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  65349. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  65350. var module = wrappedModule.module;
  65351. var vertexData = new BABYLON.VertexData();
  65352. var buffer = new module.DecoderBuffer();
  65353. buffer.Init(dataView, dataView.byteLength);
  65354. var decoder = new module.Decoder();
  65355. var geometry;
  65356. var status;
  65357. try {
  65358. var type = decoder.GetEncodedGeometryType(buffer);
  65359. switch (type) {
  65360. case module.TRIANGULAR_MESH:
  65361. geometry = new module.Mesh();
  65362. status = decoder.DecodeBufferToMesh(buffer, geometry);
  65363. break;
  65364. case module.POINT_CLOUD:
  65365. geometry = new module.PointCloud();
  65366. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  65367. break;
  65368. default:
  65369. throw new Error("Invalid geometry type " + type);
  65370. }
  65371. if (!status.ok() || !geometry.ptr) {
  65372. throw new Error(status.error_msg());
  65373. }
  65374. var numPoints = geometry.num_points();
  65375. if (type === module.TRIANGULAR_MESH) {
  65376. var numFaces = geometry.num_faces();
  65377. var faceIndices = new module.DracoInt32Array();
  65378. try {
  65379. var indices = new Uint32Array(numFaces * 3);
  65380. for (var i = 0; i < numFaces; i++) {
  65381. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  65382. var offset = i * 3;
  65383. indices[offset + 0] = faceIndices.GetValue(0);
  65384. indices[offset + 1] = faceIndices.GetValue(1);
  65385. indices[offset + 2] = faceIndices.GetValue(2);
  65386. }
  65387. vertexData.indices = indices;
  65388. }
  65389. finally {
  65390. module.destroy(faceIndices);
  65391. }
  65392. }
  65393. for (var kind in attributes) {
  65394. var uniqueId = attributes[kind];
  65395. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  65396. var dracoData = new module.DracoFloat32Array();
  65397. try {
  65398. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  65399. var babylonData = new Float32Array(numPoints * attribute.num_components());
  65400. for (var i = 0; i < babylonData.length; i++) {
  65401. babylonData[i] = dracoData.GetValue(i);
  65402. }
  65403. vertexData.set(babylonData, kind);
  65404. }
  65405. finally {
  65406. module.destroy(dracoData);
  65407. }
  65408. }
  65409. }
  65410. finally {
  65411. if (geometry) {
  65412. module.destroy(geometry);
  65413. }
  65414. module.destroy(decoder);
  65415. module.destroy(buffer);
  65416. }
  65417. return vertexData;
  65418. });
  65419. };
  65420. DracoCompression._GetDecoderModule = function () {
  65421. if (!DracoCompression._DecoderModulePromise) {
  65422. var promise = null;
  65423. var config_1 = {};
  65424. if (typeof DracoDecoderModule !== "undefined") {
  65425. promise = Promise.resolve();
  65426. }
  65427. else {
  65428. var decoder = DracoCompression.Configuration.decoder;
  65429. if (decoder) {
  65430. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  65431. promise = Promise.all([
  65432. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  65433. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  65434. config_1.wasmBinary = data;
  65435. })
  65436. ]);
  65437. }
  65438. else if (decoder.fallbackUrl) {
  65439. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  65440. }
  65441. }
  65442. }
  65443. if (!promise) {
  65444. throw new Error("Draco decoder module is not available");
  65445. }
  65446. DracoCompression._DecoderModulePromise = promise.then(function () {
  65447. return new Promise(function (resolve) {
  65448. config_1.onModuleLoaded = function (decoderModule) {
  65449. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  65450. resolve({ module: decoderModule });
  65451. };
  65452. DracoDecoderModule(config_1);
  65453. });
  65454. });
  65455. }
  65456. return DracoCompression._DecoderModulePromise;
  65457. };
  65458. DracoCompression._LoadScriptAsync = function (url) {
  65459. return new Promise(function (resolve, reject) {
  65460. BABYLON.Tools.LoadScript(url, function () {
  65461. resolve();
  65462. }, function (message) {
  65463. reject(new Error(message));
  65464. });
  65465. });
  65466. };
  65467. DracoCompression._LoadFileAsync = function (url) {
  65468. return new Promise(function (resolve, reject) {
  65469. BABYLON.Tools.LoadFile(url, function (data) {
  65470. resolve(data);
  65471. }, undefined, undefined, true, function (request, exception) {
  65472. reject(exception);
  65473. });
  65474. });
  65475. };
  65476. /**
  65477. * The configuration. Defaults to the following urls:
  65478. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  65479. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  65480. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  65481. */
  65482. DracoCompression.Configuration = {
  65483. decoder: {
  65484. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  65485. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  65486. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  65487. }
  65488. };
  65489. return DracoCompression;
  65490. }());
  65491. BABYLON.DracoCompression = DracoCompression;
  65492. })(BABYLON || (BABYLON = {}));
  65493. //# sourceMappingURL=babylon.dracoCompression.js.map
  65494. var BABYLON;
  65495. (function (BABYLON) {
  65496. // Sets the default audio engine to Babylon JS.
  65497. BABYLON.Engine.AudioEngineFactory = function () { return new AudioEngine(); };
  65498. var AudioEngine = /** @class */ (function () {
  65499. function AudioEngine() {
  65500. this._audioContext = null;
  65501. this._audioContextInitialized = false;
  65502. this.canUseWebAudio = false;
  65503. this.WarnedWebAudioUnsupported = false;
  65504. this.unlocked = false;
  65505. this.isMP3supported = false;
  65506. this.isOGGsupported = false;
  65507. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  65508. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  65509. this.canUseWebAudio = true;
  65510. }
  65511. var audioElem = document.createElement('audio');
  65512. try {
  65513. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  65514. this.isMP3supported = true;
  65515. }
  65516. }
  65517. catch (e) {
  65518. // protect error during capability check.
  65519. }
  65520. try {
  65521. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  65522. this.isOGGsupported = true;
  65523. }
  65524. }
  65525. catch (e) {
  65526. // protect error during capability check.
  65527. }
  65528. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  65529. this._unlockiOSaudio();
  65530. }
  65531. else {
  65532. this.unlocked = true;
  65533. }
  65534. }
  65535. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  65536. get: function () {
  65537. if (!this._audioContextInitialized) {
  65538. this._initializeAudioContext();
  65539. }
  65540. return this._audioContext;
  65541. },
  65542. enumerable: true,
  65543. configurable: true
  65544. });
  65545. AudioEngine.prototype._unlockiOSaudio = function () {
  65546. var _this = this;
  65547. var unlockaudio = function () {
  65548. if (!_this.audioContext) {
  65549. return;
  65550. }
  65551. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  65552. var source = _this.audioContext.createBufferSource();
  65553. source.buffer = buffer;
  65554. source.connect(_this.audioContext.destination);
  65555. source.start(0);
  65556. setTimeout(function () {
  65557. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  65558. _this.unlocked = true;
  65559. window.removeEventListener('touchend', unlockaudio, false);
  65560. if (_this.onAudioUnlocked) {
  65561. _this.onAudioUnlocked();
  65562. }
  65563. }
  65564. }, 0);
  65565. };
  65566. window.addEventListener('touchend', unlockaudio, false);
  65567. };
  65568. AudioEngine.prototype._initializeAudioContext = function () {
  65569. try {
  65570. if (this.canUseWebAudio) {
  65571. this._audioContext = new AudioContext();
  65572. // create a global volume gain node
  65573. this.masterGain = this._audioContext.createGain();
  65574. this.masterGain.gain.value = 1;
  65575. this.masterGain.connect(this._audioContext.destination);
  65576. this._audioContextInitialized = true;
  65577. }
  65578. }
  65579. catch (e) {
  65580. this.canUseWebAudio = false;
  65581. BABYLON.Tools.Error("Web Audio: " + e.message);
  65582. }
  65583. };
  65584. AudioEngine.prototype.dispose = function () {
  65585. if (this.canUseWebAudio && this._audioContextInitialized) {
  65586. if (this._connectedAnalyser && this._audioContext) {
  65587. this._connectedAnalyser.stopDebugCanvas();
  65588. this._connectedAnalyser.dispose();
  65589. this.masterGain.disconnect();
  65590. this.masterGain.connect(this._audioContext.destination);
  65591. this._connectedAnalyser = null;
  65592. }
  65593. this.masterGain.gain.value = 1;
  65594. }
  65595. this.WarnedWebAudioUnsupported = false;
  65596. };
  65597. AudioEngine.prototype.getGlobalVolume = function () {
  65598. if (this.canUseWebAudio && this._audioContextInitialized) {
  65599. return this.masterGain.gain.value;
  65600. }
  65601. else {
  65602. return -1;
  65603. }
  65604. };
  65605. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  65606. if (this.canUseWebAudio && this._audioContextInitialized) {
  65607. this.masterGain.gain.value = newVolume;
  65608. }
  65609. };
  65610. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  65611. if (this._connectedAnalyser) {
  65612. this._connectedAnalyser.stopDebugCanvas();
  65613. }
  65614. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  65615. this._connectedAnalyser = analyser;
  65616. this.masterGain.disconnect();
  65617. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  65618. }
  65619. };
  65620. return AudioEngine;
  65621. }());
  65622. BABYLON.AudioEngine = AudioEngine;
  65623. })(BABYLON || (BABYLON = {}));
  65624. //# sourceMappingURL=babylon.audioEngine.js.map
  65625. var BABYLON;
  65626. (function (BABYLON) {
  65627. var Sound = /** @class */ (function () {
  65628. /**
  65629. * Create a sound and attach it to a scene
  65630. * @param name Name of your sound
  65631. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  65632. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  65633. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  65634. */
  65635. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  65636. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  65637. var _this = this;
  65638. this.autoplay = false;
  65639. this.loop = false;
  65640. this.useCustomAttenuation = false;
  65641. this.spatialSound = false;
  65642. this.refDistance = 1;
  65643. this.rolloffFactor = 1;
  65644. this.maxDistance = 100;
  65645. this.distanceModel = "linear";
  65646. this._panningModel = "equalpower";
  65647. /**
  65648. * Observable event when the current playing sound finishes.
  65649. */
  65650. this.onEndedObservable = new BABYLON.Observable();
  65651. this._playbackRate = 1;
  65652. this._streaming = false;
  65653. this._startTime = 0;
  65654. this._startOffset = 0;
  65655. this._position = BABYLON.Vector3.Zero();
  65656. /** @hidden */
  65657. this._positionInEmitterSpace = false;
  65658. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  65659. this._volume = 1;
  65660. this._isReadyToPlay = false;
  65661. this.isPlaying = false;
  65662. this.isPaused = false;
  65663. this._isDirectional = false;
  65664. // Used if you'd like to create a directional sound.
  65665. // If not set, the sound will be omnidirectional
  65666. this._coneInnerAngle = 360;
  65667. this._coneOuterAngle = 360;
  65668. this._coneOuterGain = 0;
  65669. this._isOutputConnected = false;
  65670. this._urlType = "Unknown";
  65671. this.name = name;
  65672. this._scene = scene;
  65673. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  65674. if (!compo) {
  65675. compo = new BABYLON.AudioSceneComponent(scene);
  65676. scene._addComponent(compo);
  65677. }
  65678. this._readyToPlayCallback = readyToPlayCallback;
  65679. // Default custom attenuation function is a linear attenuation
  65680. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  65681. if (currentDistance < maxDistance) {
  65682. return currentVolume * (1 - currentDistance / maxDistance);
  65683. }
  65684. else {
  65685. return 0;
  65686. }
  65687. };
  65688. if (options) {
  65689. this.autoplay = options.autoplay || false;
  65690. this.loop = options.loop || false;
  65691. // if volume === 0, we need another way to check this option
  65692. if (options.volume !== undefined) {
  65693. this._volume = options.volume;
  65694. }
  65695. this.spatialSound = options.spatialSound || false;
  65696. this.maxDistance = options.maxDistance || 100;
  65697. this.useCustomAttenuation = options.useCustomAttenuation || false;
  65698. this.rolloffFactor = options.rolloffFactor || 1;
  65699. this.refDistance = options.refDistance || 1;
  65700. this.distanceModel = options.distanceModel || "linear";
  65701. this._playbackRate = options.playbackRate || 1;
  65702. this._streaming = options.streaming || false;
  65703. }
  65704. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65705. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  65706. this._soundGain.gain.value = this._volume;
  65707. this._inputAudioNode = this._soundGain;
  65708. this._outputAudioNode = this._soundGain;
  65709. if (this.spatialSound) {
  65710. this._createSpatialParameters();
  65711. }
  65712. this._scene.mainSoundTrack.AddSound(this);
  65713. var validParameter = true;
  65714. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  65715. if (urlOrArrayBuffer) {
  65716. try {
  65717. if (typeof (urlOrArrayBuffer) === "string") {
  65718. this._urlType = "String";
  65719. }
  65720. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  65721. this._urlType = "ArrayBuffer";
  65722. }
  65723. else if (urlOrArrayBuffer instanceof MediaStream) {
  65724. this._urlType = "MediaStream";
  65725. }
  65726. else if (Array.isArray(urlOrArrayBuffer)) {
  65727. this._urlType = "Array";
  65728. }
  65729. var urls = [];
  65730. var codecSupportedFound = false;
  65731. switch (this._urlType) {
  65732. case "MediaStream":
  65733. this._streaming = true;
  65734. this._isReadyToPlay = true;
  65735. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  65736. if (this.autoplay) {
  65737. this.play();
  65738. }
  65739. if (this._readyToPlayCallback) {
  65740. this._readyToPlayCallback();
  65741. }
  65742. break;
  65743. case "ArrayBuffer":
  65744. if (urlOrArrayBuffer.byteLength > 0) {
  65745. codecSupportedFound = true;
  65746. this._soundLoaded(urlOrArrayBuffer);
  65747. }
  65748. break;
  65749. case "String":
  65750. urls.push(urlOrArrayBuffer);
  65751. case "Array":
  65752. if (urls.length === 0)
  65753. urls = urlOrArrayBuffer;
  65754. // If we found a supported format, we load it immediately and stop the loop
  65755. for (var i = 0; i < urls.length; i++) {
  65756. var url = urls[i];
  65757. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  65758. codecSupportedFound = true;
  65759. }
  65760. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  65761. codecSupportedFound = true;
  65762. }
  65763. if (url.indexOf(".wav", url.length - 4) !== -1) {
  65764. codecSupportedFound = true;
  65765. }
  65766. if (url.indexOf("blob:") !== -1) {
  65767. codecSupportedFound = true;
  65768. }
  65769. if (codecSupportedFound) {
  65770. // Loading sound using XHR2
  65771. if (!this._streaming) {
  65772. this._scene._loadFile(url, function (data) {
  65773. _this._soundLoaded(data);
  65774. }, undefined, true, true, function (exception) {
  65775. if (exception) {
  65776. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  65777. }
  65778. BABYLON.Tools.Error("Sound creation aborted.");
  65779. _this._scene.mainSoundTrack.RemoveSound(_this);
  65780. });
  65781. }
  65782. // Streaming sound using HTML5 Audio tag
  65783. else {
  65784. this._htmlAudioElement = new Audio(url);
  65785. this._htmlAudioElement.controls = false;
  65786. this._htmlAudioElement.loop = this.loop;
  65787. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  65788. this._htmlAudioElement.preload = "auto";
  65789. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  65790. _this._isReadyToPlay = true;
  65791. if (_this.autoplay) {
  65792. _this.play();
  65793. }
  65794. if (_this._readyToPlayCallback) {
  65795. _this._readyToPlayCallback();
  65796. }
  65797. });
  65798. document.body.appendChild(this._htmlAudioElement);
  65799. }
  65800. break;
  65801. }
  65802. }
  65803. break;
  65804. default:
  65805. validParameter = false;
  65806. break;
  65807. }
  65808. if (!validParameter) {
  65809. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  65810. }
  65811. else {
  65812. if (!codecSupportedFound) {
  65813. this._isReadyToPlay = true;
  65814. // Simulating a ready to play event to avoid breaking code path
  65815. if (this._readyToPlayCallback) {
  65816. window.setTimeout(function () {
  65817. if (_this._readyToPlayCallback) {
  65818. _this._readyToPlayCallback();
  65819. }
  65820. }, 1000);
  65821. }
  65822. }
  65823. }
  65824. }
  65825. catch (ex) {
  65826. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  65827. this._scene.mainSoundTrack.RemoveSound(this);
  65828. }
  65829. }
  65830. }
  65831. else {
  65832. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  65833. this._scene.mainSoundTrack.AddSound(this);
  65834. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  65835. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  65836. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  65837. }
  65838. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  65839. if (this._readyToPlayCallback) {
  65840. window.setTimeout(function () {
  65841. if (_this._readyToPlayCallback) {
  65842. _this._readyToPlayCallback();
  65843. }
  65844. }, 1000);
  65845. }
  65846. }
  65847. }
  65848. Sound.prototype.dispose = function () {
  65849. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65850. if (this.isPlaying) {
  65851. this.stop();
  65852. }
  65853. this._isReadyToPlay = false;
  65854. if (this.soundTrackId === -1) {
  65855. this._scene.mainSoundTrack.RemoveSound(this);
  65856. }
  65857. else if (this._scene.soundTracks) {
  65858. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  65859. }
  65860. if (this._soundGain) {
  65861. this._soundGain.disconnect();
  65862. this._soundGain = null;
  65863. }
  65864. if (this._soundPanner) {
  65865. this._soundPanner.disconnect();
  65866. this._soundPanner = null;
  65867. }
  65868. if (this._soundSource) {
  65869. this._soundSource.disconnect();
  65870. this._soundSource = null;
  65871. }
  65872. this._audioBuffer = null;
  65873. if (this._htmlAudioElement) {
  65874. this._htmlAudioElement.pause();
  65875. this._htmlAudioElement.src = "";
  65876. document.body.removeChild(this._htmlAudioElement);
  65877. }
  65878. if (this._streamingSource) {
  65879. this._streamingSource.disconnect();
  65880. }
  65881. if (this._connectedMesh && this._registerFunc) {
  65882. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65883. this._connectedMesh = null;
  65884. }
  65885. }
  65886. };
  65887. Sound.prototype.isReady = function () {
  65888. return this._isReadyToPlay;
  65889. };
  65890. Sound.prototype._soundLoaded = function (audioData) {
  65891. var _this = this;
  65892. if (!BABYLON.Engine.audioEngine.audioContext) {
  65893. return;
  65894. }
  65895. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  65896. _this._audioBuffer = buffer;
  65897. _this._isReadyToPlay = true;
  65898. if (_this.autoplay) {
  65899. _this.play();
  65900. }
  65901. if (_this._readyToPlayCallback) {
  65902. _this._readyToPlayCallback();
  65903. }
  65904. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  65905. };
  65906. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  65907. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65908. this._audioBuffer = audioBuffer;
  65909. this._isReadyToPlay = true;
  65910. }
  65911. };
  65912. Sound.prototype.updateOptions = function (options) {
  65913. if (options) {
  65914. this.loop = options.loop || this.loop;
  65915. this.maxDistance = options.maxDistance || this.maxDistance;
  65916. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  65917. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  65918. this.refDistance = options.refDistance || this.refDistance;
  65919. this.distanceModel = options.distanceModel || this.distanceModel;
  65920. this._playbackRate = options.playbackRate || this._playbackRate;
  65921. this._updateSpatialParameters();
  65922. if (this.isPlaying) {
  65923. if (this._streaming && this._htmlAudioElement) {
  65924. this._htmlAudioElement.playbackRate = this._playbackRate;
  65925. }
  65926. else {
  65927. if (this._soundSource) {
  65928. this._soundSource.playbackRate.value = this._playbackRate;
  65929. }
  65930. }
  65931. }
  65932. }
  65933. };
  65934. Sound.prototype._createSpatialParameters = function () {
  65935. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65936. if (this._scene.headphone) {
  65937. this._panningModel = "HRTF";
  65938. }
  65939. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  65940. this._updateSpatialParameters();
  65941. this._soundPanner.connect(this._outputAudioNode);
  65942. this._inputAudioNode = this._soundPanner;
  65943. }
  65944. };
  65945. Sound.prototype._updateSpatialParameters = function () {
  65946. if (this.spatialSound && this._soundPanner) {
  65947. if (this.useCustomAttenuation) {
  65948. // Tricks to disable in a way embedded Web Audio attenuation
  65949. this._soundPanner.distanceModel = "linear";
  65950. this._soundPanner.maxDistance = Number.MAX_VALUE;
  65951. this._soundPanner.refDistance = 1;
  65952. this._soundPanner.rolloffFactor = 1;
  65953. this._soundPanner.panningModel = this._panningModel;
  65954. }
  65955. else {
  65956. this._soundPanner.distanceModel = this.distanceModel;
  65957. this._soundPanner.maxDistance = this.maxDistance;
  65958. this._soundPanner.refDistance = this.refDistance;
  65959. this._soundPanner.rolloffFactor = this.rolloffFactor;
  65960. this._soundPanner.panningModel = this._panningModel;
  65961. }
  65962. }
  65963. };
  65964. Sound.prototype.switchPanningModelToHRTF = function () {
  65965. this._panningModel = "HRTF";
  65966. this._switchPanningModel();
  65967. };
  65968. Sound.prototype.switchPanningModelToEqualPower = function () {
  65969. this._panningModel = "equalpower";
  65970. this._switchPanningModel();
  65971. };
  65972. Sound.prototype._switchPanningModel = function () {
  65973. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65974. this._soundPanner.panningModel = this._panningModel;
  65975. }
  65976. };
  65977. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  65978. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65979. if (this._isOutputConnected) {
  65980. this._outputAudioNode.disconnect();
  65981. }
  65982. this._outputAudioNode.connect(soundTrackAudioNode);
  65983. this._isOutputConnected = true;
  65984. }
  65985. };
  65986. /**
  65987. * Transform this sound into a directional source
  65988. * @param coneInnerAngle Size of the inner cone in degree
  65989. * @param coneOuterAngle Size of the outer cone in degree
  65990. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  65991. */
  65992. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  65993. if (coneOuterAngle < coneInnerAngle) {
  65994. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  65995. return;
  65996. }
  65997. this._coneInnerAngle = coneInnerAngle;
  65998. this._coneOuterAngle = coneOuterAngle;
  65999. this._coneOuterGain = coneOuterGain;
  66000. this._isDirectional = true;
  66001. if (this.isPlaying && this.loop) {
  66002. this.stop();
  66003. this.play();
  66004. }
  66005. };
  66006. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  66007. /**
  66008. * Gets or sets the inner angle for the directional cone.
  66009. */
  66010. get: function () {
  66011. return this._coneInnerAngle;
  66012. },
  66013. /**
  66014. * Gets or sets the inner angle for the directional cone.
  66015. */
  66016. set: function (value) {
  66017. if (value != this._coneInnerAngle) {
  66018. if (this._coneOuterAngle < value) {
  66019. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66020. return;
  66021. }
  66022. this._coneInnerAngle = value;
  66023. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66024. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  66025. }
  66026. }
  66027. },
  66028. enumerable: true,
  66029. configurable: true
  66030. });
  66031. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  66032. /**
  66033. * Gets or sets the outer angle for the directional cone.
  66034. */
  66035. get: function () {
  66036. return this._coneOuterAngle;
  66037. },
  66038. /**
  66039. * Gets or sets the outer angle for the directional cone.
  66040. */
  66041. set: function (value) {
  66042. if (value != this._coneOuterAngle) {
  66043. if (value < this._coneInnerAngle) {
  66044. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66045. return;
  66046. }
  66047. this._coneOuterAngle = value;
  66048. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66049. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  66050. }
  66051. }
  66052. },
  66053. enumerable: true,
  66054. configurable: true
  66055. });
  66056. Sound.prototype.setPosition = function (newPosition) {
  66057. this._position = newPosition;
  66058. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  66059. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  66060. }
  66061. };
  66062. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  66063. this._localDirection = newLocalDirection;
  66064. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  66065. this._updateDirection();
  66066. }
  66067. };
  66068. Sound.prototype._updateDirection = function () {
  66069. if (!this._connectedMesh || !this._soundPanner) {
  66070. return;
  66071. }
  66072. var mat = this._connectedMesh.getWorldMatrix();
  66073. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  66074. direction.normalize();
  66075. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  66076. };
  66077. Sound.prototype.updateDistanceFromListener = function () {
  66078. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  66079. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  66080. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  66081. }
  66082. };
  66083. Sound.prototype.setAttenuationFunction = function (callback) {
  66084. this._customAttenuationFunction = callback;
  66085. };
  66086. /**
  66087. * Play the sound
  66088. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  66089. * @param offset (optional) Start the sound setting it at a specific time
  66090. */
  66091. Sound.prototype.play = function (time, offset) {
  66092. var _this = this;
  66093. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  66094. try {
  66095. if (this._startOffset < 0) {
  66096. time = -this._startOffset;
  66097. this._startOffset = 0;
  66098. }
  66099. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  66100. if (!this._soundSource || !this._streamingSource) {
  66101. if (this.spatialSound && this._soundPanner) {
  66102. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  66103. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  66104. }
  66105. if (this._isDirectional) {
  66106. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  66107. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  66108. this._soundPanner.coneOuterGain = this._coneOuterGain;
  66109. if (this._connectedMesh) {
  66110. this._updateDirection();
  66111. }
  66112. else {
  66113. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  66114. }
  66115. }
  66116. }
  66117. }
  66118. if (this._streaming) {
  66119. if (!this._streamingSource) {
  66120. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  66121. this._htmlAudioElement.onended = function () { _this._onended(); };
  66122. this._htmlAudioElement.playbackRate = this._playbackRate;
  66123. }
  66124. this._streamingSource.disconnect();
  66125. this._streamingSource.connect(this._inputAudioNode);
  66126. if (this._htmlAudioElement) {
  66127. this._htmlAudioElement.play();
  66128. }
  66129. }
  66130. else {
  66131. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  66132. this._soundSource.buffer = this._audioBuffer;
  66133. this._soundSource.connect(this._inputAudioNode);
  66134. this._soundSource.loop = this.loop;
  66135. this._soundSource.playbackRate.value = this._playbackRate;
  66136. this._soundSource.onended = function () { _this._onended(); };
  66137. if (this._soundSource.buffer) {
  66138. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  66139. }
  66140. }
  66141. this._startTime = startTime;
  66142. this.isPlaying = true;
  66143. this.isPaused = false;
  66144. }
  66145. catch (ex) {
  66146. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  66147. }
  66148. }
  66149. };
  66150. Sound.prototype._onended = function () {
  66151. this.isPlaying = false;
  66152. if (this.onended) {
  66153. this.onended();
  66154. }
  66155. this.onEndedObservable.notifyObservers(this);
  66156. };
  66157. /**
  66158. * Stop the sound
  66159. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  66160. */
  66161. Sound.prototype.stop = function (time) {
  66162. if (this.isPlaying) {
  66163. if (this._streaming) {
  66164. if (this._htmlAudioElement) {
  66165. this._htmlAudioElement.pause();
  66166. // Test needed for Firefox or it will generate an Invalid State Error
  66167. if (this._htmlAudioElement.currentTime > 0) {
  66168. this._htmlAudioElement.currentTime = 0;
  66169. }
  66170. }
  66171. else {
  66172. this._streamingSource.disconnect();
  66173. }
  66174. }
  66175. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  66176. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  66177. this._soundSource.stop(stopTime);
  66178. this._soundSource.onended = function () { };
  66179. if (!this.isPaused) {
  66180. this._startOffset = 0;
  66181. }
  66182. }
  66183. this.isPlaying = false;
  66184. }
  66185. };
  66186. Sound.prototype.pause = function () {
  66187. if (this.isPlaying) {
  66188. this.isPaused = true;
  66189. if (this._streaming) {
  66190. if (this._htmlAudioElement) {
  66191. this._htmlAudioElement.pause();
  66192. }
  66193. else {
  66194. this._streamingSource.disconnect();
  66195. }
  66196. }
  66197. else if (BABYLON.Engine.audioEngine.audioContext) {
  66198. this.stop(0);
  66199. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  66200. }
  66201. }
  66202. };
  66203. Sound.prototype.setVolume = function (newVolume, time) {
  66204. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  66205. if (time && BABYLON.Engine.audioEngine.audioContext) {
  66206. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  66207. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  66208. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  66209. }
  66210. else {
  66211. this._soundGain.gain.value = newVolume;
  66212. }
  66213. }
  66214. this._volume = newVolume;
  66215. };
  66216. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  66217. this._playbackRate = newPlaybackRate;
  66218. if (this.isPlaying) {
  66219. if (this._streaming && this._htmlAudioElement) {
  66220. this._htmlAudioElement.playbackRate = this._playbackRate;
  66221. }
  66222. else if (this._soundSource) {
  66223. this._soundSource.playbackRate.value = this._playbackRate;
  66224. }
  66225. }
  66226. };
  66227. Sound.prototype.getVolume = function () {
  66228. return this._volume;
  66229. };
  66230. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  66231. var _this = this;
  66232. if (this._connectedMesh && this._registerFunc) {
  66233. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  66234. this._registerFunc = null;
  66235. }
  66236. this._connectedMesh = meshToConnectTo;
  66237. if (!this.spatialSound) {
  66238. this.spatialSound = true;
  66239. this._createSpatialParameters();
  66240. if (this.isPlaying && this.loop) {
  66241. this.stop();
  66242. this.play();
  66243. }
  66244. }
  66245. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  66246. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  66247. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  66248. };
  66249. Sound.prototype.detachFromMesh = function () {
  66250. if (this._connectedMesh && this._registerFunc) {
  66251. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  66252. this._registerFunc = null;
  66253. this._connectedMesh = null;
  66254. }
  66255. };
  66256. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  66257. if (!node.getBoundingInfo) {
  66258. return;
  66259. }
  66260. var mesh = node;
  66261. if (this._positionInEmitterSpace) {
  66262. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  66263. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  66264. }
  66265. else {
  66266. var boundingInfo = mesh.getBoundingInfo();
  66267. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  66268. }
  66269. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  66270. this._updateDirection();
  66271. }
  66272. };
  66273. Sound.prototype.clone = function () {
  66274. var _this = this;
  66275. if (!this._streaming) {
  66276. var setBufferAndRun = function () {
  66277. if (_this._isReadyToPlay) {
  66278. clonedSound._audioBuffer = _this.getAudioBuffer();
  66279. clonedSound._isReadyToPlay = true;
  66280. if (clonedSound.autoplay) {
  66281. clonedSound.play();
  66282. }
  66283. }
  66284. else {
  66285. window.setTimeout(setBufferAndRun, 300);
  66286. }
  66287. };
  66288. var currentOptions = {
  66289. autoplay: this.autoplay, loop: this.loop,
  66290. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  66291. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  66292. refDistance: this.refDistance, distanceModel: this.distanceModel
  66293. };
  66294. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  66295. if (this.useCustomAttenuation) {
  66296. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  66297. }
  66298. clonedSound.setPosition(this._position);
  66299. clonedSound.setPlaybackRate(this._playbackRate);
  66300. setBufferAndRun();
  66301. return clonedSound;
  66302. }
  66303. // Can't clone a streaming sound
  66304. else {
  66305. return null;
  66306. }
  66307. };
  66308. Sound.prototype.getAudioBuffer = function () {
  66309. return this._audioBuffer;
  66310. };
  66311. Sound.prototype.serialize = function () {
  66312. var serializationObject = {
  66313. name: this.name,
  66314. url: this.name,
  66315. autoplay: this.autoplay,
  66316. loop: this.loop,
  66317. volume: this._volume,
  66318. spatialSound: this.spatialSound,
  66319. maxDistance: this.maxDistance,
  66320. rolloffFactor: this.rolloffFactor,
  66321. refDistance: this.refDistance,
  66322. distanceModel: this.distanceModel,
  66323. playbackRate: this._playbackRate,
  66324. panningModel: this._panningModel,
  66325. soundTrackId: this.soundTrackId
  66326. };
  66327. if (this.spatialSound) {
  66328. if (this._connectedMesh)
  66329. serializationObject.connectedMeshId = this._connectedMesh.id;
  66330. serializationObject.position = this._position.asArray();
  66331. serializationObject.refDistance = this.refDistance;
  66332. serializationObject.distanceModel = this.distanceModel;
  66333. serializationObject.isDirectional = this._isDirectional;
  66334. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  66335. serializationObject.coneInnerAngle = this._coneInnerAngle;
  66336. serializationObject.coneOuterAngle = this._coneOuterAngle;
  66337. serializationObject.coneOuterGain = this._coneOuterGain;
  66338. }
  66339. return serializationObject;
  66340. };
  66341. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  66342. var soundName = parsedSound.name;
  66343. var soundUrl;
  66344. if (parsedSound.url) {
  66345. soundUrl = rootUrl + parsedSound.url;
  66346. }
  66347. else {
  66348. soundUrl = rootUrl + soundName;
  66349. }
  66350. var options = {
  66351. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  66352. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  66353. rolloffFactor: parsedSound.rolloffFactor,
  66354. refDistance: parsedSound.refDistance,
  66355. distanceModel: parsedSound.distanceModel,
  66356. playbackRate: parsedSound.playbackRate
  66357. };
  66358. var newSound;
  66359. if (!sourceSound) {
  66360. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  66361. scene._addPendingData(newSound);
  66362. }
  66363. else {
  66364. var setBufferAndRun = function () {
  66365. if (sourceSound._isReadyToPlay) {
  66366. newSound._audioBuffer = sourceSound.getAudioBuffer();
  66367. newSound._isReadyToPlay = true;
  66368. if (newSound.autoplay) {
  66369. newSound.play();
  66370. }
  66371. }
  66372. else {
  66373. window.setTimeout(setBufferAndRun, 300);
  66374. }
  66375. };
  66376. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  66377. setBufferAndRun();
  66378. }
  66379. if (parsedSound.position) {
  66380. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  66381. newSound.setPosition(soundPosition);
  66382. }
  66383. if (parsedSound.isDirectional) {
  66384. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  66385. if (parsedSound.localDirectionToMesh) {
  66386. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  66387. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  66388. }
  66389. }
  66390. if (parsedSound.connectedMeshId) {
  66391. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  66392. if (connectedMesh) {
  66393. newSound.attachToMesh(connectedMesh);
  66394. }
  66395. }
  66396. return newSound;
  66397. };
  66398. return Sound;
  66399. }());
  66400. BABYLON.Sound = Sound;
  66401. })(BABYLON || (BABYLON = {}));
  66402. //# sourceMappingURL=babylon.sound.js.map
  66403. var BABYLON;
  66404. (function (BABYLON) {
  66405. var SoundTrack = /** @class */ (function () {
  66406. function SoundTrack(scene, options) {
  66407. this.id = -1;
  66408. this._isMainTrack = false;
  66409. this._isInitialized = false;
  66410. this._scene = scene;
  66411. this.soundCollection = new Array();
  66412. this._options = options;
  66413. if (!this._isMainTrack && this._scene.soundTracks) {
  66414. this._scene.soundTracks.push(this);
  66415. this.id = this._scene.soundTracks.length - 1;
  66416. }
  66417. }
  66418. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  66419. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  66420. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  66421. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  66422. if (this._options) {
  66423. if (this._options.volume) {
  66424. this._outputAudioNode.gain.value = this._options.volume;
  66425. }
  66426. if (this._options.mainTrack) {
  66427. this._isMainTrack = this._options.mainTrack;
  66428. }
  66429. }
  66430. this._isInitialized = true;
  66431. }
  66432. };
  66433. SoundTrack.prototype.dispose = function () {
  66434. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  66435. if (this._connectedAnalyser) {
  66436. this._connectedAnalyser.stopDebugCanvas();
  66437. }
  66438. while (this.soundCollection.length) {
  66439. this.soundCollection[0].dispose();
  66440. }
  66441. if (this._outputAudioNode) {
  66442. this._outputAudioNode.disconnect();
  66443. }
  66444. this._outputAudioNode = null;
  66445. }
  66446. };
  66447. SoundTrack.prototype.AddSound = function (sound) {
  66448. if (!this._isInitialized) {
  66449. this._initializeSoundTrackAudioGraph();
  66450. }
  66451. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66452. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  66453. }
  66454. if (sound.soundTrackId) {
  66455. if (sound.soundTrackId === -1) {
  66456. this._scene.mainSoundTrack.RemoveSound(sound);
  66457. }
  66458. else if (this._scene.soundTracks) {
  66459. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  66460. }
  66461. }
  66462. this.soundCollection.push(sound);
  66463. sound.soundTrackId = this.id;
  66464. };
  66465. SoundTrack.prototype.RemoveSound = function (sound) {
  66466. var index = this.soundCollection.indexOf(sound);
  66467. if (index !== -1) {
  66468. this.soundCollection.splice(index, 1);
  66469. }
  66470. };
  66471. SoundTrack.prototype.setVolume = function (newVolume) {
  66472. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66473. this._outputAudioNode.gain.value = newVolume;
  66474. }
  66475. };
  66476. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  66477. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66478. for (var i = 0; i < this.soundCollection.length; i++) {
  66479. this.soundCollection[i].switchPanningModelToHRTF();
  66480. }
  66481. }
  66482. };
  66483. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  66484. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66485. for (var i = 0; i < this.soundCollection.length; i++) {
  66486. this.soundCollection[i].switchPanningModelToEqualPower();
  66487. }
  66488. }
  66489. };
  66490. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  66491. if (this._connectedAnalyser) {
  66492. this._connectedAnalyser.stopDebugCanvas();
  66493. }
  66494. this._connectedAnalyser = analyser;
  66495. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66496. this._outputAudioNode.disconnect();
  66497. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  66498. }
  66499. };
  66500. return SoundTrack;
  66501. }());
  66502. BABYLON.SoundTrack = SoundTrack;
  66503. })(BABYLON || (BABYLON = {}));
  66504. //# sourceMappingURL=babylon.soundtrack.js.map
  66505. var BABYLON;
  66506. (function (BABYLON) {
  66507. /**
  66508. * Class used to work with sound analyzer using fast fourier transform (FFT)
  66509. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  66510. */
  66511. var Analyser = /** @class */ (function () {
  66512. /**
  66513. * Creates a new analyser
  66514. * @param scene defines hosting scene
  66515. */
  66516. function Analyser(scene) {
  66517. /**
  66518. * Gets or sets the smoothing
  66519. * @ignorenaming
  66520. */
  66521. this.SMOOTHING = 0.75;
  66522. /**
  66523. * Gets or sets the FFT table size
  66524. * @ignorenaming
  66525. */
  66526. this.FFT_SIZE = 512;
  66527. /**
  66528. * Gets or sets the bar graph amplitude
  66529. * @ignorenaming
  66530. */
  66531. this.BARGRAPHAMPLITUDE = 256;
  66532. /**
  66533. * Gets or sets the position of the debug canvas
  66534. * @ignorenaming
  66535. */
  66536. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  66537. /**
  66538. * Gets or sets the debug canvas size
  66539. * @ignorenaming
  66540. */
  66541. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  66542. this._scene = scene;
  66543. this._audioEngine = BABYLON.Engine.audioEngine;
  66544. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  66545. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  66546. this._webAudioAnalyser.minDecibels = -140;
  66547. this._webAudioAnalyser.maxDecibels = 0;
  66548. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  66549. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  66550. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  66551. }
  66552. }
  66553. /**
  66554. * Get the number of data values you will have to play with for the visualization
  66555. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  66556. * @returns a number
  66557. */
  66558. Analyser.prototype.getFrequencyBinCount = function () {
  66559. if (this._audioEngine.canUseWebAudio) {
  66560. return this._webAudioAnalyser.frequencyBinCount;
  66561. }
  66562. else {
  66563. return 0;
  66564. }
  66565. };
  66566. /**
  66567. * Gets the current frequency data as a byte array
  66568. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  66569. * @returns a Uint8Array
  66570. */
  66571. Analyser.prototype.getByteFrequencyData = function () {
  66572. if (this._audioEngine.canUseWebAudio) {
  66573. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66574. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66575. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  66576. }
  66577. return this._byteFreqs;
  66578. };
  66579. /**
  66580. * Gets the current waveform as a byte array
  66581. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  66582. * @returns a Uint8Array
  66583. */
  66584. Analyser.prototype.getByteTimeDomainData = function () {
  66585. if (this._audioEngine.canUseWebAudio) {
  66586. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66587. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66588. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  66589. }
  66590. return this._byteTime;
  66591. };
  66592. /**
  66593. * Gets the current frequency data as a float array
  66594. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  66595. * @returns a Float32Array
  66596. */
  66597. Analyser.prototype.getFloatFrequencyData = function () {
  66598. if (this._audioEngine.canUseWebAudio) {
  66599. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66600. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66601. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  66602. }
  66603. return this._floatFreqs;
  66604. };
  66605. /**
  66606. * Renders the debug canvas
  66607. */
  66608. Analyser.prototype.drawDebugCanvas = function () {
  66609. var _this = this;
  66610. if (this._audioEngine.canUseWebAudio) {
  66611. if (!this._debugCanvas) {
  66612. this._debugCanvas = document.createElement("canvas");
  66613. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  66614. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  66615. this._debugCanvas.style.position = "absolute";
  66616. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  66617. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  66618. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  66619. document.body.appendChild(this._debugCanvas);
  66620. this._registerFunc = function () {
  66621. _this.drawDebugCanvas();
  66622. };
  66623. this._scene.registerBeforeRender(this._registerFunc);
  66624. }
  66625. if (this._registerFunc && this._debugCanvasContext) {
  66626. var workingArray = this.getByteFrequencyData();
  66627. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  66628. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  66629. // Draw the frequency domain chart.
  66630. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  66631. var value = workingArray[i];
  66632. var percent = value / this.BARGRAPHAMPLITUDE;
  66633. var height = this.DEBUGCANVASSIZE.height * percent;
  66634. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  66635. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  66636. var hue = i / this.getFrequencyBinCount() * 360;
  66637. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  66638. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  66639. }
  66640. }
  66641. }
  66642. };
  66643. /**
  66644. * Stops rendering the debug canvas and removes it
  66645. */
  66646. Analyser.prototype.stopDebugCanvas = function () {
  66647. if (this._debugCanvas) {
  66648. if (this._registerFunc) {
  66649. this._scene.unregisterBeforeRender(this._registerFunc);
  66650. this._registerFunc = null;
  66651. }
  66652. document.body.removeChild(this._debugCanvas);
  66653. this._debugCanvas = null;
  66654. this._debugCanvasContext = null;
  66655. }
  66656. };
  66657. /**
  66658. * Connects two audio nodes
  66659. * @param inputAudioNode defines first node to connect
  66660. * @param outputAudioNode defines second node to connect
  66661. */
  66662. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  66663. if (this._audioEngine.canUseWebAudio) {
  66664. inputAudioNode.connect(this._webAudioAnalyser);
  66665. this._webAudioAnalyser.connect(outputAudioNode);
  66666. }
  66667. };
  66668. /**
  66669. * Releases all associated resources
  66670. */
  66671. Analyser.prototype.dispose = function () {
  66672. if (this._audioEngine.canUseWebAudio) {
  66673. this._webAudioAnalyser.disconnect();
  66674. }
  66675. };
  66676. return Analyser;
  66677. }());
  66678. BABYLON.Analyser = Analyser;
  66679. })(BABYLON || (BABYLON = {}));
  66680. //# sourceMappingURL=babylon.analyser.js.map
  66681. var BABYLON;
  66682. (function (BABYLON) {
  66683. /**
  66684. * Wraps one or more Sound objects and selects one with random weight for playback.
  66685. */
  66686. var WeightedSound = /** @class */ (function () {
  66687. /**
  66688. * Creates a new WeightedSound from the list of sounds given.
  66689. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  66690. * @param sounds Array of Sounds that will be selected from.
  66691. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  66692. */
  66693. function WeightedSound(loop, sounds, weights) {
  66694. var _this = this;
  66695. /** When true a Sound will be selected and played when the current playing Sound completes. */
  66696. this.loop = false;
  66697. this._coneInnerAngle = 360;
  66698. this._coneOuterAngle = 360;
  66699. this._volume = 1;
  66700. /** A Sound is currently playing. */
  66701. this.isPlaying = false;
  66702. /** A Sound is currently paused. */
  66703. this.isPaused = false;
  66704. this._sounds = [];
  66705. this._weights = [];
  66706. if (sounds.length !== weights.length) {
  66707. throw new Error('Sounds length does not equal weights length');
  66708. }
  66709. this.loop = loop;
  66710. this._weights = weights;
  66711. // Normalize the weights
  66712. var weightSum = 0;
  66713. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  66714. var weight = weights_1[_i];
  66715. weightSum += weight;
  66716. }
  66717. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  66718. for (var i = 0; i < this._weights.length; i++) {
  66719. this._weights[i] *= invWeightSum;
  66720. }
  66721. this._sounds = sounds;
  66722. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  66723. var sound = _b[_a];
  66724. sound.onEndedObservable.add(function () { _this._onended(); });
  66725. }
  66726. }
  66727. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  66728. /**
  66729. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  66730. */
  66731. get: function () {
  66732. return this._coneInnerAngle;
  66733. },
  66734. /**
  66735. * The size of cone in degress for a directional sound in which there will be no attenuation.
  66736. */
  66737. set: function (value) {
  66738. if (value !== this._coneInnerAngle) {
  66739. if (this._coneOuterAngle < value) {
  66740. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66741. return;
  66742. }
  66743. this._coneInnerAngle = value;
  66744. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66745. var sound = _a[_i];
  66746. sound.directionalConeInnerAngle = value;
  66747. }
  66748. }
  66749. },
  66750. enumerable: true,
  66751. configurable: true
  66752. });
  66753. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  66754. /**
  66755. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  66756. * Listener angles between innerAngle and outerAngle will falloff linearly.
  66757. */
  66758. get: function () {
  66759. return this._coneOuterAngle;
  66760. },
  66761. /**
  66762. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  66763. * Listener angles between innerAngle and outerAngle will falloff linearly.
  66764. */
  66765. set: function (value) {
  66766. if (value !== this._coneOuterAngle) {
  66767. if (value < this._coneInnerAngle) {
  66768. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66769. return;
  66770. }
  66771. this._coneOuterAngle = value;
  66772. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66773. var sound = _a[_i];
  66774. sound.directionalConeOuterAngle = value;
  66775. }
  66776. }
  66777. },
  66778. enumerable: true,
  66779. configurable: true
  66780. });
  66781. Object.defineProperty(WeightedSound.prototype, "volume", {
  66782. /**
  66783. * Playback volume.
  66784. */
  66785. get: function () {
  66786. return this._volume;
  66787. },
  66788. /**
  66789. * Playback volume.
  66790. */
  66791. set: function (value) {
  66792. if (value !== this._volume) {
  66793. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66794. var sound = _a[_i];
  66795. sound.setVolume(value);
  66796. }
  66797. }
  66798. },
  66799. enumerable: true,
  66800. configurable: true
  66801. });
  66802. WeightedSound.prototype._onended = function () {
  66803. if (this._currentIndex !== undefined) {
  66804. this._sounds[this._currentIndex].autoplay = false;
  66805. }
  66806. if (this.loop && this.isPlaying) {
  66807. this.play();
  66808. }
  66809. else {
  66810. this.isPlaying = false;
  66811. }
  66812. };
  66813. /**
  66814. * Suspend playback
  66815. */
  66816. WeightedSound.prototype.pause = function () {
  66817. this.isPaused = true;
  66818. if (this._currentIndex !== undefined) {
  66819. this._sounds[this._currentIndex].pause();
  66820. }
  66821. };
  66822. /**
  66823. * Stop playback
  66824. */
  66825. WeightedSound.prototype.stop = function () {
  66826. this.isPlaying = false;
  66827. if (this._currentIndex !== undefined) {
  66828. this._sounds[this._currentIndex].stop();
  66829. }
  66830. };
  66831. /**
  66832. * Start playback.
  66833. * @param startOffset Position the clip head at a specific time in seconds.
  66834. */
  66835. WeightedSound.prototype.play = function (startOffset) {
  66836. if (!this.isPaused) {
  66837. this.stop();
  66838. var randomValue = Math.random();
  66839. var total = 0;
  66840. for (var i = 0; i < this._weights.length; i++) {
  66841. total += this._weights[i];
  66842. if (randomValue <= total) {
  66843. this._currentIndex = i;
  66844. break;
  66845. }
  66846. }
  66847. }
  66848. var sound = this._sounds[this._currentIndex];
  66849. if (sound.isReady()) {
  66850. sound.play(0, this.isPaused ? undefined : startOffset);
  66851. }
  66852. else {
  66853. sound.autoplay = true;
  66854. }
  66855. this.isPlaying = true;
  66856. this.isPaused = false;
  66857. };
  66858. return WeightedSound;
  66859. }());
  66860. BABYLON.WeightedSound = WeightedSound;
  66861. })(BABYLON || (BABYLON = {}));
  66862. //# sourceMappingURL=babylon.weightedsound.js.map
  66863. var BABYLON;
  66864. (function (BABYLON) {
  66865. // Adds the parser to the scene parsers.
  66866. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  66867. // TODO: add sound
  66868. var loadedSounds = [];
  66869. var loadedSound;
  66870. container.sounds = container.sounds || [];
  66871. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  66872. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  66873. var parsedSound = parsedData.sounds[index];
  66874. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66875. if (!parsedSound.url)
  66876. parsedSound.url = parsedSound.name;
  66877. if (!loadedSounds[parsedSound.url]) {
  66878. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  66879. loadedSounds[parsedSound.url] = loadedSound;
  66880. container.sounds.push(loadedSound);
  66881. }
  66882. else {
  66883. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  66884. }
  66885. }
  66886. else {
  66887. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  66888. }
  66889. }
  66890. }
  66891. loadedSounds = [];
  66892. });
  66893. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  66894. get: function () {
  66895. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  66896. if (!compo) {
  66897. compo = new AudioSceneComponent(this);
  66898. this._addComponent(compo);
  66899. }
  66900. if (!this._mainSoundTrack) {
  66901. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  66902. }
  66903. return this._mainSoundTrack;
  66904. },
  66905. enumerable: true,
  66906. configurable: true
  66907. });
  66908. BABYLON.Scene.prototype.getSoundByName = function (name) {
  66909. var index;
  66910. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  66911. if (this.mainSoundTrack.soundCollection[index].name === name) {
  66912. return this.mainSoundTrack.soundCollection[index];
  66913. }
  66914. }
  66915. if (this.soundTracks) {
  66916. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  66917. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  66918. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  66919. return this.soundTracks[sdIndex].soundCollection[index];
  66920. }
  66921. }
  66922. }
  66923. }
  66924. return null;
  66925. };
  66926. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  66927. get: function () {
  66928. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  66929. if (!compo) {
  66930. compo = new AudioSceneComponent(this);
  66931. this._addComponent(compo);
  66932. }
  66933. return compo.audioEnabled;
  66934. },
  66935. set: function (value) {
  66936. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  66937. if (!compo) {
  66938. compo = new AudioSceneComponent(this);
  66939. this._addComponent(compo);
  66940. }
  66941. if (value) {
  66942. compo.enableAudio();
  66943. }
  66944. else {
  66945. compo.disableAudio();
  66946. }
  66947. },
  66948. enumerable: true,
  66949. configurable: true
  66950. });
  66951. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  66952. get: function () {
  66953. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  66954. if (!compo) {
  66955. compo = new AudioSceneComponent(this);
  66956. this._addComponent(compo);
  66957. }
  66958. return compo.headphone;
  66959. },
  66960. set: function (value) {
  66961. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  66962. if (!compo) {
  66963. compo = new AudioSceneComponent(this);
  66964. this._addComponent(compo);
  66965. }
  66966. if (value) {
  66967. compo.switchAudioModeForHeadphones();
  66968. }
  66969. else {
  66970. compo.switchAudioModeForNormalSpeakers();
  66971. }
  66972. },
  66973. enumerable: true,
  66974. configurable: true
  66975. });
  66976. /**
  66977. * Defines the sound scene component responsible to manage any sounds
  66978. * in a given scene.
  66979. */
  66980. var AudioSceneComponent = /** @class */ (function () {
  66981. /**
  66982. * Creates a new instance of the component for the given scene
  66983. * @param scene Defines the scene to register the component in
  66984. */
  66985. function AudioSceneComponent(scene) {
  66986. /**
  66987. * The component name helpfull to identify the component in the list of scene components.
  66988. */
  66989. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  66990. this._audioEnabled = true;
  66991. this._headphone = false;
  66992. this.scene = scene;
  66993. scene.soundTracks = new Array();
  66994. scene.sounds = new Array();
  66995. }
  66996. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  66997. /**
  66998. * Gets whether audio is enabled or not.
  66999. * Please use related enable/disable method to switch state.
  67000. */
  67001. get: function () {
  67002. return this._audioEnabled;
  67003. },
  67004. enumerable: true,
  67005. configurable: true
  67006. });
  67007. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  67008. /**
  67009. * Gets whether audio is outputing to headphone or not.
  67010. * Please use the according Switch methods to change output.
  67011. */
  67012. get: function () {
  67013. return this._headphone;
  67014. },
  67015. enumerable: true,
  67016. configurable: true
  67017. });
  67018. /**
  67019. * Registers the component in a given scene
  67020. */
  67021. AudioSceneComponent.prototype.register = function () {
  67022. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  67023. };
  67024. /**
  67025. * Rebuilds the elements related to this component in case of
  67026. * context lost for instance.
  67027. */
  67028. AudioSceneComponent.prototype.rebuild = function () {
  67029. // Nothing to do here. (Not rendering related)
  67030. };
  67031. /**
  67032. * Serializes the component data to the specified json object
  67033. * @param serializationObject The object to serialize to
  67034. */
  67035. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  67036. serializationObject.sounds = [];
  67037. if (this.scene.soundTracks) {
  67038. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  67039. var soundtrack = this.scene.soundTracks[index];
  67040. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  67041. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  67042. }
  67043. }
  67044. }
  67045. };
  67046. /**
  67047. * Adds all the element from the container to the scene
  67048. * @param container the container holding the elements
  67049. */
  67050. AudioSceneComponent.prototype.addFromContainer = function (container) {
  67051. var _this = this;
  67052. if (!container.sounds) {
  67053. return;
  67054. }
  67055. container.sounds.forEach(function (sound) {
  67056. sound.play();
  67057. sound.autoplay = true;
  67058. _this.scene.mainSoundTrack.AddSound(sound);
  67059. });
  67060. };
  67061. /**
  67062. * Removes all the elements in the container from the scene
  67063. * @param container contains the elements to remove
  67064. */
  67065. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  67066. var _this = this;
  67067. if (!container.sounds) {
  67068. return;
  67069. }
  67070. container.sounds.forEach(function (sound) {
  67071. sound.stop();
  67072. sound.autoplay = false;
  67073. _this.scene.mainSoundTrack.RemoveSound(sound);
  67074. });
  67075. };
  67076. /**
  67077. * Disposes the component and the associated ressources.
  67078. */
  67079. AudioSceneComponent.prototype.dispose = function () {
  67080. var scene = this.scene;
  67081. if (scene._mainSoundTrack) {
  67082. scene.mainSoundTrack.dispose();
  67083. }
  67084. if (scene.soundTracks) {
  67085. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  67086. scene.soundTracks[scIndex].dispose();
  67087. }
  67088. }
  67089. };
  67090. /**
  67091. * Disables audio in the associated scene.
  67092. */
  67093. AudioSceneComponent.prototype.disableAudio = function () {
  67094. var scene = this.scene;
  67095. this._audioEnabled = false;
  67096. var i;
  67097. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  67098. scene.mainSoundTrack.soundCollection[i].pause();
  67099. }
  67100. if (scene.soundTracks) {
  67101. for (i = 0; i < scene.soundTracks.length; i++) {
  67102. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  67103. scene.soundTracks[i].soundCollection[j].pause();
  67104. }
  67105. }
  67106. }
  67107. };
  67108. /**
  67109. * Enables audio in the associated scene.
  67110. */
  67111. AudioSceneComponent.prototype.enableAudio = function () {
  67112. var scene = this.scene;
  67113. this._audioEnabled = true;
  67114. var i;
  67115. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  67116. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  67117. scene.mainSoundTrack.soundCollection[i].play();
  67118. }
  67119. }
  67120. if (scene.soundTracks) {
  67121. for (i = 0; i < scene.soundTracks.length; i++) {
  67122. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  67123. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  67124. scene.soundTracks[i].soundCollection[j].play();
  67125. }
  67126. }
  67127. }
  67128. }
  67129. };
  67130. /**
  67131. * Switch audio to headphone output.
  67132. */
  67133. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  67134. var scene = this.scene;
  67135. this._headphone = true;
  67136. scene.mainSoundTrack.switchPanningModelToHRTF();
  67137. if (scene.soundTracks) {
  67138. for (var i = 0; i < scene.soundTracks.length; i++) {
  67139. scene.soundTracks[i].switchPanningModelToHRTF();
  67140. }
  67141. }
  67142. };
  67143. /**
  67144. * Switch audio to normal speakers.
  67145. */
  67146. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  67147. var scene = this.scene;
  67148. this._headphone = false;
  67149. scene.mainSoundTrack.switchPanningModelToEqualPower();
  67150. if (scene.soundTracks) {
  67151. for (var i = 0; i < scene.soundTracks.length; i++) {
  67152. scene.soundTracks[i].switchPanningModelToEqualPower();
  67153. }
  67154. }
  67155. };
  67156. AudioSceneComponent.prototype._afterRender = function () {
  67157. var scene = this.scene;
  67158. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  67159. return;
  67160. }
  67161. var listeningCamera;
  67162. var audioEngine = BABYLON.Engine.audioEngine;
  67163. if (scene.activeCameras.length > 0) {
  67164. listeningCamera = scene.activeCameras[0];
  67165. }
  67166. else {
  67167. listeningCamera = scene.activeCamera;
  67168. }
  67169. if (listeningCamera && audioEngine.audioContext) {
  67170. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  67171. // for VR cameras
  67172. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  67173. listeningCamera = listeningCamera.rigCameras[0];
  67174. }
  67175. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  67176. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  67177. cameraDirection.normalize();
  67178. // To avoid some errors on GearVR
  67179. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  67180. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  67181. }
  67182. var i;
  67183. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  67184. var sound = scene.mainSoundTrack.soundCollection[i];
  67185. if (sound.useCustomAttenuation) {
  67186. sound.updateDistanceFromListener();
  67187. }
  67188. }
  67189. if (scene.soundTracks) {
  67190. for (i = 0; i < scene.soundTracks.length; i++) {
  67191. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  67192. sound = scene.soundTracks[i].soundCollection[j];
  67193. if (sound.useCustomAttenuation) {
  67194. sound.updateDistanceFromListener();
  67195. }
  67196. }
  67197. }
  67198. }
  67199. }
  67200. };
  67201. return AudioSceneComponent;
  67202. }());
  67203. BABYLON.AudioSceneComponent = AudioSceneComponent;
  67204. })(BABYLON || (BABYLON = {}));
  67205. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  67206. var BABYLON;
  67207. (function (BABYLON) {
  67208. /**
  67209. * This defines an action helpful to play a defined sound on a triggered action.
  67210. */
  67211. var PlaySoundAction = /** @class */ (function (_super) {
  67212. __extends(PlaySoundAction, _super);
  67213. /**
  67214. * Instantiate the action
  67215. * @param triggerOptions defines the trigger options
  67216. * @param sound defines the sound to play
  67217. * @param condition defines the trigger related conditions
  67218. */
  67219. function PlaySoundAction(triggerOptions, sound, condition) {
  67220. var _this = _super.call(this, triggerOptions, condition) || this;
  67221. _this._sound = sound;
  67222. return _this;
  67223. }
  67224. /** @hidden */
  67225. PlaySoundAction.prototype._prepare = function () {
  67226. };
  67227. /**
  67228. * Execute the action and play the sound.
  67229. */
  67230. PlaySoundAction.prototype.execute = function () {
  67231. if (this._sound !== undefined)
  67232. this._sound.play();
  67233. };
  67234. /**
  67235. * Serializes the actions and its related information.
  67236. * @param parent defines the object to serialize in
  67237. * @returns the serialized object
  67238. */
  67239. PlaySoundAction.prototype.serialize = function (parent) {
  67240. return _super.prototype._serialize.call(this, {
  67241. name: "PlaySoundAction",
  67242. properties: [{ name: "sound", value: this._sound.name }]
  67243. }, parent);
  67244. };
  67245. return PlaySoundAction;
  67246. }(BABYLON.Action));
  67247. BABYLON.PlaySoundAction = PlaySoundAction;
  67248. /**
  67249. * This defines an action helpful to stop a defined sound on a triggered action.
  67250. */
  67251. var StopSoundAction = /** @class */ (function (_super) {
  67252. __extends(StopSoundAction, _super);
  67253. /**
  67254. * Instantiate the action
  67255. * @param triggerOptions defines the trigger options
  67256. * @param sound defines the sound to stop
  67257. * @param condition defines the trigger related conditions
  67258. */
  67259. function StopSoundAction(triggerOptions, sound, condition) {
  67260. var _this = _super.call(this, triggerOptions, condition) || this;
  67261. _this._sound = sound;
  67262. return _this;
  67263. }
  67264. /** @hidden */
  67265. StopSoundAction.prototype._prepare = function () {
  67266. };
  67267. /**
  67268. * Execute the action and stop the sound.
  67269. */
  67270. StopSoundAction.prototype.execute = function () {
  67271. if (this._sound !== undefined)
  67272. this._sound.stop();
  67273. };
  67274. /**
  67275. * Serializes the actions and its related information.
  67276. * @param parent defines the object to serialize in
  67277. * @returns the serialized object
  67278. */
  67279. StopSoundAction.prototype.serialize = function (parent) {
  67280. return _super.prototype._serialize.call(this, {
  67281. name: "StopSoundAction",
  67282. properties: [{ name: "sound", value: this._sound.name }]
  67283. }, parent);
  67284. };
  67285. return StopSoundAction;
  67286. }(BABYLON.Action));
  67287. BABYLON.StopSoundAction = StopSoundAction;
  67288. })(BABYLON || (BABYLON = {}));
  67289. //# sourceMappingURL=babylon.directAudioActions.js.map
  67290. var BABYLON;
  67291. (function (BABYLON) {
  67292. var CubeTexture = /** @class */ (function (_super) {
  67293. __extends(CubeTexture, _super);
  67294. /**
  67295. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  67296. * as prefiltered data.
  67297. * @param rootUrl defines the url of the texture or the root name of the six images
  67298. * @param scene defines the scene the texture is attached to
  67299. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  67300. * @param noMipmap defines if mipmaps should be created or not
  67301. * @param files defines the six files to load for the different faces
  67302. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  67303. * @param onError defines a callback triggered in case of error during load
  67304. * @param format defines the internal format to use for the texture once loaded
  67305. * @param prefiltered defines whether or not the texture is created from prefiltered data
  67306. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  67307. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  67308. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  67309. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  67310. * @return the cube texture
  67311. */
  67312. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  67313. if (extensions === void 0) { extensions = null; }
  67314. if (noMipmap === void 0) { noMipmap = false; }
  67315. if (files === void 0) { files = null; }
  67316. if (onLoad === void 0) { onLoad = null; }
  67317. if (onError === void 0) { onError = null; }
  67318. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67319. if (prefiltered === void 0) { prefiltered = false; }
  67320. if (forcedExtension === void 0) { forcedExtension = null; }
  67321. if (createPolynomials === void 0) { createPolynomials = false; }
  67322. if (lodScale === void 0) { lodScale = 0.8; }
  67323. if (lodOffset === void 0) { lodOffset = 0; }
  67324. var _this = _super.call(this, scene) || this;
  67325. /**
  67326. * Gets or sets the center of the bounding box associated with the cube texture
  67327. * It must define where the camera used to render the texture was set
  67328. */
  67329. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  67330. _this._rotationY = 0;
  67331. /** @hidden */
  67332. _this._prefiltered = false;
  67333. _this.name = rootUrl;
  67334. _this.url = rootUrl;
  67335. _this._noMipmap = noMipmap;
  67336. _this.hasAlpha = false;
  67337. _this._format = format;
  67338. _this.isCube = true;
  67339. _this._textureMatrix = BABYLON.Matrix.Identity();
  67340. _this._createPolynomials = createPolynomials;
  67341. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  67342. if (!rootUrl && !files) {
  67343. return _this;
  67344. }
  67345. var lastDot = rootUrl.lastIndexOf(".");
  67346. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  67347. var isDDS = (extension === ".dds");
  67348. var isEnv = (extension === ".env");
  67349. if (isEnv) {
  67350. _this.gammaSpace = false;
  67351. _this._prefiltered = false;
  67352. }
  67353. else {
  67354. _this._prefiltered = prefiltered;
  67355. if (prefiltered) {
  67356. _this.gammaSpace = false;
  67357. }
  67358. }
  67359. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  67360. if (!files) {
  67361. if (!isEnv && !isDDS && !extensions) {
  67362. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  67363. }
  67364. files = [];
  67365. if (extensions) {
  67366. for (var index = 0; index < extensions.length; index++) {
  67367. files.push(rootUrl + extensions[index]);
  67368. }
  67369. }
  67370. }
  67371. _this._files = files;
  67372. if (!_this._texture) {
  67373. if (!scene.useDelayedTextureLoading) {
  67374. if (prefiltered) {
  67375. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  67376. }
  67377. else {
  67378. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  67379. }
  67380. }
  67381. else {
  67382. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  67383. }
  67384. }
  67385. else if (onLoad) {
  67386. if (_this._texture.isReady) {
  67387. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  67388. }
  67389. else {
  67390. _this._texture.onLoadedObservable.add(onLoad);
  67391. }
  67392. }
  67393. return _this;
  67394. }
  67395. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  67396. get: function () {
  67397. return this._boundingBoxSize;
  67398. },
  67399. /**
  67400. * Gets or sets the size of the bounding box associated with the cube texture
  67401. * When defined, the cubemap will switch to local mode
  67402. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  67403. * @example https://www.babylonjs-playground.com/#RNASML
  67404. */
  67405. set: function (value) {
  67406. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  67407. return;
  67408. }
  67409. this._boundingBoxSize = value;
  67410. var scene = this.getScene();
  67411. if (scene) {
  67412. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  67413. }
  67414. },
  67415. enumerable: true,
  67416. configurable: true
  67417. });
  67418. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  67419. /**
  67420. * Gets texture matrix rotation angle around Y axis radians.
  67421. */
  67422. get: function () {
  67423. return this._rotationY;
  67424. },
  67425. /**
  67426. * Sets texture matrix rotation angle around Y axis in radians.
  67427. */
  67428. set: function (value) {
  67429. this._rotationY = value;
  67430. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  67431. },
  67432. enumerable: true,
  67433. configurable: true
  67434. });
  67435. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  67436. var rootUrlKey = "";
  67437. files.forEach(function (url) { return rootUrlKey += url; });
  67438. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  67439. };
  67440. /**
  67441. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  67442. * @param url defines the url of the prefiltered texture
  67443. * @param scene defines the scene the texture is attached to
  67444. * @param forcedExtension defines the extension of the file if different from the url
  67445. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  67446. * @return the prefiltered texture
  67447. */
  67448. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  67449. if (forcedExtension === void 0) { forcedExtension = null; }
  67450. if (createPolynomials === void 0) { createPolynomials = true; }
  67451. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  67452. };
  67453. // Methods
  67454. CubeTexture.prototype.delayLoad = function () {
  67455. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  67456. return;
  67457. }
  67458. var scene = this.getScene();
  67459. if (!scene) {
  67460. return;
  67461. }
  67462. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  67463. this._texture = this._getFromCache(this.url, this._noMipmap);
  67464. if (!this._texture) {
  67465. if (this._prefiltered) {
  67466. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  67467. }
  67468. else {
  67469. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  67470. }
  67471. }
  67472. };
  67473. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  67474. return this._textureMatrix;
  67475. };
  67476. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  67477. this._textureMatrix = value;
  67478. };
  67479. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  67480. var texture = BABYLON.SerializationHelper.Parse(function () {
  67481. var prefiltered = false;
  67482. if (parsedTexture.prefiltered) {
  67483. prefiltered = parsedTexture.prefiltered;
  67484. }
  67485. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  67486. }, parsedTexture, scene);
  67487. // Local Cubemaps
  67488. if (parsedTexture.boundingBoxPosition) {
  67489. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  67490. }
  67491. if (parsedTexture.boundingBoxSize) {
  67492. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  67493. }
  67494. // Animations
  67495. if (parsedTexture.animations) {
  67496. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  67497. var parsedAnimation = parsedTexture.animations[animationIndex];
  67498. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  67499. }
  67500. }
  67501. return texture;
  67502. };
  67503. CubeTexture.prototype.clone = function () {
  67504. var _this = this;
  67505. return BABYLON.SerializationHelper.Clone(function () {
  67506. var scene = _this.getScene();
  67507. if (!scene) {
  67508. return _this;
  67509. }
  67510. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  67511. }, this);
  67512. };
  67513. __decorate([
  67514. BABYLON.serialize("rotationY")
  67515. ], CubeTexture.prototype, "rotationY", null);
  67516. return CubeTexture;
  67517. }(BABYLON.BaseTexture));
  67518. BABYLON.CubeTexture = CubeTexture;
  67519. })(BABYLON || (BABYLON = {}));
  67520. //# sourceMappingURL=babylon.cubeTexture.js.map
  67521. var BABYLON;
  67522. (function (BABYLON) {
  67523. /**
  67524. * Raw cube texture where the raw buffers are passed in
  67525. */
  67526. var RawCubeTexture = /** @class */ (function (_super) {
  67527. __extends(RawCubeTexture, _super);
  67528. /**
  67529. * Creates a cube texture where the raw buffers are passed in.
  67530. * @param scene defines the scene the texture is attached to
  67531. * @param data defines the array of data to use to create each face
  67532. * @param size defines the size of the textures
  67533. * @param format defines the format of the data
  67534. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  67535. * @param generateMipMaps defines if the engine should generate the mip levels
  67536. * @param invertY defines if data must be stored with Y axis inverted
  67537. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  67538. * @param compression defines the compression used (null by default)
  67539. */
  67540. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  67541. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67542. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67543. if (generateMipMaps === void 0) { generateMipMaps = false; }
  67544. if (invertY === void 0) { invertY = false; }
  67545. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67546. if (compression === void 0) { compression = null; }
  67547. var _this = _super.call(this, "", scene) || this;
  67548. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  67549. return _this;
  67550. }
  67551. /**
  67552. * Updates the raw cube texture.
  67553. * @param data defines the data to store
  67554. * @param format defines the data format
  67555. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  67556. * @param invertY defines if data must be stored with Y axis inverted
  67557. * @param compression defines the compression used (null by default)
  67558. * @param level defines which level of the texture to update
  67559. */
  67560. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  67561. if (compression === void 0) { compression = null; }
  67562. if (level === void 0) { level = 0; }
  67563. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  67564. };
  67565. /**
  67566. * Updates a raw cube texture with RGBD encoded data.
  67567. * @param data defines the array of data [mipmap][face] to use to create each face
  67568. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  67569. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  67570. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  67571. * @returns a promsie that resolves when the operation is complete
  67572. */
  67573. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  67574. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  67575. if (lodScale === void 0) { lodScale = 0.8; }
  67576. if (lodOffset === void 0) { lodOffset = 0; }
  67577. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  67578. };
  67579. /**
  67580. * Clones the raw cube texture.
  67581. * @return a new cube texture
  67582. */
  67583. RawCubeTexture.prototype.clone = function () {
  67584. var _this = this;
  67585. return BABYLON.SerializationHelper.Clone(function () {
  67586. var scene = _this.getScene();
  67587. var internalTexture = _this._texture;
  67588. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  67589. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  67590. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  67591. }
  67592. return texture;
  67593. }, this);
  67594. };
  67595. /** @hidden */
  67596. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  67597. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  67598. internalTexture._bufferViewArrayArray = data;
  67599. internalTexture._lodGenerationScale = lodScale;
  67600. internalTexture._lodGenerationOffset = lodOffset;
  67601. internalTexture._sphericalPolynomial = sphericalPolynomial;
  67602. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  67603. internalTexture.isReady = true;
  67604. });
  67605. };
  67606. return RawCubeTexture;
  67607. }(BABYLON.CubeTexture));
  67608. BABYLON.RawCubeTexture = RawCubeTexture;
  67609. })(BABYLON || (BABYLON = {}));
  67610. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  67611. var BABYLON;
  67612. (function (BABYLON) {
  67613. var RenderTargetTexture = /** @class */ (function (_super) {
  67614. __extends(RenderTargetTexture, _super);
  67615. /**
  67616. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  67617. * or used a shadow, depth texture...
  67618. * @param name The friendly name of the texture
  67619. * @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)
  67620. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  67621. * @param generateMipMaps True if mip maps need to be generated after render.
  67622. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  67623. * @param type The type of the buffer in the RTT (int, half float, float...)
  67624. * @param isCube True if a cube texture needs to be created
  67625. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  67626. * @param generateDepthBuffer True to generate a depth buffer
  67627. * @param generateStencilBuffer True to generate a stencil buffer
  67628. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  67629. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  67630. */
  67631. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  67632. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  67633. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67634. if (isCube === void 0) { isCube = false; }
  67635. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67636. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  67637. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  67638. if (isMulti === void 0) { isMulti = false; }
  67639. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67640. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  67641. _this.isCube = isCube;
  67642. _this.renderParticles = true;
  67643. _this.renderSprites = false;
  67644. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  67645. _this.ignoreCameraViewport = false;
  67646. // Events
  67647. /**
  67648. * An event triggered when the texture is unbind.
  67649. */
  67650. _this.onBeforeBindObservable = new BABYLON.Observable();
  67651. /**
  67652. * An event triggered when the texture is unbind.
  67653. */
  67654. _this.onAfterUnbindObservable = new BABYLON.Observable();
  67655. /**
  67656. * An event triggered before rendering the texture
  67657. */
  67658. _this.onBeforeRenderObservable = new BABYLON.Observable();
  67659. /**
  67660. * An event triggered after rendering the texture
  67661. */
  67662. _this.onAfterRenderObservable = new BABYLON.Observable();
  67663. /**
  67664. * An event triggered after the texture clear
  67665. */
  67666. _this.onClearObservable = new BABYLON.Observable();
  67667. _this._currentRefreshId = -1;
  67668. _this._refreshRate = 1;
  67669. _this._samples = 1;
  67670. /**
  67671. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  67672. * It must define where the camera used to render the texture is set
  67673. */
  67674. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  67675. scene = _this.getScene();
  67676. if (!scene) {
  67677. return _this;
  67678. }
  67679. _this.renderList = new Array();
  67680. _this._engine = scene.getEngine();
  67681. _this.name = name;
  67682. _this.isRenderTarget = true;
  67683. _this._initialSizeParameter = size;
  67684. _this._processSizeParameter(size);
  67685. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  67686. });
  67687. _this._generateMipMaps = generateMipMaps ? true : false;
  67688. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  67689. // Rendering groups
  67690. _this._renderingManager = new BABYLON.RenderingManager(scene);
  67691. _this._renderingManager._useSceneAutoClearSetup = true;
  67692. if (isMulti) {
  67693. return _this;
  67694. }
  67695. _this._renderTargetOptions = {
  67696. generateMipMaps: generateMipMaps,
  67697. type: type,
  67698. format: format,
  67699. samplingMode: samplingMode,
  67700. generateDepthBuffer: generateDepthBuffer,
  67701. generateStencilBuffer: generateStencilBuffer
  67702. };
  67703. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  67704. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67705. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67706. }
  67707. if (isCube) {
  67708. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  67709. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  67710. _this._textureMatrix = BABYLON.Matrix.Identity();
  67711. }
  67712. else {
  67713. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  67714. }
  67715. return _this;
  67716. }
  67717. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  67718. get: function () {
  67719. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  67720. },
  67721. enumerable: true,
  67722. configurable: true
  67723. });
  67724. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  67725. get: function () {
  67726. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  67727. },
  67728. enumerable: true,
  67729. configurable: true
  67730. });
  67731. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  67732. get: function () {
  67733. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  67734. },
  67735. enumerable: true,
  67736. configurable: true
  67737. });
  67738. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  67739. /**
  67740. * Use this list to define the list of mesh you want to render.
  67741. */
  67742. get: function () {
  67743. return this._renderList;
  67744. },
  67745. set: function (value) {
  67746. this._renderList = value;
  67747. if (this._renderList) {
  67748. this._hookArray(this._renderList);
  67749. }
  67750. },
  67751. enumerable: true,
  67752. configurable: true
  67753. });
  67754. RenderTargetTexture.prototype._hookArray = function (array) {
  67755. var _this = this;
  67756. var oldPush = array.push;
  67757. array.push = function () {
  67758. var items = [];
  67759. for (var _i = 0; _i < arguments.length; _i++) {
  67760. items[_i] = arguments[_i];
  67761. }
  67762. var result = oldPush.apply(array, items);
  67763. _this.getScene().meshes.forEach(function (mesh) {
  67764. mesh._markSubMeshesAsLightDirty();
  67765. });
  67766. return result;
  67767. };
  67768. var oldSplice = array.splice;
  67769. array.splice = function (index, deleteCount) {
  67770. var deleted = oldSplice.apply(array, [index, deleteCount]);
  67771. _this.getScene().meshes.forEach(function (mesh) {
  67772. mesh._markSubMeshesAsLightDirty();
  67773. });
  67774. return deleted;
  67775. };
  67776. };
  67777. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  67778. set: function (callback) {
  67779. if (this._onAfterUnbindObserver) {
  67780. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  67781. }
  67782. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  67783. },
  67784. enumerable: true,
  67785. configurable: true
  67786. });
  67787. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  67788. set: function (callback) {
  67789. if (this._onBeforeRenderObserver) {
  67790. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  67791. }
  67792. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  67793. },
  67794. enumerable: true,
  67795. configurable: true
  67796. });
  67797. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  67798. set: function (callback) {
  67799. if (this._onAfterRenderObserver) {
  67800. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  67801. }
  67802. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  67803. },
  67804. enumerable: true,
  67805. configurable: true
  67806. });
  67807. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  67808. set: function (callback) {
  67809. if (this._onClearObserver) {
  67810. this.onClearObservable.remove(this._onClearObserver);
  67811. }
  67812. this._onClearObserver = this.onClearObservable.add(callback);
  67813. },
  67814. enumerable: true,
  67815. configurable: true
  67816. });
  67817. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  67818. get: function () {
  67819. return this._renderTargetOptions;
  67820. },
  67821. enumerable: true,
  67822. configurable: true
  67823. });
  67824. RenderTargetTexture.prototype._onRatioRescale = function () {
  67825. if (this._sizeRatio) {
  67826. this.resize(this._initialSizeParameter);
  67827. }
  67828. };
  67829. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  67830. get: function () {
  67831. return this._boundingBoxSize;
  67832. },
  67833. /**
  67834. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  67835. * When defined, the cubemap will switch to local mode
  67836. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  67837. * @example https://www.babylonjs-playground.com/#RNASML
  67838. */
  67839. set: function (value) {
  67840. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  67841. return;
  67842. }
  67843. this._boundingBoxSize = value;
  67844. var scene = this.getScene();
  67845. if (scene) {
  67846. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  67847. }
  67848. },
  67849. enumerable: true,
  67850. configurable: true
  67851. });
  67852. /**
  67853. * Creates a depth stencil texture.
  67854. * This is only available in WebGL 2 or with the depth texture extension available.
  67855. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  67856. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  67857. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  67858. */
  67859. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  67860. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  67861. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  67862. if (generateStencil === void 0) { generateStencil = false; }
  67863. if (!this.getScene()) {
  67864. return;
  67865. }
  67866. var engine = this.getScene().getEngine();
  67867. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  67868. bilinearFiltering: bilinearFiltering,
  67869. comparisonFunction: comparisonFunction,
  67870. generateStencil: generateStencil,
  67871. isCube: this.isCube
  67872. });
  67873. engine.setFrameBufferDepthStencilTexture(this);
  67874. };
  67875. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  67876. if (size.ratio) {
  67877. this._sizeRatio = size.ratio;
  67878. this._size = {
  67879. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  67880. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  67881. };
  67882. }
  67883. else {
  67884. this._size = size;
  67885. }
  67886. };
  67887. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  67888. get: function () {
  67889. return this._samples;
  67890. },
  67891. set: function (value) {
  67892. if (this._samples === value) {
  67893. return;
  67894. }
  67895. var scene = this.getScene();
  67896. if (!scene) {
  67897. return;
  67898. }
  67899. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  67900. },
  67901. enumerable: true,
  67902. configurable: true
  67903. });
  67904. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  67905. this._currentRefreshId = -1;
  67906. };
  67907. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  67908. get: function () {
  67909. return this._refreshRate;
  67910. },
  67911. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  67912. set: function (value) {
  67913. this._refreshRate = value;
  67914. this.resetRefreshCounter();
  67915. },
  67916. enumerable: true,
  67917. configurable: true
  67918. });
  67919. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  67920. if (!this._postProcessManager) {
  67921. var scene = this.getScene();
  67922. if (!scene) {
  67923. return;
  67924. }
  67925. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  67926. this._postProcesses = new Array();
  67927. }
  67928. this._postProcesses.push(postProcess);
  67929. this._postProcesses[0].autoClear = false;
  67930. };
  67931. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  67932. if (!this._postProcesses) {
  67933. return;
  67934. }
  67935. if (dispose) {
  67936. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  67937. var postProcess = _a[_i];
  67938. postProcess.dispose();
  67939. }
  67940. }
  67941. this._postProcesses = [];
  67942. };
  67943. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  67944. if (!this._postProcesses) {
  67945. return;
  67946. }
  67947. var index = this._postProcesses.indexOf(postProcess);
  67948. if (index === -1) {
  67949. return;
  67950. }
  67951. this._postProcesses.splice(index, 1);
  67952. if (this._postProcesses.length > 0) {
  67953. this._postProcesses[0].autoClear = false;
  67954. }
  67955. };
  67956. /** @hidden */
  67957. RenderTargetTexture.prototype._shouldRender = function () {
  67958. if (this._currentRefreshId === -1) { // At least render once
  67959. this._currentRefreshId = 1;
  67960. return true;
  67961. }
  67962. if (this.refreshRate === this._currentRefreshId) {
  67963. this._currentRefreshId = 1;
  67964. return true;
  67965. }
  67966. this._currentRefreshId++;
  67967. return false;
  67968. };
  67969. RenderTargetTexture.prototype.getRenderSize = function () {
  67970. if (this._size.width) {
  67971. return this._size.width;
  67972. }
  67973. return this._size;
  67974. };
  67975. RenderTargetTexture.prototype.getRenderWidth = function () {
  67976. if (this._size.width) {
  67977. return this._size.width;
  67978. }
  67979. return this._size;
  67980. };
  67981. RenderTargetTexture.prototype.getRenderHeight = function () {
  67982. if (this._size.width) {
  67983. return this._size.height;
  67984. }
  67985. return this._size;
  67986. };
  67987. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  67988. get: function () {
  67989. return true;
  67990. },
  67991. enumerable: true,
  67992. configurable: true
  67993. });
  67994. RenderTargetTexture.prototype.scale = function (ratio) {
  67995. var newSize = this.getRenderSize() * ratio;
  67996. this.resize(newSize);
  67997. };
  67998. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  67999. if (this.isCube) {
  68000. return this._textureMatrix;
  68001. }
  68002. return _super.prototype.getReflectionTextureMatrix.call(this);
  68003. };
  68004. RenderTargetTexture.prototype.resize = function (size) {
  68005. this.releaseInternalTexture();
  68006. var scene = this.getScene();
  68007. if (!scene) {
  68008. return;
  68009. }
  68010. this._processSizeParameter(size);
  68011. if (this.isCube) {
  68012. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  68013. }
  68014. else {
  68015. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  68016. }
  68017. };
  68018. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  68019. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  68020. if (dumpForDebug === void 0) { dumpForDebug = false; }
  68021. var scene = this.getScene();
  68022. if (!scene) {
  68023. return;
  68024. }
  68025. var engine = scene.getEngine();
  68026. if (this.useCameraPostProcesses !== undefined) {
  68027. useCameraPostProcess = this.useCameraPostProcesses;
  68028. }
  68029. if (this._waitingRenderList) {
  68030. this.renderList = [];
  68031. for (var index = 0; index < this._waitingRenderList.length; index++) {
  68032. var id = this._waitingRenderList[index];
  68033. var mesh_1 = scene.getMeshByID(id);
  68034. if (mesh_1) {
  68035. this.renderList.push(mesh_1);
  68036. }
  68037. }
  68038. delete this._waitingRenderList;
  68039. }
  68040. // Is predicate defined?
  68041. if (this.renderListPredicate) {
  68042. if (this.renderList) {
  68043. this.renderList.splice(0); // Clear previous renderList
  68044. }
  68045. else {
  68046. this.renderList = [];
  68047. }
  68048. var scene = this.getScene();
  68049. if (!scene) {
  68050. return;
  68051. }
  68052. var sceneMeshes = scene.meshes;
  68053. for (var index = 0; index < sceneMeshes.length; index++) {
  68054. var mesh = sceneMeshes[index];
  68055. if (this.renderListPredicate(mesh)) {
  68056. this.renderList.push(mesh);
  68057. }
  68058. }
  68059. }
  68060. this.onBeforeBindObservable.notifyObservers(this);
  68061. // Set custom projection.
  68062. // Needs to be before binding to prevent changing the aspect ratio.
  68063. var camera;
  68064. if (this.activeCamera) {
  68065. camera = this.activeCamera;
  68066. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  68067. if (this.activeCamera !== scene.activeCamera) {
  68068. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  68069. }
  68070. }
  68071. else {
  68072. camera = scene.activeCamera;
  68073. if (camera) {
  68074. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  68075. }
  68076. }
  68077. // Prepare renderingManager
  68078. this._renderingManager.reset();
  68079. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  68080. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  68081. var sceneRenderId = scene.getRenderId();
  68082. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  68083. var mesh = currentRenderList[meshIndex];
  68084. if (mesh) {
  68085. if (!mesh.isReady(this.refreshRate === 0)) {
  68086. this.resetRefreshCounter();
  68087. continue;
  68088. }
  68089. mesh._preActivateForIntermediateRendering(sceneRenderId);
  68090. var isMasked = void 0;
  68091. if (!this.renderList && camera) {
  68092. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  68093. }
  68094. else {
  68095. isMasked = false;
  68096. }
  68097. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  68098. mesh._activate(sceneRenderId);
  68099. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  68100. var subMesh = mesh.subMeshes[subIndex];
  68101. scene._activeIndices.addCount(subMesh.indexCount, false);
  68102. this._renderingManager.dispatch(subMesh, mesh);
  68103. }
  68104. }
  68105. }
  68106. }
  68107. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  68108. var particleSystem = scene.particleSystems[particleIndex];
  68109. var emitter = particleSystem.emitter;
  68110. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  68111. continue;
  68112. }
  68113. if (currentRenderList.indexOf(emitter) >= 0) {
  68114. this._renderingManager.dispatchParticles(particleSystem);
  68115. }
  68116. }
  68117. if (this.isCube) {
  68118. for (var face = 0; face < 6; face++) {
  68119. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  68120. scene.incrementRenderId();
  68121. scene.resetCachedMaterial();
  68122. }
  68123. }
  68124. else {
  68125. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  68126. }
  68127. this.onAfterUnbindObservable.notifyObservers(this);
  68128. if (scene.activeCamera) {
  68129. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  68130. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  68131. }
  68132. engine.setViewport(scene.activeCamera.viewport);
  68133. }
  68134. scene.resetCachedMaterial();
  68135. };
  68136. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  68137. var minimum = 128;
  68138. var x = renderDimension * scale;
  68139. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  68140. // Ensure we don't exceed the render dimension (while staying POT)
  68141. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  68142. };
  68143. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  68144. var _this = this;
  68145. if (!this._texture) {
  68146. return;
  68147. }
  68148. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  68149. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  68150. });
  68151. };
  68152. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  68153. var scene = this.getScene();
  68154. if (!scene) {
  68155. return;
  68156. }
  68157. var engine = scene.getEngine();
  68158. if (!this._texture) {
  68159. return;
  68160. }
  68161. // Bind
  68162. if (this._postProcessManager) {
  68163. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  68164. }
  68165. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  68166. if (this._texture) {
  68167. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  68168. }
  68169. }
  68170. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  68171. // Clear
  68172. if (this.onClearObservable.hasObservers()) {
  68173. this.onClearObservable.notifyObservers(engine);
  68174. }
  68175. else {
  68176. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  68177. }
  68178. if (!this._doNotChangeAspectRatio) {
  68179. scene.updateTransformMatrix(true);
  68180. }
  68181. // Render
  68182. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  68183. if (this._postProcessManager) {
  68184. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  68185. }
  68186. else if (useCameraPostProcess) {
  68187. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  68188. }
  68189. if (!this._doNotChangeAspectRatio) {
  68190. scene.updateTransformMatrix(true);
  68191. }
  68192. // Dump ?
  68193. if (dumpForDebug) {
  68194. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  68195. }
  68196. // Unbind
  68197. if (!this.isCube || faceIndex === 5) {
  68198. if (this.isCube) {
  68199. if (faceIndex === 5) {
  68200. engine.generateMipMapsForCubemap(this._texture);
  68201. }
  68202. }
  68203. this.unbindFrameBuffer(engine, faceIndex);
  68204. }
  68205. else {
  68206. this.onAfterRenderObservable.notifyObservers(faceIndex);
  68207. }
  68208. };
  68209. /**
  68210. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  68211. * This allowed control for front to back rendering or reversly depending of the special needs.
  68212. *
  68213. * @param renderingGroupId The rendering group id corresponding to its index
  68214. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  68215. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  68216. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  68217. */
  68218. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  68219. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  68220. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  68221. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  68222. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  68223. };
  68224. /**
  68225. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  68226. *
  68227. * @param renderingGroupId The rendering group id corresponding to its index
  68228. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  68229. */
  68230. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  68231. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  68232. this._renderingManager._useSceneAutoClearSetup = false;
  68233. };
  68234. RenderTargetTexture.prototype.clone = function () {
  68235. var textureSize = this.getSize();
  68236. 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);
  68237. // Base texture
  68238. newTexture.hasAlpha = this.hasAlpha;
  68239. newTexture.level = this.level;
  68240. // RenderTarget Texture
  68241. newTexture.coordinatesMode = this.coordinatesMode;
  68242. if (this.renderList) {
  68243. newTexture.renderList = this.renderList.slice(0);
  68244. }
  68245. return newTexture;
  68246. };
  68247. RenderTargetTexture.prototype.serialize = function () {
  68248. if (!this.name) {
  68249. return null;
  68250. }
  68251. var serializationObject = _super.prototype.serialize.call(this);
  68252. serializationObject.renderTargetSize = this.getRenderSize();
  68253. serializationObject.renderList = [];
  68254. if (this.renderList) {
  68255. for (var index = 0; index < this.renderList.length; index++) {
  68256. serializationObject.renderList.push(this.renderList[index].id);
  68257. }
  68258. }
  68259. return serializationObject;
  68260. };
  68261. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  68262. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  68263. var objBuffer = this.getInternalTexture();
  68264. var scene = this.getScene();
  68265. if (objBuffer && scene) {
  68266. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  68267. }
  68268. };
  68269. RenderTargetTexture.prototype.dispose = function () {
  68270. if (this._postProcessManager) {
  68271. this._postProcessManager.dispose();
  68272. this._postProcessManager = null;
  68273. }
  68274. this.clearPostProcesses(true);
  68275. if (this._resizeObserver) {
  68276. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  68277. this._resizeObserver = null;
  68278. }
  68279. this.renderList = null;
  68280. // Remove from custom render targets
  68281. var scene = this.getScene();
  68282. if (!scene) {
  68283. return;
  68284. }
  68285. var index = scene.customRenderTargets.indexOf(this);
  68286. if (index >= 0) {
  68287. scene.customRenderTargets.splice(index, 1);
  68288. }
  68289. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  68290. var camera = _a[_i];
  68291. index = camera.customRenderTargets.indexOf(this);
  68292. if (index >= 0) {
  68293. camera.customRenderTargets.splice(index, 1);
  68294. }
  68295. }
  68296. _super.prototype.dispose.call(this);
  68297. };
  68298. /** @hidden */
  68299. RenderTargetTexture.prototype._rebuild = function () {
  68300. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  68301. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  68302. }
  68303. if (this._postProcessManager) {
  68304. this._postProcessManager._rebuild();
  68305. }
  68306. };
  68307. /**
  68308. * Clear the info related to rendering groups preventing retention point in material dispose.
  68309. */
  68310. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  68311. if (this._renderingManager) {
  68312. this._renderingManager.freeRenderingGroups();
  68313. }
  68314. };
  68315. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  68316. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  68317. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  68318. return RenderTargetTexture;
  68319. }(BABYLON.Texture));
  68320. BABYLON.RenderTargetTexture = RenderTargetTexture;
  68321. })(BABYLON || (BABYLON = {}));
  68322. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  68323. var BABYLON;
  68324. (function (BABYLON) {
  68325. ;
  68326. var MultiRenderTarget = /** @class */ (function (_super) {
  68327. __extends(MultiRenderTarget, _super);
  68328. function MultiRenderTarget(name, size, count, scene, options) {
  68329. var _this = this;
  68330. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  68331. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  68332. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  68333. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  68334. _this._engine = scene.getEngine();
  68335. if (!_this.isSupported) {
  68336. _this.dispose();
  68337. return;
  68338. }
  68339. var types = [];
  68340. var samplingModes = [];
  68341. for (var i = 0; i < count; i++) {
  68342. if (options && options.types && options.types[i] !== undefined) {
  68343. types.push(options.types[i]);
  68344. }
  68345. else {
  68346. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68347. }
  68348. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  68349. samplingModes.push(options.samplingModes[i]);
  68350. }
  68351. else {
  68352. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68353. }
  68354. }
  68355. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  68356. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  68357. _this._size = size;
  68358. _this._multiRenderTargetOptions = {
  68359. samplingModes: samplingModes,
  68360. generateMipMaps: generateMipMaps,
  68361. generateDepthBuffer: generateDepthBuffer,
  68362. generateStencilBuffer: generateStencilBuffer,
  68363. generateDepthTexture: generateDepthTexture,
  68364. types: types,
  68365. textureCount: count
  68366. };
  68367. _this._createInternalTextures();
  68368. _this._createTextures();
  68369. return _this;
  68370. }
  68371. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  68372. get: function () {
  68373. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  68374. },
  68375. enumerable: true,
  68376. configurable: true
  68377. });
  68378. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  68379. get: function () {
  68380. return this._textures;
  68381. },
  68382. enumerable: true,
  68383. configurable: true
  68384. });
  68385. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  68386. get: function () {
  68387. return this._textures[this._textures.length - 1];
  68388. },
  68389. enumerable: true,
  68390. configurable: true
  68391. });
  68392. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  68393. set: function (wrap) {
  68394. if (this._textures) {
  68395. for (var i = 0; i < this._textures.length; i++) {
  68396. this._textures[i].wrapU = wrap;
  68397. }
  68398. }
  68399. },
  68400. enumerable: true,
  68401. configurable: true
  68402. });
  68403. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  68404. set: function (wrap) {
  68405. if (this._textures) {
  68406. for (var i = 0; i < this._textures.length; i++) {
  68407. this._textures[i].wrapV = wrap;
  68408. }
  68409. }
  68410. },
  68411. enumerable: true,
  68412. configurable: true
  68413. });
  68414. /** @hidden */
  68415. MultiRenderTarget.prototype._rebuild = function () {
  68416. this.releaseInternalTextures();
  68417. this._createInternalTextures();
  68418. for (var i = 0; i < this._internalTextures.length; i++) {
  68419. var texture = this._textures[i];
  68420. texture._texture = this._internalTextures[i];
  68421. }
  68422. // Keeps references to frame buffer and stencil/depth buffer
  68423. this._texture = this._internalTextures[0];
  68424. };
  68425. MultiRenderTarget.prototype._createInternalTextures = function () {
  68426. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  68427. };
  68428. MultiRenderTarget.prototype._createTextures = function () {
  68429. this._textures = [];
  68430. for (var i = 0; i < this._internalTextures.length; i++) {
  68431. var texture = new BABYLON.Texture(null, this.getScene());
  68432. texture._texture = this._internalTextures[i];
  68433. this._textures.push(texture);
  68434. }
  68435. // Keeps references to frame buffer and stencil/depth buffer
  68436. this._texture = this._internalTextures[0];
  68437. };
  68438. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  68439. get: function () {
  68440. return this._samples;
  68441. },
  68442. set: function (value) {
  68443. if (this._samples === value) {
  68444. return;
  68445. }
  68446. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  68447. },
  68448. enumerable: true,
  68449. configurable: true
  68450. });
  68451. MultiRenderTarget.prototype.resize = function (size) {
  68452. this.releaseInternalTextures();
  68453. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  68454. this._createInternalTextures();
  68455. };
  68456. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  68457. var _this = this;
  68458. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  68459. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  68460. });
  68461. };
  68462. MultiRenderTarget.prototype.dispose = function () {
  68463. this.releaseInternalTextures();
  68464. _super.prototype.dispose.call(this);
  68465. };
  68466. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  68467. if (!this._internalTextures) {
  68468. return;
  68469. }
  68470. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  68471. if (this._internalTextures[i] !== undefined) {
  68472. this._internalTextures[i].dispose();
  68473. this._internalTextures.splice(i, 1);
  68474. }
  68475. }
  68476. };
  68477. return MultiRenderTarget;
  68478. }(BABYLON.RenderTargetTexture));
  68479. BABYLON.MultiRenderTarget = MultiRenderTarget;
  68480. })(BABYLON || (BABYLON = {}));
  68481. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  68482. var BABYLON;
  68483. (function (BABYLON) {
  68484. var MirrorTexture = /** @class */ (function (_super) {
  68485. __extends(MirrorTexture, _super);
  68486. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  68487. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68488. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68489. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  68490. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  68491. _this.scene = scene;
  68492. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  68493. _this._transformMatrix = BABYLON.Matrix.Zero();
  68494. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  68495. _this._adaptiveBlurKernel = 0;
  68496. _this._blurKernelX = 0;
  68497. _this._blurKernelY = 0;
  68498. _this._blurRatio = 1.0;
  68499. _this.ignoreCameraViewport = true;
  68500. _this._updateGammaSpace();
  68501. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  68502. _this._updateGammaSpace;
  68503. });
  68504. _this.onBeforeRenderObservable.add(function () {
  68505. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  68506. _this._savedViewMatrix = scene.getViewMatrix();
  68507. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  68508. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  68509. scene.clipPlane = _this.mirrorPlane;
  68510. scene.getEngine().cullBackFaces = false;
  68511. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  68512. });
  68513. _this.onAfterRenderObservable.add(function () {
  68514. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  68515. scene.getEngine().cullBackFaces = true;
  68516. scene._mirroredCameraPosition = null;
  68517. delete scene.clipPlane;
  68518. });
  68519. return _this;
  68520. }
  68521. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  68522. get: function () {
  68523. return this._blurRatio;
  68524. },
  68525. set: function (value) {
  68526. if (this._blurRatio === value) {
  68527. return;
  68528. }
  68529. this._blurRatio = value;
  68530. this._preparePostProcesses();
  68531. },
  68532. enumerable: true,
  68533. configurable: true
  68534. });
  68535. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  68536. set: function (value) {
  68537. this._adaptiveBlurKernel = value;
  68538. this._autoComputeBlurKernel();
  68539. },
  68540. enumerable: true,
  68541. configurable: true
  68542. });
  68543. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  68544. set: function (value) {
  68545. this.blurKernelX = value;
  68546. this.blurKernelY = value;
  68547. },
  68548. enumerable: true,
  68549. configurable: true
  68550. });
  68551. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  68552. get: function () {
  68553. return this._blurKernelX;
  68554. },
  68555. set: function (value) {
  68556. if (this._blurKernelX === value) {
  68557. return;
  68558. }
  68559. this._blurKernelX = value;
  68560. this._preparePostProcesses();
  68561. },
  68562. enumerable: true,
  68563. configurable: true
  68564. });
  68565. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  68566. get: function () {
  68567. return this._blurKernelY;
  68568. },
  68569. set: function (value) {
  68570. if (this._blurKernelY === value) {
  68571. return;
  68572. }
  68573. this._blurKernelY = value;
  68574. this._preparePostProcesses();
  68575. },
  68576. enumerable: true,
  68577. configurable: true
  68578. });
  68579. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  68580. var engine = this.getScene().getEngine();
  68581. var dw = this.getRenderWidth() / engine.getRenderWidth();
  68582. var dh = this.getRenderHeight() / engine.getRenderHeight();
  68583. this.blurKernelX = this._adaptiveBlurKernel * dw;
  68584. this.blurKernelY = this._adaptiveBlurKernel * dh;
  68585. };
  68586. MirrorTexture.prototype._onRatioRescale = function () {
  68587. if (this._sizeRatio) {
  68588. this.resize(this._initialSizeParameter);
  68589. if (!this._adaptiveBlurKernel) {
  68590. this._preparePostProcesses();
  68591. }
  68592. }
  68593. if (this._adaptiveBlurKernel) {
  68594. this._autoComputeBlurKernel();
  68595. }
  68596. };
  68597. MirrorTexture.prototype._updateGammaSpace = function () {
  68598. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  68599. };
  68600. MirrorTexture.prototype._preparePostProcesses = function () {
  68601. this.clearPostProcesses(true);
  68602. if (this._blurKernelX && this._blurKernelY) {
  68603. var engine = this.getScene().getEngine();
  68604. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68605. 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);
  68606. this._blurX.autoClear = false;
  68607. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  68608. this._blurX.inputTexture = this._texture;
  68609. }
  68610. else {
  68611. this._blurX.alwaysForcePOT = true;
  68612. }
  68613. 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);
  68614. this._blurY.autoClear = false;
  68615. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  68616. this.addPostProcess(this._blurX);
  68617. this.addPostProcess(this._blurY);
  68618. }
  68619. else {
  68620. if (this._blurY) {
  68621. this.removePostProcess(this._blurY);
  68622. this._blurY.dispose();
  68623. this._blurY = null;
  68624. }
  68625. if (this._blurX) {
  68626. this.removePostProcess(this._blurX);
  68627. this._blurX.dispose();
  68628. this._blurX = null;
  68629. }
  68630. }
  68631. };
  68632. MirrorTexture.prototype.clone = function () {
  68633. var scene = this.getScene();
  68634. if (!scene) {
  68635. return this;
  68636. }
  68637. var textureSize = this.getSize();
  68638. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  68639. // Base texture
  68640. newTexture.hasAlpha = this.hasAlpha;
  68641. newTexture.level = this.level;
  68642. // Mirror Texture
  68643. newTexture.mirrorPlane = this.mirrorPlane.clone();
  68644. if (this.renderList) {
  68645. newTexture.renderList = this.renderList.slice(0);
  68646. }
  68647. return newTexture;
  68648. };
  68649. MirrorTexture.prototype.serialize = function () {
  68650. if (!this.name) {
  68651. return null;
  68652. }
  68653. var serializationObject = _super.prototype.serialize.call(this);
  68654. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  68655. return serializationObject;
  68656. };
  68657. MirrorTexture.prototype.dispose = function () {
  68658. _super.prototype.dispose.call(this);
  68659. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  68660. };
  68661. return MirrorTexture;
  68662. }(BABYLON.RenderTargetTexture));
  68663. BABYLON.MirrorTexture = MirrorTexture;
  68664. })(BABYLON || (BABYLON = {}));
  68665. //# sourceMappingURL=babylon.mirrorTexture.js.map
  68666. var BABYLON;
  68667. (function (BABYLON) {
  68668. /**
  68669. * Creates a refraction texture used by refraction channel of the standard material.
  68670. * @param name the texture name
  68671. * @param size size of the underlying texture
  68672. * @param scene root scene
  68673. */
  68674. var RefractionTexture = /** @class */ (function (_super) {
  68675. __extends(RefractionTexture, _super);
  68676. function RefractionTexture(name, size, scene, generateMipMaps) {
  68677. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  68678. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  68679. _this.depth = 2.0;
  68680. _this.onBeforeRenderObservable.add(function () {
  68681. scene.clipPlane = _this.refractionPlane;
  68682. });
  68683. _this.onAfterRenderObservable.add(function () {
  68684. delete scene.clipPlane;
  68685. });
  68686. return _this;
  68687. }
  68688. RefractionTexture.prototype.clone = function () {
  68689. var scene = this.getScene();
  68690. if (!scene) {
  68691. return this;
  68692. }
  68693. var textureSize = this.getSize();
  68694. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  68695. // Base texture
  68696. newTexture.hasAlpha = this.hasAlpha;
  68697. newTexture.level = this.level;
  68698. // Refraction Texture
  68699. newTexture.refractionPlane = this.refractionPlane.clone();
  68700. if (this.renderList) {
  68701. newTexture.renderList = this.renderList.slice(0);
  68702. }
  68703. newTexture.depth = this.depth;
  68704. return newTexture;
  68705. };
  68706. RefractionTexture.prototype.serialize = function () {
  68707. if (!this.name) {
  68708. return null;
  68709. }
  68710. var serializationObject = _super.prototype.serialize.call(this);
  68711. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  68712. serializationObject.depth = this.depth;
  68713. return serializationObject;
  68714. };
  68715. return RefractionTexture;
  68716. }(BABYLON.RenderTargetTexture));
  68717. BABYLON.RefractionTexture = RefractionTexture;
  68718. })(BABYLON || (BABYLON = {}));
  68719. //# sourceMappingURL=babylon.refractionTexture.js.map
  68720. var BABYLON;
  68721. (function (BABYLON) {
  68722. /**
  68723. * A class extending {BABYLON.Texture} allowing drawing on a texture
  68724. * @see http://doc.babylonjs.com/how_to/dynamictexture
  68725. */
  68726. var DynamicTexture = /** @class */ (function (_super) {
  68727. __extends(DynamicTexture, _super);
  68728. /**
  68729. * Creates a {BABYLON.DynamicTexture}
  68730. * @param name defines the name of the texture
  68731. * @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
  68732. * @param scene defines the scene where you want the texture
  68733. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  68734. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  68735. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  68736. */
  68737. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  68738. if (scene === void 0) { scene = null; }
  68739. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68740. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  68741. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  68742. _this.name = name;
  68743. _this._engine = _this.getScene().getEngine();
  68744. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68745. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68746. _this._generateMipMaps = generateMipMaps;
  68747. if (options.getContext) {
  68748. _this._canvas = options;
  68749. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  68750. }
  68751. else {
  68752. _this._canvas = document.createElement("canvas");
  68753. if (options.width || options.width === 0) {
  68754. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  68755. }
  68756. else {
  68757. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  68758. }
  68759. }
  68760. var textureSize = _this.getSize();
  68761. _this._canvas.width = textureSize.width;
  68762. _this._canvas.height = textureSize.height;
  68763. _this._context = _this._canvas.getContext("2d");
  68764. return _this;
  68765. }
  68766. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  68767. /**
  68768. * Gets the current state of canRescale
  68769. */
  68770. get: function () {
  68771. return true;
  68772. },
  68773. enumerable: true,
  68774. configurable: true
  68775. });
  68776. DynamicTexture.prototype._recreate = function (textureSize) {
  68777. this._canvas.width = textureSize.width;
  68778. this._canvas.height = textureSize.height;
  68779. this.releaseInternalTexture();
  68780. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  68781. };
  68782. /**
  68783. * Scales the texture
  68784. * @param ratio the scale factor to apply to both width and height
  68785. */
  68786. DynamicTexture.prototype.scale = function (ratio) {
  68787. var textureSize = this.getSize();
  68788. textureSize.width *= ratio;
  68789. textureSize.height *= ratio;
  68790. this._recreate(textureSize);
  68791. };
  68792. /**
  68793. * Resizes the texture
  68794. * @param width the new width
  68795. * @param height the new height
  68796. */
  68797. DynamicTexture.prototype.scaleTo = function (width, height) {
  68798. var textureSize = this.getSize();
  68799. textureSize.width = width;
  68800. textureSize.height = height;
  68801. this._recreate(textureSize);
  68802. };
  68803. /**
  68804. * Gets the context of the canvas used by the texture
  68805. * @returns the canvas context of the dynamic texture
  68806. */
  68807. DynamicTexture.prototype.getContext = function () {
  68808. return this._context;
  68809. };
  68810. /**
  68811. * Clears the texture
  68812. */
  68813. DynamicTexture.prototype.clear = function () {
  68814. var size = this.getSize();
  68815. this._context.fillRect(0, 0, size.width, size.height);
  68816. };
  68817. /**
  68818. * Updates the texture
  68819. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  68820. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  68821. */
  68822. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  68823. if (premulAlpha === void 0) { premulAlpha = false; }
  68824. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  68825. };
  68826. /**
  68827. * Draws text onto the texture
  68828. * @param text defines the text to be drawn
  68829. * @param x defines the placement of the text from the left
  68830. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  68831. * @param font defines the font to be used with font-style, font-size, font-name
  68832. * @param color defines the color used for the text
  68833. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  68834. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  68835. * @param update defines whether texture is immediately update (default is true)
  68836. */
  68837. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  68838. if (update === void 0) { update = true; }
  68839. var size = this.getSize();
  68840. if (clearColor) {
  68841. this._context.fillStyle = clearColor;
  68842. this._context.fillRect(0, 0, size.width, size.height);
  68843. }
  68844. this._context.font = font;
  68845. if (x === null || x === undefined) {
  68846. var textSize = this._context.measureText(text);
  68847. x = (size.width - textSize.width) / 2;
  68848. }
  68849. if (y === null || y === undefined) {
  68850. var fontSize = parseInt((font.replace(/\D/g, '')));
  68851. y = (size.height / 2) + (fontSize / 3.65);
  68852. }
  68853. this._context.fillStyle = color;
  68854. this._context.fillText(text, x, y);
  68855. if (update) {
  68856. this.update(invertY);
  68857. }
  68858. };
  68859. /**
  68860. * Clones the texture
  68861. * @returns the clone of the texture.
  68862. */
  68863. DynamicTexture.prototype.clone = function () {
  68864. var scene = this.getScene();
  68865. if (!scene) {
  68866. return this;
  68867. }
  68868. var textureSize = this.getSize();
  68869. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  68870. // Base texture
  68871. newTexture.hasAlpha = this.hasAlpha;
  68872. newTexture.level = this.level;
  68873. // Dynamic Texture
  68874. newTexture.wrapU = this.wrapU;
  68875. newTexture.wrapV = this.wrapV;
  68876. return newTexture;
  68877. };
  68878. /**
  68879. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  68880. * @returns a serialized dynamic texture object
  68881. */
  68882. DynamicTexture.prototype.serialize = function () {
  68883. var scene = this.getScene();
  68884. if (scene && !scene.isReady()) {
  68885. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  68886. }
  68887. var serializationObject = _super.prototype.serialize.call(this);
  68888. serializationObject.base64String = this._canvas.toDataURL();
  68889. serializationObject.invertY = this._invertY;
  68890. serializationObject.samplingMode = this.samplingMode;
  68891. return serializationObject;
  68892. };
  68893. /** @hidden */
  68894. DynamicTexture.prototype._rebuild = function () {
  68895. this.update();
  68896. };
  68897. return DynamicTexture;
  68898. }(BABYLON.Texture));
  68899. BABYLON.DynamicTexture = DynamicTexture;
  68900. })(BABYLON || (BABYLON = {}));
  68901. //# sourceMappingURL=babylon.dynamicTexture.js.map
  68902. var BABYLON;
  68903. (function (BABYLON) {
  68904. var VideoTexture = /** @class */ (function (_super) {
  68905. __extends(VideoTexture, _super);
  68906. /**
  68907. * Creates a video texture.
  68908. * Sample : https://doc.babylonjs.com/how_to/video_texture
  68909. * @param {string | null} name optional name, will detect from video source, if not defined
  68910. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  68911. * @param {BABYLON.Scene} scene is obviously the current scene.
  68912. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  68913. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  68914. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  68915. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  68916. */
  68917. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  68918. if (generateMipMaps === void 0) { generateMipMaps = false; }
  68919. if (invertY === void 0) { invertY = false; }
  68920. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68921. if (settings === void 0) { settings = {
  68922. autoPlay: true,
  68923. loop: true,
  68924. autoUpdateTexture: true,
  68925. }; }
  68926. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68927. _this._onUserActionRequestedObservable = null;
  68928. _this._stillImageCaptured = false;
  68929. _this._poster = false;
  68930. _this._createInternalTexture = function () {
  68931. if (_this._texture != null) {
  68932. if (_this._poster) {
  68933. _this._texture.dispose();
  68934. _this._poster = false;
  68935. }
  68936. else {
  68937. return;
  68938. }
  68939. }
  68940. if (!_this._engine.needPOTTextures ||
  68941. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  68942. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68943. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68944. }
  68945. else {
  68946. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68947. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68948. _this._generateMipMaps = false;
  68949. }
  68950. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  68951. if (!_this.video.autoplay) {
  68952. var oldHandler_1 = _this.video.onplaying;
  68953. var error_1 = false;
  68954. _this.video.onplaying = function () {
  68955. _this.video.onplaying = oldHandler_1;
  68956. _this._texture.isReady = true;
  68957. _this._updateInternalTexture();
  68958. if (!error_1) {
  68959. _this.video.pause();
  68960. }
  68961. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68962. _this.onLoadObservable.notifyObservers(_this);
  68963. }
  68964. };
  68965. var playing = _this.video.play();
  68966. if (playing) {
  68967. playing.then(function () {
  68968. // Everything is good.
  68969. })
  68970. .catch(function () {
  68971. error_1 = true;
  68972. // On Chrome for instance, new policies might prevent playing without user interaction.
  68973. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  68974. _this._onUserActionRequestedObservable.notifyObservers(_this);
  68975. }
  68976. });
  68977. }
  68978. else {
  68979. _this.video.onplaying = oldHandler_1;
  68980. _this._texture.isReady = true;
  68981. _this._updateInternalTexture();
  68982. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68983. _this.onLoadObservable.notifyObservers(_this);
  68984. }
  68985. }
  68986. }
  68987. else {
  68988. _this._texture.isReady = true;
  68989. _this._updateInternalTexture();
  68990. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68991. _this.onLoadObservable.notifyObservers(_this);
  68992. }
  68993. }
  68994. };
  68995. _this.reset = function () {
  68996. if (_this._texture == null) {
  68997. return;
  68998. }
  68999. if (!_this._poster) {
  69000. _this._texture.dispose();
  69001. _this._texture = null;
  69002. }
  69003. };
  69004. _this._updateInternalTexture = function (e) {
  69005. if (_this._texture == null || !_this._texture.isReady) {
  69006. return;
  69007. }
  69008. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  69009. return;
  69010. }
  69011. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  69012. };
  69013. _this._engine = _this.getScene().getEngine();
  69014. _this._generateMipMaps = generateMipMaps;
  69015. _this._samplingMode = samplingMode;
  69016. _this.autoUpdateTexture = settings.autoUpdateTexture;
  69017. _this.name = name || _this._getName(src);
  69018. _this.video = _this._getVideo(src);
  69019. if (settings.poster) {
  69020. _this.video.poster = settings.poster;
  69021. }
  69022. if (settings.autoPlay !== undefined) {
  69023. _this.video.autoplay = settings.autoPlay;
  69024. }
  69025. if (settings.loop !== undefined) {
  69026. _this.video.loop = settings.loop;
  69027. }
  69028. _this.video.setAttribute("playsinline", "");
  69029. _this.video.addEventListener("canplay", _this._createInternalTexture);
  69030. _this.video.addEventListener("paused", _this._updateInternalTexture);
  69031. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  69032. _this.video.addEventListener("emptied", _this.reset);
  69033. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  69034. _this._createInternalTexture();
  69035. }
  69036. if (settings.poster) {
  69037. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  69038. _this._poster = true;
  69039. }
  69040. return _this;
  69041. }
  69042. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  69043. get: function () {
  69044. if (!this._onUserActionRequestedObservable) {
  69045. this._onUserActionRequestedObservable = new BABYLON.Observable();
  69046. }
  69047. return this._onUserActionRequestedObservable;
  69048. },
  69049. enumerable: true,
  69050. configurable: true
  69051. });
  69052. VideoTexture.prototype._getName = function (src) {
  69053. if (src instanceof HTMLVideoElement) {
  69054. return src.currentSrc;
  69055. }
  69056. if (typeof src === "object") {
  69057. return src.toString();
  69058. }
  69059. return src;
  69060. };
  69061. ;
  69062. VideoTexture.prototype._getVideo = function (src) {
  69063. if (src instanceof HTMLVideoElement) {
  69064. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  69065. return src;
  69066. }
  69067. var video = document.createElement("video");
  69068. if (typeof src === "string") {
  69069. BABYLON.Tools.SetCorsBehavior(src, video);
  69070. video.src = src;
  69071. }
  69072. else {
  69073. BABYLON.Tools.SetCorsBehavior(src[0], video);
  69074. src.forEach(function (url) {
  69075. var source = document.createElement("source");
  69076. source.src = url;
  69077. video.appendChild(source);
  69078. });
  69079. }
  69080. return video;
  69081. };
  69082. ;
  69083. /**
  69084. * @hidden Internal method to initiate `update`.
  69085. */
  69086. VideoTexture.prototype._rebuild = function () {
  69087. this.update();
  69088. };
  69089. /**
  69090. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  69091. */
  69092. VideoTexture.prototype.update = function () {
  69093. if (!this.autoUpdateTexture) {
  69094. // Expecting user to call `updateTexture` manually
  69095. return;
  69096. }
  69097. this.updateTexture(true);
  69098. };
  69099. /**
  69100. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  69101. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  69102. */
  69103. VideoTexture.prototype.updateTexture = function (isVisible) {
  69104. if (!isVisible) {
  69105. return;
  69106. }
  69107. if (this.video.paused && this._stillImageCaptured) {
  69108. return;
  69109. }
  69110. this._stillImageCaptured = true;
  69111. this._updateInternalTexture();
  69112. };
  69113. /**
  69114. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  69115. * @param url New url.
  69116. */
  69117. VideoTexture.prototype.updateURL = function (url) {
  69118. this.video.src = url;
  69119. };
  69120. VideoTexture.prototype.dispose = function () {
  69121. _super.prototype.dispose.call(this);
  69122. if (this._onUserActionRequestedObservable) {
  69123. this._onUserActionRequestedObservable.clear();
  69124. this._onUserActionRequestedObservable = null;
  69125. }
  69126. this.video.removeEventListener("canplay", this._createInternalTexture);
  69127. this.video.removeEventListener("paused", this._updateInternalTexture);
  69128. this.video.removeEventListener("seeked", this._updateInternalTexture);
  69129. this.video.removeEventListener("emptied", this.reset);
  69130. this.video.pause();
  69131. };
  69132. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  69133. var video = document.createElement("video");
  69134. video.setAttribute('autoplay', '');
  69135. video.setAttribute('muted', '');
  69136. video.setAttribute('playsinline', '');
  69137. var constraintsDeviceId;
  69138. if (constraints && constraints.deviceId) {
  69139. constraintsDeviceId = {
  69140. exact: constraints.deviceId,
  69141. };
  69142. }
  69143. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  69144. if (navigator.mediaDevices) {
  69145. navigator.mediaDevices.getUserMedia({ video: constraints })
  69146. .then(function (stream) {
  69147. if (video.mozSrcObject !== undefined) {
  69148. // hack for Firefox < 19
  69149. video.mozSrcObject = stream;
  69150. }
  69151. else {
  69152. video.srcObject = stream;
  69153. }
  69154. var onPlaying = function () {
  69155. if (onReady) {
  69156. onReady(new VideoTexture("video", video, scene, true, true));
  69157. }
  69158. video.removeEventListener("playing", onPlaying);
  69159. };
  69160. video.addEventListener("playing", onPlaying);
  69161. video.play();
  69162. })
  69163. .catch(function (err) {
  69164. BABYLON.Tools.Error(err.name);
  69165. });
  69166. }
  69167. else {
  69168. navigator.getUserMedia =
  69169. navigator.getUserMedia ||
  69170. navigator.webkitGetUserMedia ||
  69171. navigator.mozGetUserMedia ||
  69172. navigator.msGetUserMedia;
  69173. if (navigator.getUserMedia) {
  69174. navigator.getUserMedia({
  69175. video: {
  69176. deviceId: constraintsDeviceId,
  69177. width: {
  69178. min: (constraints && constraints.minWidth) || 256,
  69179. max: (constraints && constraints.maxWidth) || 640,
  69180. },
  69181. height: {
  69182. min: (constraints && constraints.minHeight) || 256,
  69183. max: (constraints && constraints.maxHeight) || 480,
  69184. },
  69185. },
  69186. }, function (stream) {
  69187. if (video.mozSrcObject !== undefined) {
  69188. // hack for Firefox < 19
  69189. video.mozSrcObject = stream;
  69190. }
  69191. else {
  69192. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  69193. }
  69194. video.play();
  69195. if (onReady) {
  69196. onReady(new VideoTexture("video", video, scene, true, true));
  69197. }
  69198. }, function (e) {
  69199. BABYLON.Tools.Error(e.name);
  69200. });
  69201. }
  69202. }
  69203. };
  69204. return VideoTexture;
  69205. }(BABYLON.Texture));
  69206. BABYLON.VideoTexture = VideoTexture;
  69207. })(BABYLON || (BABYLON = {}));
  69208. //# sourceMappingURL=babylon.videoTexture.js.map
  69209. var BABYLON;
  69210. (function (BABYLON) {
  69211. var RawTexture = /** @class */ (function (_super) {
  69212. __extends(RawTexture, _super);
  69213. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  69214. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69215. if (invertY === void 0) { invertY = false; }
  69216. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69217. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69218. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  69219. _this.format = format;
  69220. _this._engine = scene.getEngine();
  69221. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  69222. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69223. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69224. return _this;
  69225. }
  69226. RawTexture.prototype.update = function (data) {
  69227. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  69228. };
  69229. // Statics
  69230. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  69231. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69232. if (invertY === void 0) { invertY = false; }
  69233. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69234. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  69235. };
  69236. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  69237. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69238. if (invertY === void 0) { invertY = false; }
  69239. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69240. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  69241. };
  69242. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  69243. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69244. if (invertY === void 0) { invertY = false; }
  69245. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69246. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  69247. };
  69248. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  69249. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69250. if (invertY === void 0) { invertY = false; }
  69251. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69252. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69253. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  69254. };
  69255. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  69256. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69257. if (invertY === void 0) { invertY = false; }
  69258. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69259. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69260. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  69261. };
  69262. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  69263. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69264. if (invertY === void 0) { invertY = false; }
  69265. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69266. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  69267. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  69268. };
  69269. return RawTexture;
  69270. }(BABYLON.Texture));
  69271. BABYLON.RawTexture = RawTexture;
  69272. })(BABYLON || (BABYLON = {}));
  69273. //# sourceMappingURL=babylon.rawTexture.js.map
  69274. var BABYLON;
  69275. (function (BABYLON) {
  69276. /**
  69277. * Class used to store 3D textures containing user data
  69278. */
  69279. var RawTexture3D = /** @class */ (function (_super) {
  69280. __extends(RawTexture3D, _super);
  69281. /**
  69282. * Create a new RawTexture3D
  69283. * @param data defines the data of the texture
  69284. * @param width defines the width of the texture
  69285. * @param height defines the height of the texture
  69286. * @param depth defines the depth of the texture
  69287. * @param format defines the texture format to use
  69288. * @param scene defines the hosting scene
  69289. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  69290. * @param invertY defines if texture must be stored with Y axis inverted
  69291. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  69292. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  69293. */
  69294. function RawTexture3D(data, width, height, depth,
  69295. /** Gets or sets the texture format to use */
  69296. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  69297. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69298. if (invertY === void 0) { invertY = false; }
  69299. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69300. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69301. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  69302. _this.format = format;
  69303. _this._engine = scene.getEngine();
  69304. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  69305. _this.is3D = true;
  69306. return _this;
  69307. }
  69308. /**
  69309. * Update the texture with new data
  69310. * @param data defines the data to store in the texture
  69311. */
  69312. RawTexture3D.prototype.update = function (data) {
  69313. if (!this._texture) {
  69314. return;
  69315. }
  69316. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  69317. };
  69318. return RawTexture3D;
  69319. }(BABYLON.Texture));
  69320. BABYLON.RawTexture3D = RawTexture3D;
  69321. })(BABYLON || (BABYLON = {}));
  69322. //# sourceMappingURL=babylon.rawTexture3D.js.map
  69323. var BABYLON;
  69324. (function (BABYLON) {
  69325. /**
  69326. * PostProcessManager is used to manage one or more post processes or post process pipelines
  69327. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  69328. */
  69329. var PostProcessManager = /** @class */ (function () {
  69330. /**
  69331. * Creates a new instance PostProcess
  69332. * @param scene The scene that the post process is associated with.
  69333. */
  69334. function PostProcessManager(scene) {
  69335. this._vertexBuffers = {};
  69336. this._scene = scene;
  69337. }
  69338. PostProcessManager.prototype._prepareBuffers = function () {
  69339. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  69340. return;
  69341. }
  69342. // VBO
  69343. var vertices = [];
  69344. vertices.push(1, 1);
  69345. vertices.push(-1, 1);
  69346. vertices.push(-1, -1);
  69347. vertices.push(1, -1);
  69348. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69349. this._buildIndexBuffer();
  69350. };
  69351. PostProcessManager.prototype._buildIndexBuffer = function () {
  69352. // Indices
  69353. var indices = [];
  69354. indices.push(0);
  69355. indices.push(1);
  69356. indices.push(2);
  69357. indices.push(0);
  69358. indices.push(2);
  69359. indices.push(3);
  69360. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  69361. };
  69362. /**
  69363. * Rebuilds the vertex buffers of the manager.
  69364. * @hidden
  69365. */
  69366. PostProcessManager.prototype._rebuild = function () {
  69367. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69368. if (!vb) {
  69369. return;
  69370. }
  69371. vb._rebuild();
  69372. this._buildIndexBuffer();
  69373. };
  69374. // Methods
  69375. /**
  69376. * Prepares a frame to be run through a post process.
  69377. * @param sourceTexture The input texture to the post procesess. (default: null)
  69378. * @param postProcesses An array of post processes to be run. (default: null)
  69379. * @returns True if the post processes were able to be run.
  69380. * @hidden
  69381. */
  69382. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  69383. if (sourceTexture === void 0) { sourceTexture = null; }
  69384. if (postProcesses === void 0) { postProcesses = null; }
  69385. var camera = this._scene.activeCamera;
  69386. if (!camera) {
  69387. return false;
  69388. }
  69389. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  69390. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  69391. return false;
  69392. }
  69393. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  69394. return true;
  69395. };
  69396. /**
  69397. * Manually render a set of post processes to a texture.
  69398. * @param postProcesses An array of post processes to be run.
  69399. * @param targetTexture The target texture to render to.
  69400. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  69401. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  69402. * @param lodLevel defines which lod of the texture to render to
  69403. */
  69404. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  69405. if (targetTexture === void 0) { targetTexture = null; }
  69406. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  69407. if (faceIndex === void 0) { faceIndex = 0; }
  69408. if (lodLevel === void 0) { lodLevel = 0; }
  69409. var engine = this._scene.getEngine();
  69410. for (var index = 0; index < postProcesses.length; index++) {
  69411. if (index < postProcesses.length - 1) {
  69412. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  69413. }
  69414. else {
  69415. if (targetTexture) {
  69416. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  69417. }
  69418. else {
  69419. engine.restoreDefaultFramebuffer();
  69420. }
  69421. }
  69422. var pp = postProcesses[index];
  69423. var effect = pp.apply();
  69424. if (effect) {
  69425. pp.onBeforeRenderObservable.notifyObservers(effect);
  69426. // VBOs
  69427. this._prepareBuffers();
  69428. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  69429. // Draw order
  69430. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69431. pp.onAfterRenderObservable.notifyObservers(effect);
  69432. }
  69433. }
  69434. // Restore depth buffer
  69435. engine.setDepthBuffer(true);
  69436. engine.setDepthWrite(true);
  69437. };
  69438. /**
  69439. * Finalize the result of the output of the postprocesses.
  69440. * @param doNotPresent If true the result will not be displayed to the screen.
  69441. * @param targetTexture The target texture to render to.
  69442. * @param faceIndex The index of the face to bind the target texture to.
  69443. * @param postProcesses The array of post processes to render.
  69444. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  69445. * @hidden
  69446. */
  69447. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  69448. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  69449. var camera = this._scene.activeCamera;
  69450. if (!camera) {
  69451. return;
  69452. }
  69453. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  69454. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  69455. return;
  69456. }
  69457. var engine = this._scene.getEngine();
  69458. for (var index = 0, len = postProcesses.length; index < len; index++) {
  69459. var pp = postProcesses[index];
  69460. if (index < len - 1) {
  69461. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  69462. }
  69463. else {
  69464. if (targetTexture) {
  69465. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  69466. pp._outputTexture = targetTexture;
  69467. }
  69468. else {
  69469. engine.restoreDefaultFramebuffer();
  69470. pp._outputTexture = null;
  69471. }
  69472. }
  69473. if (doNotPresent) {
  69474. break;
  69475. }
  69476. var effect = pp.apply();
  69477. if (effect) {
  69478. pp.onBeforeRenderObservable.notifyObservers(effect);
  69479. // VBOs
  69480. this._prepareBuffers();
  69481. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  69482. // Draw order
  69483. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69484. pp.onAfterRenderObservable.notifyObservers(effect);
  69485. }
  69486. }
  69487. // Restore states
  69488. engine.setDepthBuffer(true);
  69489. engine.setDepthWrite(true);
  69490. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69491. };
  69492. /**
  69493. * Disposes of the post process manager.
  69494. */
  69495. PostProcessManager.prototype.dispose = function () {
  69496. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69497. if (buffer) {
  69498. buffer.dispose();
  69499. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69500. }
  69501. if (this._indexBuffer) {
  69502. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69503. this._indexBuffer = null;
  69504. }
  69505. };
  69506. return PostProcessManager;
  69507. }());
  69508. BABYLON.PostProcessManager = PostProcessManager;
  69509. })(BABYLON || (BABYLON = {}));
  69510. //# sourceMappingURL=babylon.postProcessManager.js.map
  69511. var BABYLON;
  69512. (function (BABYLON) {
  69513. /**
  69514. * PostProcess can be used to apply a shader to a texture after it has been rendered
  69515. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  69516. */
  69517. var PostProcess = /** @class */ (function () {
  69518. /**
  69519. * Creates a new instance PostProcess
  69520. * @param name The name of the PostProcess.
  69521. * @param fragmentUrl The url of the fragment shader to be used.
  69522. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  69523. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  69524. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69525. * @param camera The camera to apply the render pass to.
  69526. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69527. * @param engine The engine which the post process will be applied. (default: current engine)
  69528. * @param reusable If the post process can be reused on the same frame. (default: false)
  69529. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  69530. * @param textureType Type of textures used when performing the post process. (default: 0)
  69531. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  69532. * @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
  69533. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  69534. */
  69535. function PostProcess(
  69536. /** Name of the PostProcess. */
  69537. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  69538. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  69539. if (defines === void 0) { defines = null; }
  69540. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69541. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  69542. if (blockCompilation === void 0) { blockCompilation = false; }
  69543. this.name = name;
  69544. /**
  69545. * Width of the texture to apply the post process on
  69546. */
  69547. this.width = -1;
  69548. /**
  69549. * Height of the texture to apply the post process on
  69550. */
  69551. this.height = -1;
  69552. /**
  69553. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  69554. * @hidden
  69555. */
  69556. this._outputTexture = null;
  69557. /**
  69558. * If the buffer needs to be cleared before applying the post process. (default: true)
  69559. * Should be set to false if shader will overwrite all previous pixels.
  69560. */
  69561. this.autoClear = true;
  69562. /**
  69563. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  69564. */
  69565. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  69566. /**
  69567. * Animations to be used for the post processing
  69568. */
  69569. this.animations = new Array();
  69570. /**
  69571. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  69572. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  69573. */
  69574. this.enablePixelPerfectMode = false;
  69575. /**
  69576. * Force the postprocess to be applied without taking in account viewport
  69577. */
  69578. this.forceFullscreenViewport = true;
  69579. /**
  69580. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  69581. *
  69582. * | Value | Type | Description |
  69583. * | ----- | ----------------------------------- | ----------- |
  69584. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  69585. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  69586. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  69587. *
  69588. */
  69589. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  69590. /**
  69591. * Force textures to be a power of two (default: false)
  69592. */
  69593. this.alwaysForcePOT = false;
  69594. this._samples = 1;
  69595. /**
  69596. * Modify the scale of the post process to be the same as the viewport (default: false)
  69597. */
  69598. this.adaptScaleToCurrentViewport = false;
  69599. this._reusable = false;
  69600. /**
  69601. * Smart array of input and output textures for the post process.
  69602. * @hidden
  69603. */
  69604. this._textures = new BABYLON.SmartArray(2);
  69605. /**
  69606. * The index in _textures that corresponds to the output texture.
  69607. * @hidden
  69608. */
  69609. this._currentRenderTextureInd = 0;
  69610. this._scaleRatio = new BABYLON.Vector2(1, 1);
  69611. this._texelSize = BABYLON.Vector2.Zero();
  69612. // Events
  69613. /**
  69614. * An event triggered when the postprocess is activated.
  69615. */
  69616. this.onActivateObservable = new BABYLON.Observable();
  69617. /**
  69618. * An event triggered when the postprocess changes its size.
  69619. */
  69620. this.onSizeChangedObservable = new BABYLON.Observable();
  69621. /**
  69622. * An event triggered when the postprocess applies its effect.
  69623. */
  69624. this.onApplyObservable = new BABYLON.Observable();
  69625. /**
  69626. * An event triggered before rendering the postprocess
  69627. */
  69628. this.onBeforeRenderObservable = new BABYLON.Observable();
  69629. /**
  69630. * An event triggered after rendering the postprocess
  69631. */
  69632. this.onAfterRenderObservable = new BABYLON.Observable();
  69633. if (camera != null) {
  69634. this._camera = camera;
  69635. this._scene = camera.getScene();
  69636. camera.attachPostProcess(this);
  69637. this._engine = this._scene.getEngine();
  69638. this._scene.postProcesses.push(this);
  69639. }
  69640. else if (engine) {
  69641. this._engine = engine;
  69642. this._engine.postProcesses.push(this);
  69643. }
  69644. this._options = options;
  69645. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  69646. this._reusable = reusable || false;
  69647. this._textureType = textureType;
  69648. this._samplers = samplers || [];
  69649. this._samplers.push("textureSampler");
  69650. this._fragmentUrl = fragmentUrl;
  69651. this._vertexUrl = vertexUrl;
  69652. this._parameters = parameters || [];
  69653. this._parameters.push("scale");
  69654. this._indexParameters = indexParameters;
  69655. if (!blockCompilation) {
  69656. this.updateEffect(defines);
  69657. }
  69658. }
  69659. Object.defineProperty(PostProcess.prototype, "samples", {
  69660. /**
  69661. * Number of sample textures (default: 1)
  69662. */
  69663. get: function () {
  69664. return this._samples;
  69665. },
  69666. set: function (n) {
  69667. var _this = this;
  69668. this._samples = n;
  69669. this._textures.forEach(function (texture) {
  69670. if (texture.samples !== _this._samples) {
  69671. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  69672. }
  69673. });
  69674. },
  69675. enumerable: true,
  69676. configurable: true
  69677. });
  69678. Object.defineProperty(PostProcess.prototype, "onActivate", {
  69679. /**
  69680. * A function that is added to the onActivateObservable
  69681. */
  69682. set: function (callback) {
  69683. if (this._onActivateObserver) {
  69684. this.onActivateObservable.remove(this._onActivateObserver);
  69685. }
  69686. if (callback) {
  69687. this._onActivateObserver = this.onActivateObservable.add(callback);
  69688. }
  69689. },
  69690. enumerable: true,
  69691. configurable: true
  69692. });
  69693. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  69694. /**
  69695. * A function that is added to the onSizeChangedObservable
  69696. */
  69697. set: function (callback) {
  69698. if (this._onSizeChangedObserver) {
  69699. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  69700. }
  69701. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  69702. },
  69703. enumerable: true,
  69704. configurable: true
  69705. });
  69706. Object.defineProperty(PostProcess.prototype, "onApply", {
  69707. /**
  69708. * A function that is added to the onApplyObservable
  69709. */
  69710. set: function (callback) {
  69711. if (this._onApplyObserver) {
  69712. this.onApplyObservable.remove(this._onApplyObserver);
  69713. }
  69714. this._onApplyObserver = this.onApplyObservable.add(callback);
  69715. },
  69716. enumerable: true,
  69717. configurable: true
  69718. });
  69719. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  69720. /**
  69721. * A function that is added to the onBeforeRenderObservable
  69722. */
  69723. set: function (callback) {
  69724. if (this._onBeforeRenderObserver) {
  69725. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  69726. }
  69727. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  69728. },
  69729. enumerable: true,
  69730. configurable: true
  69731. });
  69732. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  69733. /**
  69734. * A function that is added to the onAfterRenderObservable
  69735. */
  69736. set: function (callback) {
  69737. if (this._onAfterRenderObserver) {
  69738. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  69739. }
  69740. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  69741. },
  69742. enumerable: true,
  69743. configurable: true
  69744. });
  69745. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  69746. /**
  69747. * 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
  69748. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  69749. */
  69750. get: function () {
  69751. return this._textures.data[this._currentRenderTextureInd];
  69752. },
  69753. set: function (value) {
  69754. this._forcedOutputTexture = value;
  69755. },
  69756. enumerable: true,
  69757. configurable: true
  69758. });
  69759. /**
  69760. * Gets the camera which post process is applied to.
  69761. * @returns The camera the post process is applied to.
  69762. */
  69763. PostProcess.prototype.getCamera = function () {
  69764. return this._camera;
  69765. };
  69766. Object.defineProperty(PostProcess.prototype, "texelSize", {
  69767. /**
  69768. * Gets the texel size of the postprocess.
  69769. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  69770. */
  69771. get: function () {
  69772. if (this._shareOutputWithPostProcess) {
  69773. return this._shareOutputWithPostProcess.texelSize;
  69774. }
  69775. if (this._forcedOutputTexture) {
  69776. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  69777. }
  69778. return this._texelSize;
  69779. },
  69780. enumerable: true,
  69781. configurable: true
  69782. });
  69783. /**
  69784. * Gets the engine which this post process belongs to.
  69785. * @returns The engine the post process was enabled with.
  69786. */
  69787. PostProcess.prototype.getEngine = function () {
  69788. return this._engine;
  69789. };
  69790. /**
  69791. * The effect that is created when initializing the post process.
  69792. * @returns The created effect corrisponding the the postprocess.
  69793. */
  69794. PostProcess.prototype.getEffect = function () {
  69795. return this._effect;
  69796. };
  69797. /**
  69798. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  69799. * @param postProcess The post process to share the output with.
  69800. * @returns This post process.
  69801. */
  69802. PostProcess.prototype.shareOutputWith = function (postProcess) {
  69803. this._disposeTextures();
  69804. this._shareOutputWithPostProcess = postProcess;
  69805. return this;
  69806. };
  69807. /**
  69808. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  69809. * This should be called if the post process that shares output with this post process is disabled/disposed.
  69810. */
  69811. PostProcess.prototype.useOwnOutput = function () {
  69812. if (this._textures.length == 0) {
  69813. this._textures = new BABYLON.SmartArray(2);
  69814. }
  69815. this._shareOutputWithPostProcess = null;
  69816. };
  69817. /**
  69818. * Updates the effect with the current post process compile time values and recompiles the shader.
  69819. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69820. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69821. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69822. * @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
  69823. * @param onCompiled Called when the shader has been compiled.
  69824. * @param onError Called if there is an error when compiling a shader.
  69825. */
  69826. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69827. if (defines === void 0) { defines = null; }
  69828. if (uniforms === void 0) { uniforms = null; }
  69829. if (samplers === void 0) { samplers = null; }
  69830. 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);
  69831. };
  69832. /**
  69833. * The post process is reusable if it can be used multiple times within one frame.
  69834. * @returns If the post process is reusable
  69835. */
  69836. PostProcess.prototype.isReusable = function () {
  69837. return this._reusable;
  69838. };
  69839. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  69840. PostProcess.prototype.markTextureDirty = function () {
  69841. this.width = -1;
  69842. };
  69843. /**
  69844. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  69845. * 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.
  69846. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  69847. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  69848. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  69849. * @returns The target texture that was bound to be written to.
  69850. */
  69851. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  69852. var _this = this;
  69853. if (sourceTexture === void 0) { sourceTexture = null; }
  69854. camera = camera || this._camera;
  69855. var scene = camera.getScene();
  69856. var engine = scene.getEngine();
  69857. var maxSize = engine.getCaps().maxTextureSize;
  69858. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  69859. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  69860. // 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
  69861. var webVRCamera = camera.parent;
  69862. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  69863. requiredWidth /= 2;
  69864. }
  69865. var desiredWidth = (this._options.width || requiredWidth);
  69866. var desiredHeight = this._options.height || requiredHeight;
  69867. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  69868. if (this.adaptScaleToCurrentViewport) {
  69869. var currentViewport = engine.currentViewport;
  69870. if (currentViewport) {
  69871. desiredWidth *= currentViewport.width;
  69872. desiredHeight *= currentViewport.height;
  69873. }
  69874. }
  69875. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  69876. if (!this._options.width) {
  69877. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  69878. }
  69879. if (!this._options.height) {
  69880. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  69881. }
  69882. }
  69883. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  69884. if (this._textures.length > 0) {
  69885. for (var i = 0; i < this._textures.length; i++) {
  69886. this._engine._releaseTexture(this._textures.data[i]);
  69887. }
  69888. this._textures.reset();
  69889. }
  69890. this.width = desiredWidth;
  69891. this.height = desiredHeight;
  69892. var textureSize = { width: this.width, height: this.height };
  69893. var textureOptions = {
  69894. generateMipMaps: false,
  69895. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  69896. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  69897. samplingMode: this.renderTargetSamplingMode,
  69898. type: this._textureType
  69899. };
  69900. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  69901. if (this._reusable) {
  69902. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  69903. }
  69904. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  69905. this.onSizeChangedObservable.notifyObservers(this);
  69906. }
  69907. this._textures.forEach(function (texture) {
  69908. if (texture.samples !== _this.samples) {
  69909. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  69910. }
  69911. });
  69912. }
  69913. var target;
  69914. if (this._shareOutputWithPostProcess) {
  69915. target = this._shareOutputWithPostProcess.inputTexture;
  69916. }
  69917. else if (this._forcedOutputTexture) {
  69918. target = this._forcedOutputTexture;
  69919. this.width = this._forcedOutputTexture.width;
  69920. this.height = this._forcedOutputTexture.height;
  69921. }
  69922. else {
  69923. target = this.inputTexture;
  69924. }
  69925. // Bind the input of this post process to be used as the output of the previous post process.
  69926. if (this.enablePixelPerfectMode) {
  69927. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  69928. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  69929. }
  69930. else {
  69931. this._scaleRatio.copyFromFloats(1, 1);
  69932. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  69933. }
  69934. this.onActivateObservable.notifyObservers(camera);
  69935. // Clear
  69936. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  69937. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  69938. }
  69939. if (this._reusable) {
  69940. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  69941. }
  69942. return target;
  69943. };
  69944. Object.defineProperty(PostProcess.prototype, "isSupported", {
  69945. /**
  69946. * If the post process is supported.
  69947. */
  69948. get: function () {
  69949. return this._effect.isSupported;
  69950. },
  69951. enumerable: true,
  69952. configurable: true
  69953. });
  69954. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  69955. /**
  69956. * The aspect ratio of the output texture.
  69957. */
  69958. get: function () {
  69959. if (this._shareOutputWithPostProcess) {
  69960. return this._shareOutputWithPostProcess.aspectRatio;
  69961. }
  69962. if (this._forcedOutputTexture) {
  69963. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  69964. }
  69965. return this.width / this.height;
  69966. },
  69967. enumerable: true,
  69968. configurable: true
  69969. });
  69970. /**
  69971. * Get a value indicating if the post-process is ready to be used
  69972. * @returns true if the post-process is ready (shader is compiled)
  69973. */
  69974. PostProcess.prototype.isReady = function () {
  69975. return this._effect && this._effect.isReady();
  69976. };
  69977. /**
  69978. * Binds all textures and uniforms to the shader, this will be run on every pass.
  69979. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  69980. */
  69981. PostProcess.prototype.apply = function () {
  69982. // Check
  69983. if (!this._effect || !this._effect.isReady())
  69984. return null;
  69985. // States
  69986. this._engine.enableEffect(this._effect);
  69987. this._engine.setState(false);
  69988. this._engine.setDepthBuffer(false);
  69989. this._engine.setDepthWrite(false);
  69990. // Alpha
  69991. this._engine.setAlphaMode(this.alphaMode);
  69992. if (this.alphaConstants) {
  69993. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  69994. }
  69995. // Bind the output texture of the preivous post process as the input to this post process.
  69996. var source;
  69997. if (this._shareOutputWithPostProcess) {
  69998. source = this._shareOutputWithPostProcess.inputTexture;
  69999. }
  70000. else if (this._forcedOutputTexture) {
  70001. source = this._forcedOutputTexture;
  70002. }
  70003. else {
  70004. source = this.inputTexture;
  70005. }
  70006. this._effect._bindTexture("textureSampler", source);
  70007. // Parameters
  70008. this._effect.setVector2("scale", this._scaleRatio);
  70009. this.onApplyObservable.notifyObservers(this._effect);
  70010. return this._effect;
  70011. };
  70012. PostProcess.prototype._disposeTextures = function () {
  70013. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  70014. return;
  70015. }
  70016. if (this._textures.length > 0) {
  70017. for (var i = 0; i < this._textures.length; i++) {
  70018. this._engine._releaseTexture(this._textures.data[i]);
  70019. }
  70020. }
  70021. this._textures.dispose();
  70022. };
  70023. /**
  70024. * Disposes the post process.
  70025. * @param camera The camera to dispose the post process on.
  70026. */
  70027. PostProcess.prototype.dispose = function (camera) {
  70028. camera = camera || this._camera;
  70029. this._disposeTextures();
  70030. if (this._scene) {
  70031. var index_1 = this._scene.postProcesses.indexOf(this);
  70032. if (index_1 !== -1) {
  70033. this._scene.postProcesses.splice(index_1, 1);
  70034. }
  70035. }
  70036. else {
  70037. var index_2 = this._engine.postProcesses.indexOf(this);
  70038. if (index_2 !== -1) {
  70039. this._engine.postProcesses.splice(index_2, 1);
  70040. }
  70041. }
  70042. if (!camera) {
  70043. return;
  70044. }
  70045. camera.detachPostProcess(this);
  70046. var index = camera._postProcesses.indexOf(this);
  70047. if (index === 0 && camera._postProcesses.length > 0) {
  70048. var firstPostProcess = this._camera._getFirstPostProcess();
  70049. if (firstPostProcess) {
  70050. firstPostProcess.markTextureDirty();
  70051. }
  70052. }
  70053. this.onActivateObservable.clear();
  70054. this.onAfterRenderObservable.clear();
  70055. this.onApplyObservable.clear();
  70056. this.onBeforeRenderObservable.clear();
  70057. this.onSizeChangedObservable.clear();
  70058. };
  70059. return PostProcess;
  70060. }());
  70061. BABYLON.PostProcess = PostProcess;
  70062. })(BABYLON || (BABYLON = {}));
  70063. //# sourceMappingURL=babylon.postProcess.js.map
  70064. var BABYLON;
  70065. (function (BABYLON) {
  70066. var PassPostProcess = /** @class */ (function (_super) {
  70067. __extends(PassPostProcess, _super);
  70068. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70069. if (camera === void 0) { camera = null; }
  70070. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70071. if (blockCompilation === void 0) { blockCompilation = false; }
  70072. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  70073. }
  70074. return PassPostProcess;
  70075. }(BABYLON.PostProcess));
  70076. BABYLON.PassPostProcess = PassPostProcess;
  70077. })(BABYLON || (BABYLON = {}));
  70078. //# sourceMappingURL=babylon.passPostProcess.js.map
  70079. var __assign = (this && this.__assign) || function () {
  70080. __assign = Object.assign || function(t) {
  70081. for (var s, i = 1, n = arguments.length; i < n; i++) {
  70082. s = arguments[i];
  70083. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  70084. t[p] = s[p];
  70085. }
  70086. return t;
  70087. };
  70088. return __assign.apply(this, arguments);
  70089. };
  70090. var BABYLON;
  70091. (function (BABYLON) {
  70092. /**
  70093. * Default implementation IShadowGenerator.
  70094. * This is the main object responsible of generating shadows in the framework.
  70095. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  70096. */
  70097. var ShadowGenerator = /** @class */ (function () {
  70098. /**
  70099. * Creates a ShadowGenerator object.
  70100. * A ShadowGenerator is the required tool to use the shadows.
  70101. * Each light casting shadows needs to use its own ShadowGenerator.
  70102. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  70103. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  70104. * @param light The light object generating the shadows.
  70105. * @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.
  70106. */
  70107. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  70108. this._bias = 0.00005;
  70109. this._normalBias = 0;
  70110. this._blurBoxOffset = 1;
  70111. this._blurScale = 2;
  70112. this._blurKernel = 1;
  70113. this._useKernelBlur = false;
  70114. this._filter = ShadowGenerator.FILTER_NONE;
  70115. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  70116. this._contactHardeningLightSizeUVRatio = 0.1;
  70117. this._darkness = 0;
  70118. this._transparencyShadow = false;
  70119. /**
  70120. * Controls the extent to which the shadows fade out at the edge of the frustum
  70121. * Used only by directionals and spots
  70122. */
  70123. this.frustumEdgeFalloff = 0;
  70124. /**
  70125. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  70126. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  70127. * It might on the other hand introduce peter panning.
  70128. */
  70129. this.forceBackFacesOnly = false;
  70130. this._lightDirection = BABYLON.Vector3.Zero();
  70131. this._viewMatrix = BABYLON.Matrix.Zero();
  70132. this._projectionMatrix = BABYLON.Matrix.Zero();
  70133. this._transformMatrix = BABYLON.Matrix.Zero();
  70134. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  70135. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  70136. this._currentFaceIndex = 0;
  70137. this._currentFaceIndexCache = 0;
  70138. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  70139. this._mapSize = mapSize;
  70140. this._light = light;
  70141. this._scene = light.getScene();
  70142. light._shadowGenerator = this;
  70143. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  70144. if (!component) {
  70145. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  70146. this._scene._addComponent(component);
  70147. }
  70148. // Texture type fallback from float to int if not supported.
  70149. var caps = this._scene.getEngine().getCaps();
  70150. if (!useFullFloatFirst) {
  70151. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  70152. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70153. }
  70154. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  70155. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70156. }
  70157. else {
  70158. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70159. }
  70160. }
  70161. else {
  70162. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  70163. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70164. }
  70165. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  70166. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70167. }
  70168. else {
  70169. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70170. }
  70171. }
  70172. this._initializeGenerator();
  70173. this._applyFilterValues();
  70174. }
  70175. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  70176. /**
  70177. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  70178. */
  70179. get: function () {
  70180. return this._bias;
  70181. },
  70182. /**
  70183. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  70184. */
  70185. set: function (bias) {
  70186. this._bias = bias;
  70187. },
  70188. enumerable: true,
  70189. configurable: true
  70190. });
  70191. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  70192. /**
  70193. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  70194. */
  70195. get: function () {
  70196. return this._normalBias;
  70197. },
  70198. /**
  70199. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  70200. */
  70201. set: function (normalBias) {
  70202. this._normalBias = normalBias;
  70203. },
  70204. enumerable: true,
  70205. configurable: true
  70206. });
  70207. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  70208. /**
  70209. * Gets the blur box offset: offset applied during the blur pass.
  70210. * Only usefull if useKernelBlur = false
  70211. */
  70212. get: function () {
  70213. return this._blurBoxOffset;
  70214. },
  70215. /**
  70216. * Sets the blur box offset: offset applied during the blur pass.
  70217. * Only usefull if useKernelBlur = false
  70218. */
  70219. set: function (value) {
  70220. if (this._blurBoxOffset === value) {
  70221. return;
  70222. }
  70223. this._blurBoxOffset = value;
  70224. this._disposeBlurPostProcesses();
  70225. },
  70226. enumerable: true,
  70227. configurable: true
  70228. });
  70229. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  70230. /**
  70231. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  70232. * 2 means half of the size.
  70233. */
  70234. get: function () {
  70235. return this._blurScale;
  70236. },
  70237. /**
  70238. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  70239. * 2 means half of the size.
  70240. */
  70241. set: function (value) {
  70242. if (this._blurScale === value) {
  70243. return;
  70244. }
  70245. this._blurScale = value;
  70246. this._disposeBlurPostProcesses();
  70247. },
  70248. enumerable: true,
  70249. configurable: true
  70250. });
  70251. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  70252. /**
  70253. * Gets the blur kernel: kernel size of the blur pass.
  70254. * Only usefull if useKernelBlur = true
  70255. */
  70256. get: function () {
  70257. return this._blurKernel;
  70258. },
  70259. /**
  70260. * Sets the blur kernel: kernel size of the blur pass.
  70261. * Only usefull if useKernelBlur = true
  70262. */
  70263. set: function (value) {
  70264. if (this._blurKernel === value) {
  70265. return;
  70266. }
  70267. this._blurKernel = value;
  70268. this._disposeBlurPostProcesses();
  70269. },
  70270. enumerable: true,
  70271. configurable: true
  70272. });
  70273. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  70274. /**
  70275. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  70276. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  70277. */
  70278. get: function () {
  70279. return this._useKernelBlur;
  70280. },
  70281. /**
  70282. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  70283. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  70284. */
  70285. set: function (value) {
  70286. if (this._useKernelBlur === value) {
  70287. return;
  70288. }
  70289. this._useKernelBlur = value;
  70290. this._disposeBlurPostProcesses();
  70291. },
  70292. enumerable: true,
  70293. configurable: true
  70294. });
  70295. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  70296. /**
  70297. * Gets the depth scale used in ESM mode.
  70298. */
  70299. get: function () {
  70300. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  70301. },
  70302. /**
  70303. * Sets the depth scale used in ESM mode.
  70304. * This can override the scale stored on the light.
  70305. */
  70306. set: function (value) {
  70307. this._depthScale = value;
  70308. },
  70309. enumerable: true,
  70310. configurable: true
  70311. });
  70312. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  70313. /**
  70314. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  70315. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  70316. */
  70317. get: function () {
  70318. return this._filter;
  70319. },
  70320. /**
  70321. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  70322. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  70323. */
  70324. set: function (value) {
  70325. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  70326. if (this._light.needCube()) {
  70327. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  70328. this.useExponentialShadowMap = true;
  70329. return;
  70330. }
  70331. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  70332. this.useCloseExponentialShadowMap = true;
  70333. return;
  70334. }
  70335. // PCF on cubemap would also be expensive
  70336. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  70337. this.usePoissonSampling = true;
  70338. return;
  70339. }
  70340. }
  70341. // Weblg1 fallback for PCF.
  70342. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  70343. if (this._scene.getEngine().webGLVersion === 1) {
  70344. this.usePoissonSampling = true;
  70345. return;
  70346. }
  70347. }
  70348. if (this._filter === value) {
  70349. return;
  70350. }
  70351. this._filter = value;
  70352. this._disposeBlurPostProcesses();
  70353. this._applyFilterValues();
  70354. this._light._markMeshesAsLightDirty();
  70355. },
  70356. enumerable: true,
  70357. configurable: true
  70358. });
  70359. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  70360. /**
  70361. * Gets if the current filter is set to Poisson Sampling.
  70362. */
  70363. get: function () {
  70364. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  70365. },
  70366. /**
  70367. * Sets the current filter to Poisson Sampling.
  70368. */
  70369. set: function (value) {
  70370. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  70371. return;
  70372. }
  70373. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  70374. },
  70375. enumerable: true,
  70376. configurable: true
  70377. });
  70378. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  70379. /**
  70380. * Gets if the current filter is set to VSM.
  70381. * DEPRECATED. Should use useExponentialShadowMap instead.
  70382. */
  70383. get: function () {
  70384. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  70385. return this.useExponentialShadowMap;
  70386. },
  70387. /**
  70388. * Sets the current filter is to VSM.
  70389. * DEPRECATED. Should use useExponentialShadowMap instead.
  70390. */
  70391. set: function (value) {
  70392. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  70393. this.useExponentialShadowMap = value;
  70394. },
  70395. enumerable: true,
  70396. configurable: true
  70397. });
  70398. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  70399. /**
  70400. * Gets if the current filter is set to blurred VSM.
  70401. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  70402. */
  70403. get: function () {
  70404. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  70405. return this.useBlurExponentialShadowMap;
  70406. },
  70407. /**
  70408. * Sets the current filter is to blurred VSM.
  70409. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  70410. */
  70411. set: function (value) {
  70412. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  70413. this.useBlurExponentialShadowMap = value;
  70414. },
  70415. enumerable: true,
  70416. configurable: true
  70417. });
  70418. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  70419. /**
  70420. * Gets if the current filter is set to ESM.
  70421. */
  70422. get: function () {
  70423. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  70424. },
  70425. /**
  70426. * Sets the current filter is to ESM.
  70427. */
  70428. set: function (value) {
  70429. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  70430. return;
  70431. }
  70432. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70433. },
  70434. enumerable: true,
  70435. configurable: true
  70436. });
  70437. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  70438. /**
  70439. * Gets if the current filter is set to filtered ESM.
  70440. */
  70441. get: function () {
  70442. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  70443. },
  70444. /**
  70445. * Gets if the current filter is set to filtered ESM.
  70446. */
  70447. set: function (value) {
  70448. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  70449. return;
  70450. }
  70451. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70452. },
  70453. enumerable: true,
  70454. configurable: true
  70455. });
  70456. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  70457. /**
  70458. * Gets if the current filter is set to "close ESM" (using the inverse of the
  70459. * exponential to prevent steep falloff artifacts).
  70460. */
  70461. get: function () {
  70462. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  70463. },
  70464. /**
  70465. * Sets the current filter to "close ESM" (using the inverse of the
  70466. * exponential to prevent steep falloff artifacts).
  70467. */
  70468. set: function (value) {
  70469. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  70470. return;
  70471. }
  70472. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70473. },
  70474. enumerable: true,
  70475. configurable: true
  70476. });
  70477. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  70478. /**
  70479. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  70480. * exponential to prevent steep falloff artifacts).
  70481. */
  70482. get: function () {
  70483. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  70484. },
  70485. /**
  70486. * Sets the current filter to filtered "close ESM" (using the inverse of the
  70487. * exponential to prevent steep falloff artifacts).
  70488. */
  70489. set: function (value) {
  70490. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  70491. return;
  70492. }
  70493. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70494. },
  70495. enumerable: true,
  70496. configurable: true
  70497. });
  70498. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  70499. /**
  70500. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  70501. */
  70502. get: function () {
  70503. return this.filter === ShadowGenerator.FILTER_PCF;
  70504. },
  70505. /**
  70506. * Sets the current filter to "PCF" (percentage closer filtering).
  70507. */
  70508. set: function (value) {
  70509. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  70510. return;
  70511. }
  70512. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  70513. },
  70514. enumerable: true,
  70515. configurable: true
  70516. });
  70517. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  70518. /**
  70519. * Gets the PCF or PCSS Quality.
  70520. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  70521. */
  70522. get: function () {
  70523. return this._filteringQuality;
  70524. },
  70525. /**
  70526. * Sets the PCF or PCSS Quality.
  70527. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  70528. */
  70529. set: function (filteringQuality) {
  70530. this._filteringQuality = filteringQuality;
  70531. },
  70532. enumerable: true,
  70533. configurable: true
  70534. });
  70535. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  70536. /**
  70537. * Gets if the current filter is set to "PCSS" (contact hardening).
  70538. */
  70539. get: function () {
  70540. return this.filter === ShadowGenerator.FILTER_PCSS;
  70541. },
  70542. /**
  70543. * Sets the current filter to "PCSS" (contact hardening).
  70544. */
  70545. set: function (value) {
  70546. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  70547. return;
  70548. }
  70549. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  70550. },
  70551. enumerable: true,
  70552. configurable: true
  70553. });
  70554. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  70555. /**
  70556. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  70557. * Using a ratio helps keeping shape stability independently of the map size.
  70558. *
  70559. * It does not account for the light projection as it was having too much
  70560. * instability during the light setup or during light position changes.
  70561. *
  70562. * Only valid if useContactHardeningShadow is true.
  70563. */
  70564. get: function () {
  70565. return this._contactHardeningLightSizeUVRatio;
  70566. },
  70567. /**
  70568. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  70569. * Using a ratio helps keeping shape stability independently of the map size.
  70570. *
  70571. * It does not account for the light projection as it was having too much
  70572. * instability during the light setup or during light position changes.
  70573. *
  70574. * Only valid if useContactHardeningShadow is true.
  70575. */
  70576. set: function (contactHardeningLightSizeUVRatio) {
  70577. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  70578. },
  70579. enumerable: true,
  70580. configurable: true
  70581. });
  70582. /**
  70583. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  70584. * 0 means strongest and 1 would means no shadow.
  70585. * @returns the darkness.
  70586. */
  70587. ShadowGenerator.prototype.getDarkness = function () {
  70588. return this._darkness;
  70589. };
  70590. /**
  70591. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  70592. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  70593. * @returns the shadow generator allowing fluent coding.
  70594. */
  70595. ShadowGenerator.prototype.setDarkness = function (darkness) {
  70596. if (darkness >= 1.0)
  70597. this._darkness = 1.0;
  70598. else if (darkness <= 0.0)
  70599. this._darkness = 0.0;
  70600. else
  70601. this._darkness = darkness;
  70602. return this;
  70603. };
  70604. /**
  70605. * Sets the ability to have transparent shadow (boolean).
  70606. * @param transparent True if transparent else False
  70607. * @returns the shadow generator allowing fluent coding
  70608. */
  70609. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  70610. this._transparencyShadow = transparent;
  70611. return this;
  70612. };
  70613. /**
  70614. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  70615. * @returns The render target texture if present otherwise, null
  70616. */
  70617. ShadowGenerator.prototype.getShadowMap = function () {
  70618. return this._shadowMap;
  70619. };
  70620. /**
  70621. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  70622. * @returns The render target texture if the shadow map is present otherwise, null
  70623. */
  70624. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  70625. if (this._shadowMap2) {
  70626. return this._shadowMap2;
  70627. }
  70628. return this._shadowMap;
  70629. };
  70630. /**
  70631. * Helper function to add a mesh and its descendants to the list of shadow casters.
  70632. * @param mesh Mesh to add
  70633. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  70634. * @returns the Shadow Generator itself
  70635. */
  70636. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  70637. if (includeDescendants === void 0) { includeDescendants = true; }
  70638. var _a;
  70639. if (!this._shadowMap) {
  70640. return this;
  70641. }
  70642. if (!this._shadowMap.renderList) {
  70643. this._shadowMap.renderList = [];
  70644. }
  70645. this._shadowMap.renderList.push(mesh);
  70646. if (includeDescendants) {
  70647. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  70648. }
  70649. return this;
  70650. };
  70651. /**
  70652. * Helper function to remove a mesh and its descendants from the list of shadow casters
  70653. * @param mesh Mesh to remove
  70654. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  70655. * @returns the Shadow Generator itself
  70656. */
  70657. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  70658. if (includeDescendants === void 0) { includeDescendants = true; }
  70659. if (!this._shadowMap || !this._shadowMap.renderList) {
  70660. return this;
  70661. }
  70662. var index = this._shadowMap.renderList.indexOf(mesh);
  70663. if (index !== -1) {
  70664. this._shadowMap.renderList.splice(index, 1);
  70665. }
  70666. if (includeDescendants) {
  70667. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  70668. var child = _a[_i];
  70669. this.removeShadowCaster(child);
  70670. }
  70671. }
  70672. return this;
  70673. };
  70674. /**
  70675. * Returns the associated light object.
  70676. * @returns the light generating the shadow
  70677. */
  70678. ShadowGenerator.prototype.getLight = function () {
  70679. return this._light;
  70680. };
  70681. ShadowGenerator.prototype._initializeGenerator = function () {
  70682. this._light._markMeshesAsLightDirty();
  70683. this._initializeShadowMap();
  70684. };
  70685. ShadowGenerator.prototype._initializeShadowMap = function () {
  70686. var _this = this;
  70687. // Render target
  70688. var engine = this._scene.getEngine();
  70689. if (engine.webGLVersion > 1) {
  70690. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  70691. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  70692. }
  70693. else {
  70694. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  70695. }
  70696. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70697. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70698. this._shadowMap.anisotropicFilteringLevel = 1;
  70699. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70700. this._shadowMap.renderParticles = false;
  70701. this._shadowMap.ignoreCameraViewport = true;
  70702. // Record Face Index before render.
  70703. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  70704. _this._currentFaceIndex = faceIndex;
  70705. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70706. engine.setColorWrite(false);
  70707. }
  70708. });
  70709. // Custom render function.
  70710. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  70711. // Blur if required afer render.
  70712. this._shadowMap.onAfterUnbindObservable.add(function () {
  70713. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70714. engine.setColorWrite(true);
  70715. }
  70716. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  70717. return;
  70718. }
  70719. var shadowMap = _this.getShadowMapForRendering();
  70720. if (shadowMap) {
  70721. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  70722. }
  70723. });
  70724. // Clear according to the chosen filter.
  70725. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  70726. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  70727. this._shadowMap.onClearObservable.add(function (engine) {
  70728. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70729. engine.clear(clearOne, false, true, false);
  70730. }
  70731. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  70732. engine.clear(clearZero, true, true, false);
  70733. }
  70734. else {
  70735. engine.clear(clearOne, true, true, false);
  70736. }
  70737. });
  70738. };
  70739. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  70740. var _this = this;
  70741. var engine = this._scene.getEngine();
  70742. var targetSize = this._mapSize / this.blurScale;
  70743. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  70744. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  70745. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70746. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70747. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70748. }
  70749. if (this.useKernelBlur) {
  70750. 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);
  70751. this._kernelBlurXPostprocess.width = targetSize;
  70752. this._kernelBlurXPostprocess.height = targetSize;
  70753. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  70754. effect.setTexture("textureSampler", _this._shadowMap);
  70755. });
  70756. 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);
  70757. this._kernelBlurXPostprocess.autoClear = false;
  70758. this._kernelBlurYPostprocess.autoClear = false;
  70759. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70760. this._kernelBlurXPostprocess.packedFloat = true;
  70761. this._kernelBlurYPostprocess.packedFloat = true;
  70762. }
  70763. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  70764. }
  70765. else {
  70766. 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);
  70767. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  70768. effect.setFloat2("screenSize", targetSize, targetSize);
  70769. effect.setTexture("textureSampler", _this._shadowMap);
  70770. });
  70771. this._boxBlurPostprocess.autoClear = false;
  70772. this._blurPostProcesses = [this._boxBlurPostprocess];
  70773. }
  70774. };
  70775. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70776. var index;
  70777. var engine = this._scene.getEngine();
  70778. if (depthOnlySubMeshes.length) {
  70779. engine.setColorWrite(false);
  70780. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70781. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  70782. }
  70783. engine.setColorWrite(true);
  70784. }
  70785. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70786. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  70787. }
  70788. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70789. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  70790. }
  70791. if (this._transparencyShadow) {
  70792. for (index = 0; index < transparentSubMeshes.length; index++) {
  70793. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  70794. }
  70795. }
  70796. };
  70797. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  70798. var _this = this;
  70799. var mesh = subMesh.getRenderingMesh();
  70800. var scene = this._scene;
  70801. var engine = scene.getEngine();
  70802. var material = subMesh.getMaterial();
  70803. if (!material) {
  70804. return;
  70805. }
  70806. // Culling
  70807. engine.setState(material.backFaceCulling);
  70808. // Managing instances
  70809. var batch = mesh._getInstancesRenderList(subMesh._id);
  70810. if (batch.mustReturn) {
  70811. return;
  70812. }
  70813. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  70814. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  70815. engine.enableEffect(this._effect);
  70816. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  70817. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  70818. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  70819. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  70820. this._effect.setVector3("lightData", this._cachedDirection);
  70821. }
  70822. else {
  70823. this._effect.setVector3("lightData", this._cachedPosition);
  70824. }
  70825. if (scene.activeCamera) {
  70826. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  70827. }
  70828. // Alpha test
  70829. if (material && material.needAlphaTesting()) {
  70830. var alphaTexture = material.getAlphaTestTexture();
  70831. if (alphaTexture) {
  70832. this._effect.setTexture("diffuseSampler", alphaTexture);
  70833. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  70834. }
  70835. }
  70836. // Bones
  70837. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70838. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  70839. }
  70840. // Morph targets
  70841. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  70842. if (this.forceBackFacesOnly) {
  70843. engine.setState(true, 0, false, true);
  70844. }
  70845. // Draw
  70846. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70847. if (this.forceBackFacesOnly) {
  70848. engine.setState(true, 0, false, false);
  70849. }
  70850. }
  70851. else {
  70852. // Need to reset refresh rate of the shadowMap
  70853. if (this._shadowMap) {
  70854. this._shadowMap.resetRefreshCounter();
  70855. }
  70856. }
  70857. };
  70858. ShadowGenerator.prototype._applyFilterValues = function () {
  70859. if (!this._shadowMap) {
  70860. return;
  70861. }
  70862. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  70863. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  70864. }
  70865. else {
  70866. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70867. }
  70868. };
  70869. /**
  70870. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  70871. * @param onCompiled Callback triggered at the and of the effects compilation
  70872. * @param options Sets of optional options forcing the compilation with different modes
  70873. */
  70874. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  70875. var _this = this;
  70876. var localOptions = __assign({ useInstances: false }, options);
  70877. var shadowMap = this.getShadowMap();
  70878. if (!shadowMap) {
  70879. if (onCompiled) {
  70880. onCompiled(this);
  70881. }
  70882. return;
  70883. }
  70884. var renderList = shadowMap.renderList;
  70885. if (!renderList) {
  70886. if (onCompiled) {
  70887. onCompiled(this);
  70888. }
  70889. return;
  70890. }
  70891. var subMeshes = new Array();
  70892. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  70893. var mesh = renderList_1[_i];
  70894. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  70895. }
  70896. if (subMeshes.length === 0) {
  70897. if (onCompiled) {
  70898. onCompiled(this);
  70899. }
  70900. return;
  70901. }
  70902. var currentIndex = 0;
  70903. var checkReady = function () {
  70904. if (!_this._scene || !_this._scene.getEngine()) {
  70905. return;
  70906. }
  70907. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  70908. currentIndex++;
  70909. if (currentIndex >= subMeshes.length) {
  70910. if (onCompiled) {
  70911. onCompiled(_this);
  70912. }
  70913. return;
  70914. }
  70915. }
  70916. setTimeout(checkReady, 16);
  70917. };
  70918. checkReady();
  70919. };
  70920. /**
  70921. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  70922. * @param options Sets of optional options forcing the compilation with different modes
  70923. * @returns A promise that resolves when the compilation completes
  70924. */
  70925. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  70926. var _this = this;
  70927. return new Promise(function (resolve) {
  70928. _this.forceCompilation(function () {
  70929. resolve();
  70930. }, options);
  70931. });
  70932. };
  70933. /**
  70934. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  70935. * @param subMesh The submesh we want to render in the shadow map
  70936. * @param useInstances Defines wether will draw in the map using instances
  70937. * @returns true if ready otherwise, false
  70938. */
  70939. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  70940. var defines = [];
  70941. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70942. defines.push("#define FLOAT");
  70943. }
  70944. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  70945. defines.push("#define ESM");
  70946. }
  70947. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  70948. defines.push("#define DEPTHTEXTURE");
  70949. }
  70950. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70951. var mesh = subMesh.getMesh();
  70952. var material = subMesh.getMaterial();
  70953. // Normal bias.
  70954. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  70955. attribs.push(BABYLON.VertexBuffer.NormalKind);
  70956. defines.push("#define NORMAL");
  70957. if (mesh.nonUniformScaling) {
  70958. defines.push("#define NONUNIFORMSCALING");
  70959. }
  70960. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  70961. defines.push("#define DIRECTIONINLIGHTDATA");
  70962. }
  70963. }
  70964. // Alpha test
  70965. if (material && material.needAlphaTesting()) {
  70966. var alphaTexture = material.getAlphaTestTexture();
  70967. if (alphaTexture) {
  70968. defines.push("#define ALPHATEST");
  70969. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70970. attribs.push(BABYLON.VertexBuffer.UVKind);
  70971. defines.push("#define UV1");
  70972. }
  70973. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70974. if (alphaTexture.coordinatesIndex === 1) {
  70975. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70976. defines.push("#define UV2");
  70977. }
  70978. }
  70979. }
  70980. }
  70981. // Bones
  70982. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70983. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70984. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70985. if (mesh.numBoneInfluencers > 4) {
  70986. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70987. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70988. }
  70989. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70990. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  70991. }
  70992. else {
  70993. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70994. }
  70995. // Morph targets
  70996. var manager = mesh.morphTargetManager;
  70997. var morphInfluencers = 0;
  70998. if (manager) {
  70999. if (manager.numInfluencers > 0) {
  71000. defines.push("#define MORPHTARGETS");
  71001. morphInfluencers = manager.numInfluencers;
  71002. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  71003. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  71004. }
  71005. }
  71006. // Instances
  71007. if (useInstances) {
  71008. defines.push("#define INSTANCES");
  71009. attribs.push("world0");
  71010. attribs.push("world1");
  71011. attribs.push("world2");
  71012. attribs.push("world3");
  71013. }
  71014. // Get correct effect
  71015. var join = defines.join("\n");
  71016. if (this._cachedDefines !== join) {
  71017. this._cachedDefines = join;
  71018. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  71019. }
  71020. if (!this._effect.isReady()) {
  71021. return false;
  71022. }
  71023. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  71024. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  71025. this._initializeBlurRTTAndPostProcesses();
  71026. }
  71027. }
  71028. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  71029. return false;
  71030. }
  71031. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  71032. return false;
  71033. }
  71034. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  71035. return false;
  71036. }
  71037. return true;
  71038. };
  71039. /**
  71040. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  71041. * @param defines Defines of the material we want to update
  71042. * @param lightIndex Index of the light in the enabled light list of the material
  71043. */
  71044. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  71045. var scene = this._scene;
  71046. var light = this._light;
  71047. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  71048. return;
  71049. }
  71050. defines["SHADOW" + lightIndex] = true;
  71051. if (this.useContactHardeningShadow) {
  71052. defines["SHADOWPCSS" + lightIndex] = true;
  71053. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  71054. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  71055. }
  71056. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  71057. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  71058. }
  71059. // else default to high.
  71060. }
  71061. if (this.usePercentageCloserFiltering) {
  71062. defines["SHADOWPCF" + lightIndex] = true;
  71063. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  71064. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  71065. }
  71066. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  71067. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  71068. }
  71069. // else default to high.
  71070. }
  71071. else if (this.usePoissonSampling) {
  71072. defines["SHADOWPOISSON" + lightIndex] = true;
  71073. }
  71074. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  71075. defines["SHADOWESM" + lightIndex] = true;
  71076. }
  71077. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  71078. defines["SHADOWCLOSEESM" + lightIndex] = true;
  71079. }
  71080. if (light.needCube()) {
  71081. defines["SHADOWCUBE" + lightIndex] = true;
  71082. }
  71083. };
  71084. /**
  71085. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  71086. * defined in the generator but impacting the effect).
  71087. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  71088. * @param effect The effect we are binfing the information for
  71089. */
  71090. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  71091. var light = this._light;
  71092. var scene = this._scene;
  71093. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  71094. return;
  71095. }
  71096. var camera = scene.activeCamera;
  71097. if (!camera) {
  71098. return;
  71099. }
  71100. var shadowMap = this.getShadowMap();
  71101. if (!shadowMap) {
  71102. return;
  71103. }
  71104. if (!light.needCube()) {
  71105. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  71106. }
  71107. // Only PCF uses depth stencil texture.
  71108. if (this._filter === ShadowGenerator.FILTER_PCF) {
  71109. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  71110. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  71111. }
  71112. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  71113. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  71114. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  71115. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  71116. }
  71117. else {
  71118. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  71119. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  71120. }
  71121. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  71122. };
  71123. /**
  71124. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  71125. * (eq to shadow prjection matrix * light transform matrix)
  71126. * @returns The transform matrix used to create the shadow map
  71127. */
  71128. ShadowGenerator.prototype.getTransformMatrix = function () {
  71129. var scene = this._scene;
  71130. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  71131. return this._transformMatrix;
  71132. }
  71133. this._currentRenderID = scene.getRenderId();
  71134. this._currentFaceIndexCache = this._currentFaceIndex;
  71135. var lightPosition = this._light.position;
  71136. if (this._light.computeTransformedInformation()) {
  71137. lightPosition = this._light.transformedPosition;
  71138. }
  71139. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  71140. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  71141. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  71142. }
  71143. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  71144. this._cachedPosition.copyFrom(lightPosition);
  71145. this._cachedDirection.copyFrom(this._lightDirection);
  71146. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  71147. var shadowMap = this.getShadowMap();
  71148. if (shadowMap) {
  71149. var renderList = shadowMap.renderList;
  71150. if (renderList) {
  71151. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  71152. }
  71153. }
  71154. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  71155. }
  71156. return this._transformMatrix;
  71157. };
  71158. /**
  71159. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  71160. * Cube and 2D textures for instance.
  71161. */
  71162. ShadowGenerator.prototype.recreateShadowMap = function () {
  71163. var shadowMap = this._shadowMap;
  71164. if (!shadowMap) {
  71165. return;
  71166. }
  71167. // Track render list.
  71168. var renderList = shadowMap.renderList;
  71169. // Clean up existing data.
  71170. this._disposeRTTandPostProcesses();
  71171. // Reinitializes.
  71172. this._initializeGenerator();
  71173. // Reaffect the filter to ensure a correct fallback if necessary.
  71174. this.filter = this.filter;
  71175. // Reaffect the filter.
  71176. this._applyFilterValues();
  71177. // Reaffect Render List.
  71178. this._shadowMap.renderList = renderList;
  71179. };
  71180. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  71181. if (this._shadowMap2) {
  71182. this._shadowMap2.dispose();
  71183. this._shadowMap2 = null;
  71184. }
  71185. if (this._boxBlurPostprocess) {
  71186. this._boxBlurPostprocess.dispose();
  71187. this._boxBlurPostprocess = null;
  71188. }
  71189. if (this._kernelBlurXPostprocess) {
  71190. this._kernelBlurXPostprocess.dispose();
  71191. this._kernelBlurXPostprocess = null;
  71192. }
  71193. if (this._kernelBlurYPostprocess) {
  71194. this._kernelBlurYPostprocess.dispose();
  71195. this._kernelBlurYPostprocess = null;
  71196. }
  71197. this._blurPostProcesses = [];
  71198. };
  71199. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  71200. if (this._shadowMap) {
  71201. this._shadowMap.dispose();
  71202. this._shadowMap = null;
  71203. }
  71204. this._disposeBlurPostProcesses();
  71205. };
  71206. /**
  71207. * Disposes the ShadowGenerator.
  71208. * Returns nothing.
  71209. */
  71210. ShadowGenerator.prototype.dispose = function () {
  71211. this._disposeRTTandPostProcesses();
  71212. if (this._light) {
  71213. this._light._shadowGenerator = null;
  71214. this._light._markMeshesAsLightDirty();
  71215. }
  71216. };
  71217. /**
  71218. * Serializes the shadow generator setup to a json object.
  71219. * @returns The serialized JSON object
  71220. */
  71221. ShadowGenerator.prototype.serialize = function () {
  71222. var serializationObject = {};
  71223. var shadowMap = this.getShadowMap();
  71224. if (!shadowMap) {
  71225. return serializationObject;
  71226. }
  71227. serializationObject.lightId = this._light.id;
  71228. serializationObject.mapSize = shadowMap.getRenderSize();
  71229. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  71230. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  71231. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  71232. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  71233. serializationObject.usePoissonSampling = this.usePoissonSampling;
  71234. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  71235. serializationObject.depthScale = this.depthScale;
  71236. serializationObject.darkness = this.getDarkness();
  71237. serializationObject.blurBoxOffset = this.blurBoxOffset;
  71238. serializationObject.blurKernel = this.blurKernel;
  71239. serializationObject.blurScale = this.blurScale;
  71240. serializationObject.useKernelBlur = this.useKernelBlur;
  71241. serializationObject.transparencyShadow = this._transparencyShadow;
  71242. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  71243. serializationObject.bias = this.bias;
  71244. serializationObject.normalBias = this.normalBias;
  71245. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  71246. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  71247. serializationObject.filteringQuality = this.filteringQuality;
  71248. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  71249. serializationObject.renderList = [];
  71250. if (shadowMap.renderList) {
  71251. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  71252. var mesh = shadowMap.renderList[meshIndex];
  71253. serializationObject.renderList.push(mesh.id);
  71254. }
  71255. }
  71256. return serializationObject;
  71257. };
  71258. /**
  71259. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  71260. * @param parsedShadowGenerator The JSON object to parse
  71261. * @param scene The scene to create the shadow map for
  71262. * @returns The parsed shadow generator
  71263. */
  71264. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  71265. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  71266. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  71267. var shadowMap = shadowGenerator.getShadowMap();
  71268. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  71269. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  71270. meshes.forEach(function (mesh) {
  71271. if (!shadowMap) {
  71272. return;
  71273. }
  71274. if (!shadowMap.renderList) {
  71275. shadowMap.renderList = [];
  71276. }
  71277. shadowMap.renderList.push(mesh);
  71278. });
  71279. }
  71280. if (parsedShadowGenerator.usePoissonSampling) {
  71281. shadowGenerator.usePoissonSampling = true;
  71282. }
  71283. else if (parsedShadowGenerator.useExponentialShadowMap) {
  71284. shadowGenerator.useExponentialShadowMap = true;
  71285. }
  71286. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  71287. shadowGenerator.useBlurExponentialShadowMap = true;
  71288. }
  71289. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  71290. shadowGenerator.useCloseExponentialShadowMap = true;
  71291. }
  71292. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  71293. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  71294. }
  71295. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  71296. shadowGenerator.usePercentageCloserFiltering = true;
  71297. }
  71298. else if (parsedShadowGenerator.useContactHardeningShadow) {
  71299. shadowGenerator.useContactHardeningShadow = true;
  71300. }
  71301. if (parsedShadowGenerator.filteringQuality) {
  71302. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  71303. }
  71304. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  71305. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  71306. }
  71307. // Backward compat
  71308. else if (parsedShadowGenerator.useVarianceShadowMap) {
  71309. shadowGenerator.useExponentialShadowMap = true;
  71310. }
  71311. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  71312. shadowGenerator.useBlurExponentialShadowMap = true;
  71313. }
  71314. if (parsedShadowGenerator.depthScale) {
  71315. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  71316. }
  71317. if (parsedShadowGenerator.blurScale) {
  71318. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  71319. }
  71320. if (parsedShadowGenerator.blurBoxOffset) {
  71321. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  71322. }
  71323. if (parsedShadowGenerator.useKernelBlur) {
  71324. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  71325. }
  71326. if (parsedShadowGenerator.blurKernel) {
  71327. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  71328. }
  71329. if (parsedShadowGenerator.bias !== undefined) {
  71330. shadowGenerator.bias = parsedShadowGenerator.bias;
  71331. }
  71332. if (parsedShadowGenerator.normalBias !== undefined) {
  71333. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  71334. }
  71335. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  71336. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  71337. }
  71338. if (parsedShadowGenerator.darkness) {
  71339. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  71340. }
  71341. if (parsedShadowGenerator.transparencyShadow) {
  71342. shadowGenerator.setTransparencyShadow(true);
  71343. }
  71344. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  71345. return shadowGenerator;
  71346. };
  71347. /**
  71348. * Shadow generator mode None: no filtering applied.
  71349. */
  71350. ShadowGenerator.FILTER_NONE = 0;
  71351. /**
  71352. * Shadow generator mode ESM: Exponential Shadow Mapping.
  71353. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71354. */
  71355. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  71356. /**
  71357. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  71358. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  71359. */
  71360. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  71361. /**
  71362. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  71363. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71364. */
  71365. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  71366. /**
  71367. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  71368. * edge artifacts on steep falloff.
  71369. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71370. */
  71371. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  71372. /**
  71373. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  71374. * edge artifacts on steep falloff.
  71375. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71376. */
  71377. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  71378. /**
  71379. * Shadow generator mode PCF: Percentage Closer Filtering
  71380. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  71381. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  71382. */
  71383. ShadowGenerator.FILTER_PCF = 6;
  71384. /**
  71385. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  71386. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  71387. * Contact Hardening
  71388. */
  71389. ShadowGenerator.FILTER_PCSS = 7;
  71390. /**
  71391. * Reserved for PCF and PCSS
  71392. * Highest Quality.
  71393. *
  71394. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  71395. *
  71396. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  71397. */
  71398. ShadowGenerator.QUALITY_HIGH = 0;
  71399. /**
  71400. * Reserved for PCF and PCSS
  71401. * Good tradeoff for quality/perf cross devices
  71402. *
  71403. * Execute PCF on a 3*3 kernel.
  71404. *
  71405. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  71406. */
  71407. ShadowGenerator.QUALITY_MEDIUM = 1;
  71408. /**
  71409. * Reserved for PCF and PCSS
  71410. * The lowest quality but the fastest.
  71411. *
  71412. * Execute PCF on a 1*1 kernel.
  71413. *
  71414. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  71415. */
  71416. ShadowGenerator.QUALITY_LOW = 2;
  71417. return ShadowGenerator;
  71418. }());
  71419. BABYLON.ShadowGenerator = ShadowGenerator;
  71420. })(BABYLON || (BABYLON = {}));
  71421. //# sourceMappingURL=babylon.shadowGenerator.js.map
  71422. var BABYLON;
  71423. (function (BABYLON) {
  71424. // Adds the parser to the scene parsers.
  71425. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  71426. // Shadows
  71427. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  71428. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  71429. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  71430. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  71431. // SG would be available on their associated lights
  71432. }
  71433. }
  71434. });
  71435. /**
  71436. * Defines the shadow generator component responsible to manage any shadow generators
  71437. * in a given scene.
  71438. */
  71439. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  71440. /**
  71441. * Creates a new instance of the component for the given scene
  71442. * @param scene Defines the scene to register the component in
  71443. */
  71444. function ShadowGeneratorSceneComponent(scene) {
  71445. /**
  71446. * The component name helpfull to identify the component in the list of scene components.
  71447. */
  71448. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  71449. this.scene = scene;
  71450. }
  71451. /**
  71452. * Registers the component in a given scene
  71453. */
  71454. ShadowGeneratorSceneComponent.prototype.register = function () {
  71455. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  71456. };
  71457. /**
  71458. * Rebuilds the elements related to this component in case of
  71459. * context lost for instance.
  71460. */
  71461. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  71462. // Nothing To Do Here.
  71463. };
  71464. /**
  71465. * Serializes the component data to the specified json object
  71466. * @param serializationObject The object to serialize to
  71467. */
  71468. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  71469. // Shadows
  71470. serializationObject.shadowGenerators = [];
  71471. var lights = this.scene.lights;
  71472. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  71473. var light = lights_1[_i];
  71474. var shadowGenerator = light.getShadowGenerator();
  71475. if (shadowGenerator) {
  71476. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  71477. }
  71478. }
  71479. };
  71480. /**
  71481. * Adds all the element from the container to the scene
  71482. * @param container the container holding the elements
  71483. */
  71484. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  71485. // Nothing To Do Here. (directly attached to a light)
  71486. };
  71487. /**
  71488. * Removes all the elements in the container from the scene
  71489. * @param container contains the elements to remove
  71490. */
  71491. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  71492. // Nothing To Do Here. (directly attached to a light)
  71493. };
  71494. /**
  71495. * Rebuilds the elements related to this component in case of
  71496. * context lost for instance.
  71497. */
  71498. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  71499. // Nothing To Do Here.
  71500. };
  71501. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  71502. // Shadows
  71503. var scene = this.scene;
  71504. if (this.scene.shadowsEnabled) {
  71505. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  71506. var light = scene.lights[lightIndex];
  71507. var shadowGenerator = light.getShadowGenerator();
  71508. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  71509. var shadowMap = (shadowGenerator.getShadowMap());
  71510. if (scene.textures.indexOf(shadowMap) !== -1) {
  71511. renderTargets.push(shadowMap);
  71512. }
  71513. }
  71514. }
  71515. }
  71516. };
  71517. return ShadowGeneratorSceneComponent;
  71518. }());
  71519. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  71520. })(BABYLON || (BABYLON = {}));
  71521. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  71522. var BABYLON;
  71523. (function (BABYLON) {
  71524. var DefaultLoadingScreen = /** @class */ (function () {
  71525. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  71526. if (_loadingText === void 0) { _loadingText = ""; }
  71527. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  71528. var _this = this;
  71529. this._renderingCanvas = _renderingCanvas;
  71530. this._loadingText = _loadingText;
  71531. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  71532. // Resize
  71533. this._resizeLoadingUI = function () {
  71534. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  71535. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  71536. if (!_this._loadingDiv) {
  71537. return;
  71538. }
  71539. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  71540. _this._loadingDiv.style.left = canvasRect.left + "px";
  71541. _this._loadingDiv.style.top = canvasRect.top + "px";
  71542. _this._loadingDiv.style.width = canvasRect.width + "px";
  71543. _this._loadingDiv.style.height = canvasRect.height + "px";
  71544. };
  71545. }
  71546. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  71547. if (this._loadingDiv) {
  71548. // Do not add a loading screen if there is already one
  71549. return;
  71550. }
  71551. this._loadingDiv = document.createElement("div");
  71552. this._loadingDiv.id = "babylonjsLoadingDiv";
  71553. this._loadingDiv.style.opacity = "0";
  71554. this._loadingDiv.style.transition = "opacity 1.5s ease";
  71555. this._loadingDiv.style.pointerEvents = "none";
  71556. // Loading text
  71557. this._loadingTextDiv = document.createElement("div");
  71558. this._loadingTextDiv.style.position = "absolute";
  71559. this._loadingTextDiv.style.left = "0";
  71560. this._loadingTextDiv.style.top = "50%";
  71561. this._loadingTextDiv.style.marginTop = "80px";
  71562. this._loadingTextDiv.style.width = "100%";
  71563. this._loadingTextDiv.style.height = "20px";
  71564. this._loadingTextDiv.style.fontFamily = "Arial";
  71565. this._loadingTextDiv.style.fontSize = "14px";
  71566. this._loadingTextDiv.style.color = "white";
  71567. this._loadingTextDiv.style.textAlign = "center";
  71568. this._loadingTextDiv.innerHTML = "Loading";
  71569. this._loadingDiv.appendChild(this._loadingTextDiv);
  71570. //set the predefined text
  71571. this._loadingTextDiv.innerHTML = this._loadingText;
  71572. // Generating keyframes
  71573. var style = document.createElement('style');
  71574. style.type = 'text/css';
  71575. 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 }";
  71576. style.innerHTML = keyFrames;
  71577. document.getElementsByTagName('head')[0].appendChild(style);
  71578. // Loading img
  71579. var imgBack = new Image();
  71580. 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";
  71581. imgBack.style.position = "absolute";
  71582. imgBack.style.left = "50%";
  71583. imgBack.style.top = "50%";
  71584. imgBack.style.marginLeft = "-60px";
  71585. imgBack.style.marginTop = "-60px";
  71586. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  71587. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  71588. imgBack.style.transformOrigin = "50% 50%";
  71589. imgBack.style.webkitTransformOrigin = "50% 50%";
  71590. this._loadingDiv.appendChild(imgBack);
  71591. this._resizeLoadingUI();
  71592. window.addEventListener("resize", this._resizeLoadingUI);
  71593. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  71594. document.body.appendChild(this._loadingDiv);
  71595. this._loadingDiv.style.opacity = "1";
  71596. };
  71597. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  71598. var _this = this;
  71599. if (!this._loadingDiv) {
  71600. return;
  71601. }
  71602. var onTransitionEnd = function () {
  71603. if (!_this._loadingDiv) {
  71604. return;
  71605. }
  71606. document.body.removeChild(_this._loadingDiv);
  71607. window.removeEventListener("resize", _this._resizeLoadingUI);
  71608. _this._loadingDiv = null;
  71609. };
  71610. this._loadingDiv.style.opacity = "0";
  71611. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  71612. };
  71613. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  71614. set: function (text) {
  71615. this._loadingText = text;
  71616. if (this._loadingTextDiv) {
  71617. this._loadingTextDiv.innerHTML = this._loadingText;
  71618. }
  71619. },
  71620. enumerable: true,
  71621. configurable: true
  71622. });
  71623. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  71624. get: function () {
  71625. return this._loadingDivBackgroundColor;
  71626. },
  71627. set: function (color) {
  71628. this._loadingDivBackgroundColor = color;
  71629. if (!this._loadingDiv) {
  71630. return;
  71631. }
  71632. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  71633. },
  71634. enumerable: true,
  71635. configurable: true
  71636. });
  71637. return DefaultLoadingScreen;
  71638. }());
  71639. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  71640. })(BABYLON || (BABYLON = {}));
  71641. //# sourceMappingURL=babylon.loadingScreen.js.map
  71642. var BABYLON;
  71643. (function (BABYLON) {
  71644. var SceneLoaderProgressEvent = /** @class */ (function () {
  71645. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  71646. this.lengthComputable = lengthComputable;
  71647. this.loaded = loaded;
  71648. this.total = total;
  71649. }
  71650. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  71651. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  71652. };
  71653. return SceneLoaderProgressEvent;
  71654. }());
  71655. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  71656. var SceneLoader = /** @class */ (function () {
  71657. function SceneLoader() {
  71658. }
  71659. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  71660. get: function () {
  71661. return 0;
  71662. },
  71663. enumerable: true,
  71664. configurable: true
  71665. });
  71666. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  71667. get: function () {
  71668. return 1;
  71669. },
  71670. enumerable: true,
  71671. configurable: true
  71672. });
  71673. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  71674. get: function () {
  71675. return 2;
  71676. },
  71677. enumerable: true,
  71678. configurable: true
  71679. });
  71680. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  71681. get: function () {
  71682. return 3;
  71683. },
  71684. enumerable: true,
  71685. configurable: true
  71686. });
  71687. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  71688. get: function () {
  71689. return SceneLoader._ForceFullSceneLoadingForIncremental;
  71690. },
  71691. set: function (value) {
  71692. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  71693. },
  71694. enumerable: true,
  71695. configurable: true
  71696. });
  71697. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  71698. get: function () {
  71699. return SceneLoader._ShowLoadingScreen;
  71700. },
  71701. set: function (value) {
  71702. SceneLoader._ShowLoadingScreen = value;
  71703. },
  71704. enumerable: true,
  71705. configurable: true
  71706. });
  71707. Object.defineProperty(SceneLoader, "loggingLevel", {
  71708. get: function () {
  71709. return SceneLoader._loggingLevel;
  71710. },
  71711. set: function (value) {
  71712. SceneLoader._loggingLevel = value;
  71713. },
  71714. enumerable: true,
  71715. configurable: true
  71716. });
  71717. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  71718. get: function () {
  71719. return SceneLoader._CleanBoneMatrixWeights;
  71720. },
  71721. set: function (value) {
  71722. SceneLoader._CleanBoneMatrixWeights = value;
  71723. },
  71724. enumerable: true,
  71725. configurable: true
  71726. });
  71727. SceneLoader._getDefaultPlugin = function () {
  71728. return SceneLoader._registeredPlugins[".babylon"];
  71729. };
  71730. SceneLoader._getPluginForExtension = function (extension) {
  71731. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  71732. if (registeredPlugin) {
  71733. return registeredPlugin;
  71734. }
  71735. 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");
  71736. return SceneLoader._getDefaultPlugin();
  71737. };
  71738. SceneLoader._getPluginForDirectLoad = function (data) {
  71739. for (var extension in SceneLoader._registeredPlugins) {
  71740. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  71741. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  71742. return SceneLoader._registeredPlugins[extension];
  71743. }
  71744. }
  71745. return SceneLoader._getDefaultPlugin();
  71746. };
  71747. SceneLoader._getPluginForFilename = function (sceneFilename) {
  71748. var queryStringPosition = sceneFilename.indexOf("?");
  71749. if (queryStringPosition !== -1) {
  71750. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  71751. }
  71752. var dotPosition = sceneFilename.lastIndexOf(".");
  71753. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  71754. return SceneLoader._getPluginForExtension(extension);
  71755. };
  71756. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  71757. SceneLoader._getDirectLoad = function (sceneFilename) {
  71758. if (sceneFilename.substr(0, 5) === "data:") {
  71759. return sceneFilename.substr(5);
  71760. }
  71761. return null;
  71762. };
  71763. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  71764. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  71765. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  71766. var plugin;
  71767. if (registeredPlugin.plugin.createPlugin) {
  71768. plugin = registeredPlugin.plugin.createPlugin();
  71769. }
  71770. else {
  71771. plugin = registeredPlugin.plugin;
  71772. }
  71773. var useArrayBuffer = registeredPlugin.isBinary;
  71774. var database;
  71775. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  71776. var dataCallback = function (data, responseURL) {
  71777. if (scene.isDisposed) {
  71778. onError("Scene has been disposed");
  71779. return;
  71780. }
  71781. scene.database = database;
  71782. onSuccess(plugin, data, responseURL);
  71783. };
  71784. var request = null;
  71785. var pluginDisposed = false;
  71786. var onDisposeObservable = plugin.onDisposeObservable;
  71787. if (onDisposeObservable) {
  71788. onDisposeObservable.add(function () {
  71789. pluginDisposed = true;
  71790. if (request) {
  71791. request.abort();
  71792. request = null;
  71793. }
  71794. onDispose();
  71795. });
  71796. }
  71797. var manifestChecked = function () {
  71798. if (pluginDisposed) {
  71799. return;
  71800. }
  71801. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  71802. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  71803. } : undefined, database, useArrayBuffer, function (request, exception) {
  71804. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  71805. });
  71806. };
  71807. if (directLoad) {
  71808. dataCallback(directLoad);
  71809. return plugin;
  71810. }
  71811. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  71812. var engine = scene.getEngine();
  71813. var canUseOfflineSupport = engine.enableOfflineSupport;
  71814. if (canUseOfflineSupport) {
  71815. // Also check for exceptions
  71816. var exceptionFound = false;
  71817. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  71818. var regex = _a[_i];
  71819. if (regex.test(fileInfo.url)) {
  71820. exceptionFound = true;
  71821. break;
  71822. }
  71823. }
  71824. canUseOfflineSupport = !exceptionFound;
  71825. }
  71826. if (canUseOfflineSupport) {
  71827. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  71828. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  71829. }
  71830. else {
  71831. manifestChecked();
  71832. }
  71833. }
  71834. // Loading file from disk via input file or drag'n'drop
  71835. else {
  71836. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  71837. if (file) {
  71838. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  71839. }
  71840. else {
  71841. onError("Unable to find file named " + fileInfo.name);
  71842. }
  71843. }
  71844. return plugin;
  71845. };
  71846. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  71847. var url;
  71848. var name;
  71849. if (!sceneFilename) {
  71850. url = rootUrl;
  71851. name = BABYLON.Tools.GetFilename(rootUrl);
  71852. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71853. }
  71854. else {
  71855. if (sceneFilename.substr(0, 1) === "/") {
  71856. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71857. return null;
  71858. }
  71859. url = rootUrl + sceneFilename;
  71860. name = sceneFilename;
  71861. }
  71862. ;
  71863. return {
  71864. url: url,
  71865. rootUrl: rootUrl,
  71866. name: name
  71867. };
  71868. };
  71869. // Public functions
  71870. SceneLoader.GetPluginForExtension = function (extension) {
  71871. return SceneLoader._getPluginForExtension(extension).plugin;
  71872. };
  71873. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  71874. return !!SceneLoader._registeredPlugins[extension];
  71875. };
  71876. SceneLoader.RegisterPlugin = function (plugin) {
  71877. if (typeof plugin.extensions === "string") {
  71878. var extension = plugin.extensions;
  71879. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  71880. plugin: plugin,
  71881. isBinary: false
  71882. };
  71883. }
  71884. else {
  71885. var extensions = plugin.extensions;
  71886. Object.keys(extensions).forEach(function (extension) {
  71887. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  71888. plugin: plugin,
  71889. isBinary: extensions[extension].isBinary
  71890. };
  71891. });
  71892. }
  71893. };
  71894. /**
  71895. * Import meshes into a scene
  71896. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  71897. * @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)
  71898. * @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)
  71899. * @param scene the instance of BABYLON.Scene to append to
  71900. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  71901. * @param onProgress a callback with a progress event for each file being loaded
  71902. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71903. * @param pluginExtension the extension used to determine the plugin
  71904. * @returns The loaded plugin
  71905. */
  71906. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  71907. if (sceneFilename === void 0) { sceneFilename = ""; }
  71908. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71909. if (onSuccess === void 0) { onSuccess = null; }
  71910. if (onProgress === void 0) { onProgress = null; }
  71911. if (onError === void 0) { onError = null; }
  71912. if (pluginExtension === void 0) { pluginExtension = null; }
  71913. if (!scene) {
  71914. BABYLON.Tools.Error("No scene available to import mesh to");
  71915. return null;
  71916. }
  71917. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  71918. if (!fileInfo) {
  71919. return null;
  71920. }
  71921. var loadingToken = {};
  71922. scene._addPendingData(loadingToken);
  71923. var disposeHandler = function () {
  71924. scene._removePendingData(loadingToken);
  71925. };
  71926. var errorHandler = function (message, exception) {
  71927. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  71928. if (onError) {
  71929. onError(scene, errorMessage, exception);
  71930. }
  71931. else {
  71932. BABYLON.Tools.Error(errorMessage);
  71933. // should the exception be thrown?
  71934. }
  71935. disposeHandler();
  71936. };
  71937. var progressHandler = onProgress ? function (event) {
  71938. try {
  71939. onProgress(event);
  71940. }
  71941. catch (e) {
  71942. errorHandler("Error in onProgress callback", e);
  71943. }
  71944. } : undefined;
  71945. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  71946. scene.importedMeshesFiles.push(fileInfo.url);
  71947. if (onSuccess) {
  71948. try {
  71949. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  71950. }
  71951. catch (e) {
  71952. errorHandler("Error in onSuccess callback", e);
  71953. }
  71954. }
  71955. scene._removePendingData(loadingToken);
  71956. };
  71957. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  71958. if (plugin.rewriteRootURL) {
  71959. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  71960. }
  71961. if (plugin.importMesh) {
  71962. var syncedPlugin = plugin;
  71963. var meshes = new Array();
  71964. var particleSystems = new Array();
  71965. var skeletons = new Array();
  71966. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  71967. return;
  71968. }
  71969. scene.loadingPluginName = plugin.name;
  71970. successHandler(meshes, particleSystems, skeletons, []);
  71971. }
  71972. else {
  71973. var asyncedPlugin = plugin;
  71974. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  71975. scene.loadingPluginName = plugin.name;
  71976. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  71977. }).catch(function (error) {
  71978. errorHandler(error.message, error);
  71979. });
  71980. }
  71981. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  71982. };
  71983. /**
  71984. * Import meshes into a scene
  71985. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  71986. * @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)
  71987. * @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)
  71988. * @param scene the instance of BABYLON.Scene to append to
  71989. * @param onProgress a callback with a progress event for each file being loaded
  71990. * @param pluginExtension the extension used to determine the plugin
  71991. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  71992. */
  71993. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  71994. if (sceneFilename === void 0) { sceneFilename = ""; }
  71995. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71996. if (onProgress === void 0) { onProgress = null; }
  71997. if (pluginExtension === void 0) { pluginExtension = null; }
  71998. return new Promise(function (resolve, reject) {
  71999. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  72000. resolve({
  72001. meshes: meshes,
  72002. particleSystems: particleSystems,
  72003. skeletons: skeletons,
  72004. animationGroups: animationGroups
  72005. });
  72006. }, onProgress, function (scene, message, exception) {
  72007. reject(exception || new Error(message));
  72008. }, pluginExtension);
  72009. });
  72010. };
  72011. /**
  72012. * Load a scene
  72013. * @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)
  72014. * @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)
  72015. * @param engine is the instance of BABYLON.Engine to use to create the scene
  72016. * @param onSuccess a callback with the scene when import succeeds
  72017. * @param onProgress a callback with a progress event for each file being loaded
  72018. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  72019. * @param pluginExtension the extension used to determine the plugin
  72020. * @returns The loaded plugin
  72021. */
  72022. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  72023. if (onSuccess === void 0) { onSuccess = null; }
  72024. if (onProgress === void 0) { onProgress = null; }
  72025. if (onError === void 0) { onError = null; }
  72026. if (pluginExtension === void 0) { pluginExtension = null; }
  72027. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  72028. };
  72029. /**
  72030. * Load a scene
  72031. * @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)
  72032. * @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)
  72033. * @param engine is the instance of BABYLON.Engine to use to create the scene
  72034. * @param onProgress a callback with a progress event for each file being loaded
  72035. * @param pluginExtension the extension used to determine the plugin
  72036. * @returns The loaded scene
  72037. */
  72038. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  72039. if (onProgress === void 0) { onProgress = null; }
  72040. if (pluginExtension === void 0) { pluginExtension = null; }
  72041. return new Promise(function (resolve, reject) {
  72042. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  72043. resolve(scene);
  72044. }, onProgress, function (scene, message, exception) {
  72045. reject(exception || new Error(message));
  72046. }, pluginExtension);
  72047. });
  72048. };
  72049. /**
  72050. * Append a scene
  72051. * @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)
  72052. * @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)
  72053. * @param scene is the instance of BABYLON.Scene to append to
  72054. * @param onSuccess a callback with the scene when import succeeds
  72055. * @param onProgress a callback with a progress event for each file being loaded
  72056. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  72057. * @param pluginExtension the extension used to determine the plugin
  72058. * @returns The loaded plugin
  72059. */
  72060. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  72061. if (sceneFilename === void 0) { sceneFilename = ""; }
  72062. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72063. if (onSuccess === void 0) { onSuccess = null; }
  72064. if (onProgress === void 0) { onProgress = null; }
  72065. if (onError === void 0) { onError = null; }
  72066. if (pluginExtension === void 0) { pluginExtension = null; }
  72067. if (!scene) {
  72068. BABYLON.Tools.Error("No scene available to append to");
  72069. return null;
  72070. }
  72071. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  72072. if (!fileInfo) {
  72073. return null;
  72074. }
  72075. if (SceneLoader.ShowLoadingScreen) {
  72076. scene.getEngine().displayLoadingUI();
  72077. }
  72078. var loadingToken = {};
  72079. scene._addPendingData(loadingToken);
  72080. var disposeHandler = function () {
  72081. scene._removePendingData(loadingToken);
  72082. scene.getEngine().hideLoadingUI();
  72083. };
  72084. var errorHandler = function (message, exception) {
  72085. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  72086. if (onError) {
  72087. onError(scene, errorMessage, exception);
  72088. }
  72089. else {
  72090. BABYLON.Tools.Error(errorMessage);
  72091. // should the exception be thrown?
  72092. }
  72093. disposeHandler();
  72094. };
  72095. var progressHandler = onProgress ? function (event) {
  72096. try {
  72097. onProgress(event);
  72098. }
  72099. catch (e) {
  72100. errorHandler("Error in onProgress callback", e);
  72101. }
  72102. } : undefined;
  72103. var successHandler = function () {
  72104. if (onSuccess) {
  72105. try {
  72106. onSuccess(scene);
  72107. }
  72108. catch (e) {
  72109. errorHandler("Error in onSuccess callback", e);
  72110. }
  72111. }
  72112. scene._removePendingData(loadingToken);
  72113. };
  72114. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  72115. if (plugin.load) {
  72116. var syncedPlugin = plugin;
  72117. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  72118. return;
  72119. }
  72120. scene.loadingPluginName = plugin.name;
  72121. successHandler();
  72122. }
  72123. else {
  72124. var asyncedPlugin = plugin;
  72125. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  72126. scene.loadingPluginName = plugin.name;
  72127. successHandler();
  72128. }).catch(function (error) {
  72129. errorHandler(error.message, error);
  72130. });
  72131. }
  72132. if (SceneLoader.ShowLoadingScreen) {
  72133. scene.executeWhenReady(function () {
  72134. scene.getEngine().hideLoadingUI();
  72135. });
  72136. }
  72137. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  72138. };
  72139. /**
  72140. * Append a scene
  72141. * @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)
  72142. * @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)
  72143. * @param scene is the instance of BABYLON.Scene to append to
  72144. * @param onProgress a callback with a progress event for each file being loaded
  72145. * @param pluginExtension the extension used to determine the plugin
  72146. * @returns The given scene
  72147. */
  72148. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  72149. if (sceneFilename === void 0) { sceneFilename = ""; }
  72150. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72151. if (onProgress === void 0) { onProgress = null; }
  72152. if (pluginExtension === void 0) { pluginExtension = null; }
  72153. return new Promise(function (resolve, reject) {
  72154. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  72155. resolve(scene);
  72156. }, onProgress, function (scene, message, exception) {
  72157. reject(exception || new Error(message));
  72158. }, pluginExtension);
  72159. });
  72160. };
  72161. /**
  72162. * Load a scene into an asset container
  72163. * @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)
  72164. * @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)
  72165. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  72166. * @param onSuccess a callback with the scene when import succeeds
  72167. * @param onProgress a callback with a progress event for each file being loaded
  72168. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  72169. * @param pluginExtension the extension used to determine the plugin
  72170. * @returns The loaded plugin
  72171. */
  72172. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  72173. if (sceneFilename === void 0) { sceneFilename = ""; }
  72174. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72175. if (onSuccess === void 0) { onSuccess = null; }
  72176. if (onProgress === void 0) { onProgress = null; }
  72177. if (onError === void 0) { onError = null; }
  72178. if (pluginExtension === void 0) { pluginExtension = null; }
  72179. if (!scene) {
  72180. BABYLON.Tools.Error("No scene available to load asset container to");
  72181. return null;
  72182. }
  72183. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  72184. if (!fileInfo) {
  72185. return null;
  72186. }
  72187. var loadingToken = {};
  72188. scene._addPendingData(loadingToken);
  72189. var disposeHandler = function () {
  72190. scene._removePendingData(loadingToken);
  72191. };
  72192. var errorHandler = function (message, exception) {
  72193. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  72194. if (onError) {
  72195. onError(scene, errorMessage, exception);
  72196. }
  72197. else {
  72198. BABYLON.Tools.Error(errorMessage);
  72199. // should the exception be thrown?
  72200. }
  72201. disposeHandler();
  72202. };
  72203. var progressHandler = onProgress ? function (event) {
  72204. try {
  72205. onProgress(event);
  72206. }
  72207. catch (e) {
  72208. errorHandler("Error in onProgress callback", e);
  72209. }
  72210. } : undefined;
  72211. var successHandler = function (assets) {
  72212. if (onSuccess) {
  72213. try {
  72214. onSuccess(assets);
  72215. }
  72216. catch (e) {
  72217. errorHandler("Error in onSuccess callback", e);
  72218. }
  72219. }
  72220. scene._removePendingData(loadingToken);
  72221. };
  72222. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  72223. if (plugin.loadAssetContainer) {
  72224. var syncedPlugin = plugin;
  72225. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  72226. if (!assetContainer) {
  72227. return;
  72228. }
  72229. scene.loadingPluginName = plugin.name;
  72230. successHandler(assetContainer);
  72231. }
  72232. else if (plugin.loadAssetContainerAsync) {
  72233. var asyncedPlugin = plugin;
  72234. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  72235. scene.loadingPluginName = plugin.name;
  72236. successHandler(assetContainer);
  72237. }).catch(function (error) {
  72238. errorHandler(error.message, error);
  72239. });
  72240. }
  72241. else {
  72242. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  72243. }
  72244. if (SceneLoader.ShowLoadingScreen) {
  72245. scene.executeWhenReady(function () {
  72246. scene.getEngine().hideLoadingUI();
  72247. });
  72248. }
  72249. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  72250. };
  72251. /**
  72252. * Load a scene into an asset container
  72253. * @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)
  72254. * @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)
  72255. * @param scene is the instance of BABYLON.Scene to append to
  72256. * @param onProgress a callback with a progress event for each file being loaded
  72257. * @param pluginExtension the extension used to determine the plugin
  72258. * @returns The loaded asset container
  72259. */
  72260. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  72261. if (sceneFilename === void 0) { sceneFilename = ""; }
  72262. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  72263. if (onProgress === void 0) { onProgress = null; }
  72264. if (pluginExtension === void 0) { pluginExtension = null; }
  72265. return new Promise(function (resolve, reject) {
  72266. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  72267. resolve(assetContainer);
  72268. }, onProgress, function (scene, message, exception) {
  72269. reject(exception || new Error(message));
  72270. }, pluginExtension);
  72271. });
  72272. };
  72273. // Flags
  72274. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  72275. SceneLoader._ShowLoadingScreen = true;
  72276. SceneLoader._CleanBoneMatrixWeights = false;
  72277. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  72278. // Members
  72279. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  72280. SceneLoader._registeredPlugins = {};
  72281. return SceneLoader;
  72282. }());
  72283. BABYLON.SceneLoader = SceneLoader;
  72284. ;
  72285. })(BABYLON || (BABYLON = {}));
  72286. //# sourceMappingURL=babylon.sceneLoader.js.map
  72287. var BABYLON;
  72288. (function (BABYLON) {
  72289. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  72290. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  72291. var parsedMaterial = parsedData.materials[index];
  72292. if (parsedMaterial.id === id) {
  72293. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  72294. }
  72295. }
  72296. return null;
  72297. };
  72298. var isDescendantOf = function (mesh, names, hierarchyIds) {
  72299. for (var i in names) {
  72300. if (mesh.name === names[i]) {
  72301. hierarchyIds.push(mesh.id);
  72302. return true;
  72303. }
  72304. }
  72305. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  72306. hierarchyIds.push(mesh.id);
  72307. return true;
  72308. }
  72309. return false;
  72310. };
  72311. var logOperation = function (operation, producer) {
  72312. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  72313. };
  72314. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  72315. if (addToScene === void 0) { addToScene = false; }
  72316. var container = new BABYLON.AssetContainer(scene);
  72317. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72318. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72319. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72320. // and avoid problems with multiple concurrent .babylon loads.
  72321. var log = "importScene has failed JSON parse";
  72322. try {
  72323. var parsedData = JSON.parse(data);
  72324. log = "";
  72325. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  72326. var index;
  72327. var cache;
  72328. // Lights
  72329. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  72330. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  72331. var parsedLight = parsedData.lights[index];
  72332. var light = BABYLON.Light.Parse(parsedLight, scene);
  72333. if (light) {
  72334. container.lights.push(light);
  72335. log += (index === 0 ? "\n\tLights:" : "");
  72336. log += "\n\t\t" + light.toString(fullDetails);
  72337. }
  72338. }
  72339. }
  72340. // Animations
  72341. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  72342. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  72343. var parsedAnimation = parsedData.animations[index];
  72344. var animation = BABYLON.Animation.Parse(parsedAnimation);
  72345. scene.animations.push(animation);
  72346. container.animations.push(animation);
  72347. log += (index === 0 ? "\n\tAnimations:" : "");
  72348. log += "\n\t\t" + animation.toString(fullDetails);
  72349. }
  72350. }
  72351. // Materials
  72352. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  72353. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  72354. var parsedMaterial = parsedData.materials[index];
  72355. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  72356. container.materials.push(mat);
  72357. log += (index === 0 ? "\n\tMaterials:" : "");
  72358. log += "\n\t\t" + mat.toString(fullDetails);
  72359. }
  72360. }
  72361. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  72362. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  72363. var parsedMultiMaterial = parsedData.multiMaterials[index];
  72364. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  72365. container.multiMaterials.push(mmat);
  72366. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  72367. log += "\n\t\t" + mmat.toString(fullDetails);
  72368. }
  72369. }
  72370. // Morph targets
  72371. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  72372. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  72373. var managerData = _a[_i];
  72374. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  72375. }
  72376. }
  72377. // Skeletons
  72378. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  72379. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  72380. var parsedSkeleton = parsedData.skeletons[index];
  72381. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  72382. container.skeletons.push(skeleton);
  72383. log += (index === 0 ? "\n\tSkeletons:" : "");
  72384. log += "\n\t\t" + skeleton.toString(fullDetails);
  72385. }
  72386. }
  72387. // Geometries
  72388. var geometries = parsedData.geometries;
  72389. if (geometries !== undefined && geometries !== null) {
  72390. var addedGeometry = new Array();
  72391. // Boxes
  72392. var boxes = geometries.boxes;
  72393. if (boxes !== undefined && boxes !== null) {
  72394. for (index = 0, cache = boxes.length; index < cache; index++) {
  72395. var parsedBox = boxes[index];
  72396. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  72397. }
  72398. }
  72399. // Spheres
  72400. var spheres = geometries.spheres;
  72401. if (spheres !== undefined && spheres !== null) {
  72402. for (index = 0, cache = spheres.length; index < cache; index++) {
  72403. var parsedSphere = spheres[index];
  72404. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  72405. }
  72406. }
  72407. // Cylinders
  72408. var cylinders = geometries.cylinders;
  72409. if (cylinders !== undefined && cylinders !== null) {
  72410. for (index = 0, cache = cylinders.length; index < cache; index++) {
  72411. var parsedCylinder = cylinders[index];
  72412. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  72413. }
  72414. }
  72415. // Toruses
  72416. var toruses = geometries.toruses;
  72417. if (toruses !== undefined && toruses !== null) {
  72418. for (index = 0, cache = toruses.length; index < cache; index++) {
  72419. var parsedTorus = toruses[index];
  72420. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  72421. }
  72422. }
  72423. // Grounds
  72424. var grounds = geometries.grounds;
  72425. if (grounds !== undefined && grounds !== null) {
  72426. for (index = 0, cache = grounds.length; index < cache; index++) {
  72427. var parsedGround = grounds[index];
  72428. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  72429. }
  72430. }
  72431. // Planes
  72432. var planes = geometries.planes;
  72433. if (planes !== undefined && planes !== null) {
  72434. for (index = 0, cache = planes.length; index < cache; index++) {
  72435. var parsedPlane = planes[index];
  72436. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  72437. }
  72438. }
  72439. // TorusKnots
  72440. var torusKnots = geometries.torusKnots;
  72441. if (torusKnots !== undefined && torusKnots !== null) {
  72442. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  72443. var parsedTorusKnot = torusKnots[index];
  72444. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  72445. }
  72446. }
  72447. // VertexData
  72448. var vertexData = geometries.vertexData;
  72449. if (vertexData !== undefined && vertexData !== null) {
  72450. for (index = 0, cache = vertexData.length; index < cache; index++) {
  72451. var parsedVertexData = vertexData[index];
  72452. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  72453. }
  72454. }
  72455. addedGeometry.forEach(function (g) {
  72456. if (g) {
  72457. container.geometries.push(g);
  72458. }
  72459. });
  72460. }
  72461. // Transform nodes
  72462. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  72463. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  72464. var parsedTransformNode = parsedData.transformNodes[index];
  72465. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  72466. container.transformNodes.push(node);
  72467. }
  72468. }
  72469. // Meshes
  72470. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  72471. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  72472. var parsedMesh = parsedData.meshes[index];
  72473. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  72474. container.meshes.push(mesh);
  72475. log += (index === 0 ? "\n\tMeshes:" : "");
  72476. log += "\n\t\t" + mesh.toString(fullDetails);
  72477. }
  72478. }
  72479. // Cameras
  72480. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  72481. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  72482. var parsedCamera = parsedData.cameras[index];
  72483. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  72484. container.cameras.push(camera);
  72485. log += (index === 0 ? "\n\tCameras:" : "");
  72486. log += "\n\t\t" + camera.toString(fullDetails);
  72487. }
  72488. }
  72489. // Animation Groups
  72490. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  72491. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  72492. var parsedAnimationGroup = parsedData.animationGroups[index];
  72493. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  72494. container.animationGroups.push(animationGroup);
  72495. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  72496. log += "\n\t\t" + animationGroup.toString(fullDetails);
  72497. }
  72498. }
  72499. // Browsing all the graph to connect the dots
  72500. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  72501. var camera = scene.cameras[index];
  72502. if (camera._waitingParentId) {
  72503. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  72504. camera._waitingParentId = null;
  72505. }
  72506. }
  72507. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  72508. var light_1 = scene.lights[index];
  72509. if (light_1 && light_1._waitingParentId) {
  72510. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  72511. light_1._waitingParentId = null;
  72512. }
  72513. }
  72514. // Connect parents & children and parse actions
  72515. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  72516. var transformNode = scene.transformNodes[index];
  72517. if (transformNode._waitingParentId) {
  72518. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  72519. transformNode._waitingParentId = null;
  72520. }
  72521. }
  72522. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72523. var mesh = scene.meshes[index];
  72524. if (mesh._waitingParentId) {
  72525. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  72526. mesh._waitingParentId = null;
  72527. }
  72528. if (mesh._waitingActions) {
  72529. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  72530. mesh._waitingActions = null;
  72531. }
  72532. }
  72533. // freeze world matrix application
  72534. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72535. var currentMesh = scene.meshes[index];
  72536. if (currentMesh._waitingFreezeWorldMatrix) {
  72537. currentMesh.freezeWorldMatrix();
  72538. currentMesh._waitingFreezeWorldMatrix = null;
  72539. }
  72540. else {
  72541. currentMesh.computeWorldMatrix(true);
  72542. }
  72543. }
  72544. // Lights exclusions / inclusions
  72545. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  72546. var light_2 = scene.lights[index];
  72547. // Excluded check
  72548. if (light_2._excludedMeshesIds.length > 0) {
  72549. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  72550. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  72551. if (excludedMesh) {
  72552. light_2.excludedMeshes.push(excludedMesh);
  72553. }
  72554. }
  72555. light_2._excludedMeshesIds = [];
  72556. }
  72557. // Included check
  72558. if (light_2._includedOnlyMeshesIds.length > 0) {
  72559. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  72560. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  72561. if (includedOnlyMesh) {
  72562. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  72563. }
  72564. }
  72565. light_2._includedOnlyMeshesIds = [];
  72566. }
  72567. }
  72568. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  72569. // Actions (scene)
  72570. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  72571. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  72572. }
  72573. if (!addToScene) {
  72574. container.removeAllFromScene();
  72575. }
  72576. }
  72577. catch (err) {
  72578. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  72579. if (onError) {
  72580. onError(msg, err);
  72581. }
  72582. else {
  72583. BABYLON.Tools.Log(msg);
  72584. throw err;
  72585. }
  72586. }
  72587. finally {
  72588. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72589. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72590. }
  72591. }
  72592. return container;
  72593. };
  72594. BABYLON.SceneLoader.RegisterPlugin({
  72595. name: "babylon.js",
  72596. extensions: ".babylon",
  72597. canDirectLoad: function (data) {
  72598. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  72599. return true;
  72600. }
  72601. return false;
  72602. },
  72603. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  72604. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72605. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72606. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72607. // and avoid problems with multiple concurrent .babylon loads.
  72608. var log = "importMesh has failed JSON parse";
  72609. try {
  72610. var parsedData = JSON.parse(data);
  72611. log = "";
  72612. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  72613. if (!meshesNames) {
  72614. meshesNames = null;
  72615. }
  72616. else if (!Array.isArray(meshesNames)) {
  72617. meshesNames = [meshesNames];
  72618. }
  72619. var hierarchyIds = new Array();
  72620. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  72621. var loadedSkeletonsIds = [];
  72622. var loadedMaterialsIds = [];
  72623. var index;
  72624. var cache;
  72625. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  72626. var parsedMesh = parsedData.meshes[index];
  72627. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  72628. if (meshesNames !== null) {
  72629. // Remove found mesh name from list.
  72630. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  72631. }
  72632. //Geometry?
  72633. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  72634. //does the file contain geometries?
  72635. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  72636. //find the correct geometry and add it to the scene
  72637. var found = false;
  72638. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  72639. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  72640. return;
  72641. }
  72642. else {
  72643. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  72644. if (parsedGeometryData.id === parsedMesh.geometryId) {
  72645. switch (geometryType) {
  72646. case "boxes":
  72647. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  72648. break;
  72649. case "spheres":
  72650. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  72651. break;
  72652. case "cylinders":
  72653. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  72654. break;
  72655. case "toruses":
  72656. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  72657. break;
  72658. case "grounds":
  72659. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  72660. break;
  72661. case "planes":
  72662. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  72663. break;
  72664. case "torusKnots":
  72665. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  72666. break;
  72667. case "vertexData":
  72668. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  72669. break;
  72670. }
  72671. found = true;
  72672. }
  72673. });
  72674. }
  72675. });
  72676. if (found === false) {
  72677. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  72678. }
  72679. }
  72680. }
  72681. // Material ?
  72682. if (parsedMesh.materialId) {
  72683. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  72684. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  72685. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  72686. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  72687. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  72688. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  72689. var subMatId = parsedMultiMaterial.materials[matIndex];
  72690. loadedMaterialsIds.push(subMatId);
  72691. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  72692. if (mat) {
  72693. log += "\n\tMaterial " + mat.toString(fullDetails);
  72694. }
  72695. }
  72696. loadedMaterialsIds.push(parsedMultiMaterial.id);
  72697. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  72698. if (mmat) {
  72699. materialFound = true;
  72700. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  72701. }
  72702. break;
  72703. }
  72704. }
  72705. }
  72706. if (materialFound === false) {
  72707. loadedMaterialsIds.push(parsedMesh.materialId);
  72708. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  72709. if (!mat) {
  72710. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  72711. }
  72712. else {
  72713. log += "\n\tMaterial " + mat.toString(fullDetails);
  72714. }
  72715. }
  72716. }
  72717. // Skeleton ?
  72718. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  72719. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  72720. if (skeletonAlreadyLoaded === false) {
  72721. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  72722. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  72723. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  72724. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  72725. skeletons.push(skeleton);
  72726. loadedSkeletonsIds.push(parsedSkeleton.id);
  72727. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  72728. }
  72729. }
  72730. }
  72731. }
  72732. // Morph targets ?
  72733. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  72734. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  72735. var managerData = _a[_i];
  72736. BABYLON.MorphTargetManager.Parse(managerData, scene);
  72737. }
  72738. }
  72739. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  72740. meshes.push(mesh);
  72741. log += "\n\tMesh " + mesh.toString(fullDetails);
  72742. }
  72743. }
  72744. // Connecting parents
  72745. var currentMesh;
  72746. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72747. currentMesh = scene.meshes[index];
  72748. if (currentMesh._waitingParentId) {
  72749. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  72750. currentMesh._waitingParentId = null;
  72751. }
  72752. }
  72753. // freeze and compute world matrix application
  72754. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72755. currentMesh = scene.meshes[index];
  72756. if (currentMesh._waitingFreezeWorldMatrix) {
  72757. currentMesh.freezeWorldMatrix();
  72758. currentMesh._waitingFreezeWorldMatrix = null;
  72759. }
  72760. else {
  72761. currentMesh.computeWorldMatrix(true);
  72762. }
  72763. }
  72764. }
  72765. // Particles
  72766. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  72767. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  72768. if (parser) {
  72769. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  72770. var parsedParticleSystem = parsedData.particleSystems[index];
  72771. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  72772. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  72773. }
  72774. }
  72775. }
  72776. }
  72777. return true;
  72778. }
  72779. catch (err) {
  72780. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  72781. if (onError) {
  72782. onError(msg, err);
  72783. }
  72784. else {
  72785. BABYLON.Tools.Log(msg);
  72786. throw err;
  72787. }
  72788. }
  72789. finally {
  72790. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72791. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72792. }
  72793. }
  72794. return false;
  72795. },
  72796. load: function (scene, data, rootUrl, onError) {
  72797. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72798. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72799. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72800. // and avoid problems with multiple concurrent .babylon loads.
  72801. var log = "importScene has failed JSON parse";
  72802. try {
  72803. var parsedData = JSON.parse(data);
  72804. log = "";
  72805. // Scene
  72806. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  72807. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  72808. }
  72809. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  72810. scene.autoClear = parsedData.autoClear;
  72811. }
  72812. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  72813. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  72814. }
  72815. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  72816. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  72817. }
  72818. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  72819. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  72820. }
  72821. // Fog
  72822. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  72823. scene.fogMode = parsedData.fogMode;
  72824. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  72825. scene.fogStart = parsedData.fogStart;
  72826. scene.fogEnd = parsedData.fogEnd;
  72827. scene.fogDensity = parsedData.fogDensity;
  72828. log += "\tFog mode for scene: ";
  72829. switch (scene.fogMode) {
  72830. // getters not compiling, so using hardcoded
  72831. case 1:
  72832. log += "exp\n";
  72833. break;
  72834. case 2:
  72835. log += "exp2\n";
  72836. break;
  72837. case 3:
  72838. log += "linear\n";
  72839. break;
  72840. }
  72841. }
  72842. //Physics
  72843. if (parsedData.physicsEnabled) {
  72844. var physicsPlugin;
  72845. if (parsedData.physicsEngine === "cannon") {
  72846. physicsPlugin = new BABYLON.CannonJSPlugin();
  72847. }
  72848. else if (parsedData.physicsEngine === "oimo") {
  72849. physicsPlugin = new BABYLON.OimoJSPlugin();
  72850. }
  72851. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  72852. //else - default engine, which is currently oimo
  72853. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  72854. scene.enablePhysics(physicsGravity, physicsPlugin);
  72855. }
  72856. // Metadata
  72857. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  72858. scene.metadata = parsedData.metadata;
  72859. }
  72860. //collisions, if defined. otherwise, default is true
  72861. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  72862. scene.collisionsEnabled = parsedData.collisionsEnabled;
  72863. }
  72864. scene.workerCollisions = !!parsedData.workerCollisions;
  72865. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  72866. if (!container) {
  72867. return false;
  72868. }
  72869. if (parsedData.autoAnimate) {
  72870. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  72871. }
  72872. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  72873. scene.setActiveCameraByID(parsedData.activeCameraID);
  72874. }
  72875. // Environment texture
  72876. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  72877. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  72878. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  72879. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  72880. if (parsedData.environmentTextureRotationY) {
  72881. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  72882. }
  72883. scene.environmentTexture = hdrTexture;
  72884. }
  72885. else {
  72886. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  72887. if (parsedData.environmentTextureRotationY) {
  72888. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  72889. }
  72890. scene.environmentTexture = cubeTexture;
  72891. }
  72892. if (parsedData.createDefaultSkybox === true) {
  72893. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  72894. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  72895. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  72896. }
  72897. }
  72898. // Finish
  72899. return true;
  72900. }
  72901. catch (err) {
  72902. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  72903. if (onError) {
  72904. onError(msg, err);
  72905. }
  72906. else {
  72907. BABYLON.Tools.Log(msg);
  72908. throw err;
  72909. }
  72910. }
  72911. finally {
  72912. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72913. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72914. }
  72915. }
  72916. return false;
  72917. },
  72918. loadAssetContainer: function (scene, data, rootUrl, onError) {
  72919. var container = loadAssetContainer(scene, data, rootUrl, onError);
  72920. return container;
  72921. }
  72922. });
  72923. })(BABYLON || (BABYLON = {}));
  72924. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  72925. var BABYLON;
  72926. (function (BABYLON) {
  72927. var FilesInput = /** @class */ (function () {
  72928. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  72929. this.onProcessFileCallback = function () { return true; };
  72930. this._engine = engine;
  72931. this._currentScene = scene;
  72932. this._sceneLoadedCallback = sceneLoadedCallback;
  72933. this._progressCallback = progressCallback;
  72934. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  72935. this._textureLoadingCallback = textureLoadingCallback;
  72936. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  72937. this._onReloadCallback = onReloadCallback;
  72938. this._errorCallback = errorCallback;
  72939. }
  72940. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  72941. var _this = this;
  72942. if (elementToMonitor) {
  72943. this._elementToMonitor = elementToMonitor;
  72944. this._dragEnterHandler = function (e) { _this.drag(e); };
  72945. this._dragOverHandler = function (e) { _this.drag(e); };
  72946. this._dropHandler = function (e) { _this.drop(e); };
  72947. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  72948. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  72949. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  72950. }
  72951. };
  72952. FilesInput.prototype.dispose = function () {
  72953. if (!this._elementToMonitor) {
  72954. return;
  72955. }
  72956. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  72957. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  72958. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  72959. };
  72960. FilesInput.prototype.renderFunction = function () {
  72961. if (this._additionalRenderLoopLogicCallback) {
  72962. this._additionalRenderLoopLogicCallback();
  72963. }
  72964. if (this._currentScene) {
  72965. if (this._textureLoadingCallback) {
  72966. var remaining = this._currentScene.getWaitingItemsCount();
  72967. if (remaining > 0) {
  72968. this._textureLoadingCallback(remaining);
  72969. }
  72970. }
  72971. this._currentScene.render();
  72972. }
  72973. };
  72974. FilesInput.prototype.drag = function (e) {
  72975. e.stopPropagation();
  72976. e.preventDefault();
  72977. };
  72978. FilesInput.prototype.drop = function (eventDrop) {
  72979. eventDrop.stopPropagation();
  72980. eventDrop.preventDefault();
  72981. this.loadFiles(eventDrop);
  72982. };
  72983. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  72984. var _this = this;
  72985. var reader = folder.createReader();
  72986. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  72987. reader.readEntries(function (entries) {
  72988. remaining.count += entries.length;
  72989. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  72990. var entry = entries_1[_i];
  72991. if (entry.isFile) {
  72992. entry.file(function (file) {
  72993. file.correctName = relativePath + file.name;
  72994. files.push(file);
  72995. if (--remaining.count === 0) {
  72996. callback();
  72997. }
  72998. });
  72999. }
  73000. else if (entry.isDirectory) {
  73001. _this._traverseFolder(entry, files, remaining, callback);
  73002. }
  73003. }
  73004. if (--remaining.count) {
  73005. callback();
  73006. }
  73007. });
  73008. };
  73009. FilesInput.prototype._processFiles = function (files) {
  73010. for (var i = 0; i < files.length; i++) {
  73011. var name = files[i].correctName.toLowerCase();
  73012. var extension = name.split('.').pop();
  73013. if (!this.onProcessFileCallback(files[i], name, extension)) {
  73014. continue;
  73015. }
  73016. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  73017. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  73018. this._sceneFileToLoad = files[i];
  73019. }
  73020. FilesInput.FilesToLoad[name] = files[i];
  73021. }
  73022. };
  73023. FilesInput.prototype.loadFiles = function (event) {
  73024. var _this = this;
  73025. // Handling data transfer via drag'n'drop
  73026. if (event && event.dataTransfer && event.dataTransfer.files) {
  73027. this._filesToLoad = event.dataTransfer.files;
  73028. }
  73029. // Handling files from input files
  73030. if (event && event.target && event.target.files) {
  73031. this._filesToLoad = event.target.files;
  73032. }
  73033. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  73034. return;
  73035. }
  73036. if (this._startingProcessingFilesCallback) {
  73037. this._startingProcessingFilesCallback(this._filesToLoad);
  73038. }
  73039. if (this._filesToLoad && this._filesToLoad.length > 0) {
  73040. var files_1 = new Array();
  73041. var folders = [];
  73042. var items = event.dataTransfer ? event.dataTransfer.items : null;
  73043. for (var i = 0; i < this._filesToLoad.length; i++) {
  73044. var fileToLoad = this._filesToLoad[i];
  73045. var name_1 = fileToLoad.name.toLowerCase();
  73046. var entry = void 0;
  73047. fileToLoad.correctName = name_1;
  73048. if (items) {
  73049. var item = items[i];
  73050. if (item.getAsEntry) {
  73051. entry = item.getAsEntry();
  73052. }
  73053. else if (item.webkitGetAsEntry) {
  73054. entry = item.webkitGetAsEntry();
  73055. }
  73056. }
  73057. if (!entry) {
  73058. files_1.push(fileToLoad);
  73059. }
  73060. else {
  73061. if (entry.isDirectory) {
  73062. folders.push(entry);
  73063. }
  73064. else {
  73065. files_1.push(fileToLoad);
  73066. }
  73067. }
  73068. }
  73069. if (folders.length === 0) {
  73070. this._processFiles(files_1);
  73071. this._processReload();
  73072. }
  73073. else {
  73074. var remaining = { count: folders.length };
  73075. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  73076. var folder = folders_1[_i];
  73077. this._traverseFolder(folder, files_1, remaining, function () {
  73078. _this._processFiles(files_1);
  73079. if (remaining.count === 0) {
  73080. _this._processReload();
  73081. }
  73082. });
  73083. }
  73084. }
  73085. }
  73086. };
  73087. FilesInput.prototype._processReload = function () {
  73088. if (this._onReloadCallback) {
  73089. this._onReloadCallback(this._sceneFileToLoad);
  73090. }
  73091. else {
  73092. this.reload();
  73093. }
  73094. };
  73095. FilesInput.prototype.reload = function () {
  73096. var _this = this;
  73097. // If a scene file has been provided
  73098. if (this._sceneFileToLoad) {
  73099. if (this._currentScene) {
  73100. if (BABYLON.Tools.errorsCount > 0) {
  73101. BABYLON.Tools.ClearLogCache();
  73102. }
  73103. this._engine.stopRenderLoop();
  73104. }
  73105. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  73106. if (_this._progressCallback) {
  73107. _this._progressCallback(progress);
  73108. }
  73109. }).then(function (scene) {
  73110. if (_this._currentScene) {
  73111. _this._currentScene.dispose();
  73112. }
  73113. _this._currentScene = scene;
  73114. if (_this._sceneLoadedCallback) {
  73115. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  73116. }
  73117. // Wait for textures and shaders to be ready
  73118. _this._currentScene.executeWhenReady(function () {
  73119. _this._engine.runRenderLoop(function () {
  73120. _this.renderFunction();
  73121. });
  73122. });
  73123. }).catch(function (error) {
  73124. if (_this._errorCallback) {
  73125. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  73126. }
  73127. });
  73128. }
  73129. else {
  73130. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  73131. }
  73132. };
  73133. FilesInput.FilesToLoad = {};
  73134. return FilesInput;
  73135. }());
  73136. BABYLON.FilesInput = FilesInput;
  73137. })(BABYLON || (BABYLON = {}));
  73138. //# sourceMappingURL=babylon.filesInput.js.map
  73139. var BABYLON;
  73140. (function (BABYLON) {
  73141. var Tags = /** @class */ (function () {
  73142. function Tags() {
  73143. }
  73144. Tags.EnableFor = function (obj) {
  73145. obj._tags = obj._tags || {};
  73146. obj.hasTags = function () {
  73147. return Tags.HasTags(obj);
  73148. };
  73149. obj.addTags = function (tagsString) {
  73150. return Tags.AddTagsTo(obj, tagsString);
  73151. };
  73152. obj.removeTags = function (tagsString) {
  73153. return Tags.RemoveTagsFrom(obj, tagsString);
  73154. };
  73155. obj.matchesTagsQuery = function (tagsQuery) {
  73156. return Tags.MatchesQuery(obj, tagsQuery);
  73157. };
  73158. };
  73159. Tags.DisableFor = function (obj) {
  73160. delete obj._tags;
  73161. delete obj.hasTags;
  73162. delete obj.addTags;
  73163. delete obj.removeTags;
  73164. delete obj.matchesTagsQuery;
  73165. };
  73166. Tags.HasTags = function (obj) {
  73167. if (!obj._tags) {
  73168. return false;
  73169. }
  73170. return !BABYLON.Tools.IsEmpty(obj._tags);
  73171. };
  73172. Tags.GetTags = function (obj, asString) {
  73173. if (asString === void 0) { asString = true; }
  73174. if (!obj._tags) {
  73175. return null;
  73176. }
  73177. if (asString) {
  73178. var tagsArray = [];
  73179. for (var tag in obj._tags) {
  73180. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  73181. tagsArray.push(tag);
  73182. }
  73183. }
  73184. return tagsArray.join(" ");
  73185. }
  73186. else {
  73187. return obj._tags;
  73188. }
  73189. };
  73190. // the tags 'true' and 'false' are reserved and cannot be used as tags
  73191. // a tag cannot start with '||', '&&', and '!'
  73192. // it cannot contain whitespaces
  73193. Tags.AddTagsTo = function (obj, tagsString) {
  73194. if (!tagsString) {
  73195. return;
  73196. }
  73197. if (typeof tagsString !== "string") {
  73198. return;
  73199. }
  73200. var tags = tagsString.split(" ");
  73201. tags.forEach(function (tag, index, array) {
  73202. Tags._AddTagTo(obj, tag);
  73203. });
  73204. };
  73205. Tags._AddTagTo = function (obj, tag) {
  73206. tag = tag.trim();
  73207. if (tag === "" || tag === "true" || tag === "false") {
  73208. return;
  73209. }
  73210. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  73211. return;
  73212. }
  73213. Tags.EnableFor(obj);
  73214. obj._tags[tag] = true;
  73215. };
  73216. Tags.RemoveTagsFrom = function (obj, tagsString) {
  73217. if (!Tags.HasTags(obj)) {
  73218. return;
  73219. }
  73220. var tags = tagsString.split(" ");
  73221. for (var t in tags) {
  73222. Tags._RemoveTagFrom(obj, tags[t]);
  73223. }
  73224. };
  73225. Tags._RemoveTagFrom = function (obj, tag) {
  73226. delete obj._tags[tag];
  73227. };
  73228. Tags.MatchesQuery = function (obj, tagsQuery) {
  73229. if (tagsQuery === undefined) {
  73230. return true;
  73231. }
  73232. if (tagsQuery === "") {
  73233. return Tags.HasTags(obj);
  73234. }
  73235. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  73236. };
  73237. return Tags;
  73238. }());
  73239. BABYLON.Tags = Tags;
  73240. })(BABYLON || (BABYLON = {}));
  73241. //# sourceMappingURL=babylon.tags.js.map
  73242. var BABYLON;
  73243. (function (BABYLON) {
  73244. /**
  73245. * Class used to evalaute queries containing `and` and `or` operators
  73246. */
  73247. var AndOrNotEvaluator = /** @class */ (function () {
  73248. function AndOrNotEvaluator() {
  73249. }
  73250. /**
  73251. * Evaluate a query
  73252. * @param query defines the query to evaluate
  73253. * @param evaluateCallback defines the callback used to filter result
  73254. * @returns true if the query matches
  73255. */
  73256. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  73257. if (!query.match(/\([^\(\)]*\)/g)) {
  73258. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  73259. }
  73260. else {
  73261. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  73262. // remove parenthesis
  73263. r = r.slice(1, r.length - 1);
  73264. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  73265. });
  73266. }
  73267. if (query === "true") {
  73268. return true;
  73269. }
  73270. if (query === "false") {
  73271. return false;
  73272. }
  73273. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  73274. };
  73275. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  73276. evaluateCallback = evaluateCallback || (function (r) {
  73277. return r === "true" ? true : false;
  73278. });
  73279. var result;
  73280. var or = parenthesisContent.split("||");
  73281. for (var i in or) {
  73282. if (or.hasOwnProperty(i)) {
  73283. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  73284. var and = ori.split("&&");
  73285. if (and.length > 1) {
  73286. for (var j = 0; j < and.length; ++j) {
  73287. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  73288. if (andj !== "true" && andj !== "false") {
  73289. if (andj[0] === "!") {
  73290. result = !evaluateCallback(andj.substring(1));
  73291. }
  73292. else {
  73293. result = evaluateCallback(andj);
  73294. }
  73295. }
  73296. else {
  73297. result = andj === "true" ? true : false;
  73298. }
  73299. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  73300. ori = "false";
  73301. break;
  73302. }
  73303. }
  73304. }
  73305. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  73306. result = true;
  73307. break;
  73308. }
  73309. // result equals false (or undefined)
  73310. if (ori !== "true" && ori !== "false") {
  73311. if (ori[0] === "!") {
  73312. result = !evaluateCallback(ori.substring(1));
  73313. }
  73314. else {
  73315. result = evaluateCallback(ori);
  73316. }
  73317. }
  73318. else {
  73319. result = ori === "true" ? true : false;
  73320. }
  73321. }
  73322. }
  73323. // the whole parenthesis scope is replaced by 'true' or 'false'
  73324. return result ? "true" : "false";
  73325. };
  73326. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  73327. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  73328. // remove whitespaces
  73329. r = r.replace(/[\s]/g, function () { return ""; });
  73330. return r.length % 2 ? "!" : "";
  73331. });
  73332. booleanString = booleanString.trim();
  73333. if (booleanString === "!true") {
  73334. booleanString = "false";
  73335. }
  73336. else if (booleanString === "!false") {
  73337. booleanString = "true";
  73338. }
  73339. return booleanString;
  73340. };
  73341. return AndOrNotEvaluator;
  73342. }());
  73343. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  73344. })(BABYLON || (BABYLON = {}));
  73345. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  73346. var BABYLON;
  73347. (function (BABYLON) {
  73348. /**
  73349. * Class used to enable access to IndexedDB
  73350. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  73351. */
  73352. var Database = /** @class */ (function () {
  73353. /**
  73354. * Creates a new Database
  73355. * @param urlToScene defines the url to load the scene
  73356. * @param callbackManifestChecked defines the callback to use when manifest is checked
  73357. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  73358. */
  73359. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  73360. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  73361. var _this = this;
  73362. // Handling various flavors of prefixed version of IndexedDB
  73363. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  73364. this.callbackManifestChecked = callbackManifestChecked;
  73365. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  73366. this.db = null;
  73367. this._enableSceneOffline = false;
  73368. this._enableTexturesOffline = false;
  73369. this.manifestVersionFound = 0;
  73370. this.mustUpdateRessources = false;
  73371. this.hasReachedQuota = false;
  73372. if (!Database.IDBStorageEnabled) {
  73373. this.callbackManifestChecked(true);
  73374. }
  73375. else {
  73376. if (disableManifestCheck) {
  73377. this._enableSceneOffline = true;
  73378. this._enableTexturesOffline = true;
  73379. this.manifestVersionFound = 1;
  73380. BABYLON.Tools.SetImmediate(function () {
  73381. _this.callbackManifestChecked(true);
  73382. });
  73383. }
  73384. else {
  73385. this._checkManifestFile();
  73386. }
  73387. }
  73388. }
  73389. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  73390. /**
  73391. * Gets a boolean indicating if scene must be saved in the database
  73392. */
  73393. get: function () {
  73394. return this._enableSceneOffline;
  73395. },
  73396. enumerable: true,
  73397. configurable: true
  73398. });
  73399. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  73400. /**
  73401. * Gets a boolean indicating if textures must be saved in the database
  73402. */
  73403. get: function () {
  73404. return this._enableTexturesOffline;
  73405. },
  73406. enumerable: true,
  73407. configurable: true
  73408. });
  73409. Database.prototype._checkManifestFile = function () {
  73410. var _this = this;
  73411. var noManifestFile = function () {
  73412. _this._enableSceneOffline = false;
  73413. _this._enableTexturesOffline = false;
  73414. _this.callbackManifestChecked(false);
  73415. };
  73416. var timeStampUsed = false;
  73417. var manifestURL = this.currentSceneUrl + ".manifest";
  73418. var xhr = new XMLHttpRequest();
  73419. if (navigator.onLine) {
  73420. // Adding a timestamp to by-pass browsers' cache
  73421. timeStampUsed = true;
  73422. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  73423. }
  73424. xhr.open("GET", manifestURL, true);
  73425. xhr.addEventListener("load", function () {
  73426. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  73427. try {
  73428. var manifestFile = JSON.parse(xhr.response);
  73429. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  73430. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  73431. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  73432. _this.manifestVersionFound = manifestFile.version;
  73433. }
  73434. if (_this.callbackManifestChecked) {
  73435. _this.callbackManifestChecked(true);
  73436. }
  73437. }
  73438. catch (ex) {
  73439. noManifestFile();
  73440. }
  73441. }
  73442. else {
  73443. noManifestFile();
  73444. }
  73445. }, false);
  73446. xhr.addEventListener("error", function (event) {
  73447. if (timeStampUsed) {
  73448. timeStampUsed = false;
  73449. // Let's retry without the timeStamp
  73450. // It could fail when coupled with HTML5 Offline API
  73451. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  73452. xhr.open("GET", retryManifestURL, true);
  73453. xhr.send();
  73454. }
  73455. else {
  73456. noManifestFile();
  73457. }
  73458. }, false);
  73459. try {
  73460. xhr.send();
  73461. }
  73462. catch (ex) {
  73463. BABYLON.Tools.Error("Error on XHR send request.");
  73464. this.callbackManifestChecked(false);
  73465. }
  73466. };
  73467. /**
  73468. * Open the database and make it available
  73469. * @param successCallback defines the callback to call on success
  73470. * @param errorCallback defines the callback to call on error
  73471. */
  73472. Database.prototype.openAsync = function (successCallback, errorCallback) {
  73473. var _this = this;
  73474. var handleError = function () {
  73475. _this.isSupported = false;
  73476. if (errorCallback)
  73477. errorCallback();
  73478. };
  73479. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  73480. // Your browser doesn't support IndexedDB
  73481. this.isSupported = false;
  73482. if (errorCallback)
  73483. errorCallback();
  73484. }
  73485. else {
  73486. // If the DB hasn't been opened or created yet
  73487. if (!this.db) {
  73488. this.hasReachedQuota = false;
  73489. this.isSupported = true;
  73490. var request = this.idbFactory.open("babylonjs", 1);
  73491. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  73492. request.onerror = function (event) {
  73493. handleError();
  73494. };
  73495. // executes when a version change transaction cannot complete due to other active transactions
  73496. request.onblocked = function (event) {
  73497. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  73498. handleError();
  73499. };
  73500. // DB has been opened successfully
  73501. request.onsuccess = function (event) {
  73502. _this.db = request.result;
  73503. successCallback();
  73504. };
  73505. // Initialization of the DB. Creating Scenes & Textures stores
  73506. request.onupgradeneeded = function (event) {
  73507. _this.db = (event.target).result;
  73508. if (_this.db) {
  73509. try {
  73510. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  73511. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  73512. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  73513. }
  73514. catch (ex) {
  73515. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  73516. handleError();
  73517. }
  73518. }
  73519. };
  73520. }
  73521. // DB has already been created and opened
  73522. else {
  73523. if (successCallback)
  73524. successCallback();
  73525. }
  73526. }
  73527. };
  73528. /**
  73529. * Loads an image from the database
  73530. * @param url defines the url to load from
  73531. * @param image defines the target DOM image
  73532. */
  73533. Database.prototype.loadImageFromDB = function (url, image) {
  73534. var _this = this;
  73535. var completeURL = Database._ReturnFullUrlLocation(url);
  73536. var saveAndLoadImage = function () {
  73537. if (!_this.hasReachedQuota && _this.db !== null) {
  73538. // the texture is not yet in the DB, let's try to save it
  73539. _this._saveImageIntoDBAsync(completeURL, image);
  73540. }
  73541. // If the texture is not in the DB and we've reached the DB quota limit
  73542. // let's load it directly from the web
  73543. else {
  73544. image.src = url;
  73545. }
  73546. };
  73547. if (!this.mustUpdateRessources) {
  73548. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  73549. }
  73550. // First time we're download the images or update requested in the manifest file by a version change
  73551. else {
  73552. saveAndLoadImage();
  73553. }
  73554. };
  73555. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  73556. if (this.isSupported && this.db !== null) {
  73557. var texture;
  73558. var transaction = this.db.transaction(["textures"]);
  73559. transaction.onabort = function (event) {
  73560. image.src = url;
  73561. };
  73562. transaction.oncomplete = function (event) {
  73563. var blobTextureURL;
  73564. if (texture) {
  73565. var URL = window.URL || window.webkitURL;
  73566. blobTextureURL = URL.createObjectURL(texture.data);
  73567. image.onerror = function () {
  73568. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  73569. image.src = url;
  73570. };
  73571. image.src = blobTextureURL;
  73572. }
  73573. else {
  73574. notInDBCallback();
  73575. }
  73576. };
  73577. var getRequest = transaction.objectStore("textures").get(url);
  73578. getRequest.onsuccess = function (event) {
  73579. texture = (event.target).result;
  73580. };
  73581. getRequest.onerror = function (event) {
  73582. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  73583. image.src = url;
  73584. };
  73585. }
  73586. else {
  73587. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73588. image.src = url;
  73589. }
  73590. };
  73591. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  73592. var _this = this;
  73593. if (this.isSupported) {
  73594. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  73595. var generateBlobUrl = function () {
  73596. var blobTextureURL;
  73597. if (blob) {
  73598. var URL = window.URL || window.webkitURL;
  73599. try {
  73600. blobTextureURL = URL.createObjectURL(blob);
  73601. }
  73602. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  73603. catch (ex) {
  73604. blobTextureURL = URL.createObjectURL(blob);
  73605. }
  73606. }
  73607. if (blobTextureURL) {
  73608. image.src = blobTextureURL;
  73609. }
  73610. };
  73611. if (Database.IsUASupportingBlobStorage) { // Create XHR
  73612. var xhr = new XMLHttpRequest(), blob;
  73613. xhr.open("GET", url, true);
  73614. xhr.responseType = "blob";
  73615. xhr.addEventListener("load", function () {
  73616. if (xhr.status === 200 && _this.db) {
  73617. // Blob as response (XHR2)
  73618. blob = xhr.response;
  73619. var transaction = _this.db.transaction(["textures"], "readwrite");
  73620. // the transaction could abort because of a QuotaExceededError error
  73621. transaction.onabort = function (event) {
  73622. try {
  73623. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73624. var srcElement = (event.srcElement || event.target);
  73625. var error = srcElement.error;
  73626. if (error && error.name === "QuotaExceededError") {
  73627. _this.hasReachedQuota = true;
  73628. }
  73629. }
  73630. catch (ex) { }
  73631. generateBlobUrl();
  73632. };
  73633. transaction.oncomplete = function (event) {
  73634. generateBlobUrl();
  73635. };
  73636. var newTexture = { textureUrl: url, data: blob };
  73637. try {
  73638. // Put the blob into the dabase
  73639. var addRequest = transaction.objectStore("textures").put(newTexture);
  73640. addRequest.onsuccess = function (event) {
  73641. };
  73642. addRequest.onerror = function (event) {
  73643. generateBlobUrl();
  73644. };
  73645. }
  73646. catch (ex) {
  73647. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  73648. if (ex.code === 25) {
  73649. Database.IsUASupportingBlobStorage = false;
  73650. }
  73651. image.src = url;
  73652. }
  73653. }
  73654. else {
  73655. image.src = url;
  73656. }
  73657. }, false);
  73658. xhr.addEventListener("error", function (event) {
  73659. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  73660. image.src = url;
  73661. }, false);
  73662. xhr.send();
  73663. }
  73664. else {
  73665. image.src = url;
  73666. }
  73667. }
  73668. else {
  73669. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73670. image.src = url;
  73671. }
  73672. };
  73673. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  73674. var _this = this;
  73675. var updateVersion = function () {
  73676. // the version is not yet in the DB or we need to update it
  73677. _this._saveVersionIntoDBAsync(url, versionLoaded);
  73678. };
  73679. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  73680. };
  73681. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  73682. var _this = this;
  73683. if (this.isSupported && this.db) {
  73684. var version;
  73685. try {
  73686. var transaction = this.db.transaction(["versions"]);
  73687. transaction.oncomplete = function (event) {
  73688. if (version) {
  73689. // If the version in the JSON file is different from the version in DB
  73690. if (_this.manifestVersionFound !== version.data) {
  73691. _this.mustUpdateRessources = true;
  73692. updateInDBCallback();
  73693. }
  73694. else {
  73695. callback(version.data);
  73696. }
  73697. }
  73698. // version was not found in DB
  73699. else {
  73700. _this.mustUpdateRessources = true;
  73701. updateInDBCallback();
  73702. }
  73703. };
  73704. transaction.onabort = function (event) {
  73705. callback(-1);
  73706. };
  73707. var getRequest = transaction.objectStore("versions").get(url);
  73708. getRequest.onsuccess = function (event) {
  73709. version = (event.target).result;
  73710. };
  73711. getRequest.onerror = function (event) {
  73712. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  73713. callback(-1);
  73714. };
  73715. }
  73716. catch (ex) {
  73717. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  73718. callback(-1);
  73719. }
  73720. }
  73721. else {
  73722. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73723. callback(-1);
  73724. }
  73725. };
  73726. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  73727. var _this = this;
  73728. if (this.isSupported && !this.hasReachedQuota && this.db) {
  73729. try {
  73730. // Open a transaction to the database
  73731. var transaction = this.db.transaction(["versions"], "readwrite");
  73732. // the transaction could abort because of a QuotaExceededError error
  73733. transaction.onabort = function (event) {
  73734. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73735. var error = event.srcElement['error'];
  73736. if (error && error.name === "QuotaExceededError") {
  73737. _this.hasReachedQuota = true;
  73738. }
  73739. }
  73740. catch (ex) { }
  73741. callback(-1);
  73742. };
  73743. transaction.oncomplete = function (event) {
  73744. callback(_this.manifestVersionFound);
  73745. };
  73746. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  73747. // Put the scene into the database
  73748. var addRequest = transaction.objectStore("versions").put(newVersion);
  73749. addRequest.onsuccess = function (event) {
  73750. };
  73751. addRequest.onerror = function (event) {
  73752. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  73753. };
  73754. }
  73755. catch (ex) {
  73756. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  73757. callback(-1);
  73758. }
  73759. }
  73760. else {
  73761. callback(-1);
  73762. }
  73763. };
  73764. /**
  73765. * Loads a file from database
  73766. * @param url defines the URL to load from
  73767. * @param sceneLoaded defines a callback to call on success
  73768. * @param progressCallBack defines a callback to call when progress changed
  73769. * @param errorCallback defines a callback to call on error
  73770. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  73771. */
  73772. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  73773. var _this = this;
  73774. var completeUrl = Database._ReturnFullUrlLocation(url);
  73775. var saveAndLoadFile = function () {
  73776. // the scene is not yet in the DB, let's try to save it
  73777. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  73778. };
  73779. this._checkVersionFromDB(completeUrl, function (version) {
  73780. if (version !== -1) {
  73781. if (!_this.mustUpdateRessources) {
  73782. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  73783. }
  73784. else {
  73785. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  73786. }
  73787. }
  73788. else {
  73789. if (errorCallback) {
  73790. errorCallback();
  73791. }
  73792. }
  73793. });
  73794. };
  73795. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  73796. if (this.isSupported && this.db) {
  73797. var targetStore;
  73798. if (url.indexOf(".babylon") !== -1) {
  73799. targetStore = "scenes";
  73800. }
  73801. else {
  73802. targetStore = "textures";
  73803. }
  73804. var file;
  73805. var transaction = this.db.transaction([targetStore]);
  73806. transaction.oncomplete = function (event) {
  73807. if (file) {
  73808. callback(file.data);
  73809. }
  73810. // file was not found in DB
  73811. else {
  73812. notInDBCallback();
  73813. }
  73814. };
  73815. transaction.onabort = function (event) {
  73816. notInDBCallback();
  73817. };
  73818. var getRequest = transaction.objectStore(targetStore).get(url);
  73819. getRequest.onsuccess = function (event) {
  73820. file = (event.target).result;
  73821. };
  73822. getRequest.onerror = function (event) {
  73823. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  73824. notInDBCallback();
  73825. };
  73826. }
  73827. else {
  73828. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73829. callback();
  73830. }
  73831. };
  73832. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  73833. var _this = this;
  73834. if (this.isSupported) {
  73835. var targetStore;
  73836. if (url.indexOf(".babylon") !== -1) {
  73837. targetStore = "scenes";
  73838. }
  73839. else {
  73840. targetStore = "textures";
  73841. }
  73842. // Create XHR
  73843. var xhr = new XMLHttpRequest();
  73844. var fileData;
  73845. xhr.open("GET", url + "?" + Date.now(), true);
  73846. if (useArrayBuffer) {
  73847. xhr.responseType = "arraybuffer";
  73848. }
  73849. if (progressCallback) {
  73850. xhr.onprogress = progressCallback;
  73851. }
  73852. xhr.addEventListener("load", function () {
  73853. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  73854. // Blob as response (XHR2)
  73855. //fileData = xhr.responseText;
  73856. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  73857. if (!_this.hasReachedQuota && _this.db) {
  73858. // Open a transaction to the database
  73859. var transaction = _this.db.transaction([targetStore], "readwrite");
  73860. // the transaction could abort because of a QuotaExceededError error
  73861. transaction.onabort = function (event) {
  73862. try {
  73863. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73864. var error = event.srcElement['error'];
  73865. if (error && error.name === "QuotaExceededError") {
  73866. _this.hasReachedQuota = true;
  73867. }
  73868. }
  73869. catch (ex) { }
  73870. callback(fileData);
  73871. };
  73872. transaction.oncomplete = function (event) {
  73873. callback(fileData);
  73874. };
  73875. var newFile;
  73876. if (targetStore === "scenes") {
  73877. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  73878. }
  73879. else {
  73880. newFile = { textureUrl: url, data: fileData };
  73881. }
  73882. try {
  73883. // Put the scene into the database
  73884. var addRequest = transaction.objectStore(targetStore).put(newFile);
  73885. addRequest.onsuccess = function (event) {
  73886. };
  73887. addRequest.onerror = function (event) {
  73888. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  73889. };
  73890. }
  73891. catch (ex) {
  73892. callback(fileData);
  73893. }
  73894. }
  73895. else {
  73896. callback(fileData);
  73897. }
  73898. }
  73899. else {
  73900. if (xhr.status >= 400 && errorCallback) {
  73901. errorCallback(xhr);
  73902. }
  73903. else {
  73904. callback();
  73905. }
  73906. }
  73907. }, false);
  73908. xhr.addEventListener("error", function (event) {
  73909. BABYLON.Tools.Error("error on XHR request.");
  73910. callback();
  73911. }, false);
  73912. xhr.send();
  73913. }
  73914. else {
  73915. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73916. callback();
  73917. }
  73918. };
  73919. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  73920. Database.IsUASupportingBlobStorage = true;
  73921. /** Gets a boolean indicating if Database storate is enabled */
  73922. Database.IDBStorageEnabled = true;
  73923. Database._ParseURL = function (url) {
  73924. var a = document.createElement('a');
  73925. a.href = url;
  73926. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  73927. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  73928. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  73929. return absLocation;
  73930. };
  73931. Database._ReturnFullUrlLocation = function (url) {
  73932. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  73933. return (Database._ParseURL(window.location.href) + url);
  73934. }
  73935. else {
  73936. return url;
  73937. }
  73938. };
  73939. return Database;
  73940. }());
  73941. BABYLON.Database = Database;
  73942. })(BABYLON || (BABYLON = {}));
  73943. //# sourceMappingURL=babylon.database.js.map
  73944. var BABYLON;
  73945. (function (BABYLON) {
  73946. var FresnelParameters = /** @class */ (function () {
  73947. function FresnelParameters() {
  73948. this._isEnabled = true;
  73949. this.leftColor = BABYLON.Color3.White();
  73950. this.rightColor = BABYLON.Color3.Black();
  73951. this.bias = 0;
  73952. this.power = 1;
  73953. }
  73954. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  73955. get: function () {
  73956. return this._isEnabled;
  73957. },
  73958. set: function (value) {
  73959. if (this._isEnabled === value) {
  73960. return;
  73961. }
  73962. this._isEnabled = value;
  73963. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  73964. },
  73965. enumerable: true,
  73966. configurable: true
  73967. });
  73968. FresnelParameters.prototype.clone = function () {
  73969. var newFresnelParameters = new FresnelParameters();
  73970. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  73971. return newFresnelParameters;
  73972. };
  73973. FresnelParameters.prototype.serialize = function () {
  73974. var serializationObject = {};
  73975. serializationObject.isEnabled = this.isEnabled;
  73976. serializationObject.leftColor = this.leftColor.asArray();
  73977. serializationObject.rightColor = this.rightColor.asArray();
  73978. serializationObject.bias = this.bias;
  73979. serializationObject.power = this.power;
  73980. return serializationObject;
  73981. };
  73982. FresnelParameters.Parse = function (parsedFresnelParameters) {
  73983. var fresnelParameters = new FresnelParameters();
  73984. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  73985. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  73986. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  73987. fresnelParameters.bias = parsedFresnelParameters.bias;
  73988. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  73989. return fresnelParameters;
  73990. };
  73991. return FresnelParameters;
  73992. }());
  73993. BABYLON.FresnelParameters = FresnelParameters;
  73994. })(BABYLON || (BABYLON = {}));
  73995. //# sourceMappingURL=babylon.fresnelParameters.js.map
  73996. var BABYLON;
  73997. (function (BABYLON) {
  73998. var MultiMaterial = /** @class */ (function (_super) {
  73999. __extends(MultiMaterial, _super);
  74000. function MultiMaterial(name, scene) {
  74001. var _this = _super.call(this, name, scene, true) || this;
  74002. scene.multiMaterials.push(_this);
  74003. _this.subMaterials = new Array();
  74004. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  74005. return _this;
  74006. }
  74007. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  74008. get: function () {
  74009. return this._subMaterials;
  74010. },
  74011. set: function (value) {
  74012. this._subMaterials = value;
  74013. this._hookArray(value);
  74014. },
  74015. enumerable: true,
  74016. configurable: true
  74017. });
  74018. MultiMaterial.prototype._hookArray = function (array) {
  74019. var _this = this;
  74020. var oldPush = array.push;
  74021. array.push = function () {
  74022. var items = [];
  74023. for (var _i = 0; _i < arguments.length; _i++) {
  74024. items[_i] = arguments[_i];
  74025. }
  74026. var result = oldPush.apply(array, items);
  74027. _this._markAllSubMeshesAsTexturesDirty();
  74028. return result;
  74029. };
  74030. var oldSplice = array.splice;
  74031. array.splice = function (index, deleteCount) {
  74032. var deleted = oldSplice.apply(array, [index, deleteCount]);
  74033. _this._markAllSubMeshesAsTexturesDirty();
  74034. return deleted;
  74035. };
  74036. };
  74037. // Properties
  74038. MultiMaterial.prototype.getSubMaterial = function (index) {
  74039. if (index < 0 || index >= this.subMaterials.length) {
  74040. return this.getScene().defaultMaterial;
  74041. }
  74042. return this.subMaterials[index];
  74043. };
  74044. MultiMaterial.prototype.getActiveTextures = function () {
  74045. var _a;
  74046. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  74047. if (subMaterial) {
  74048. return subMaterial.getActiveTextures();
  74049. }
  74050. else {
  74051. return [];
  74052. }
  74053. }));
  74054. };
  74055. // Methods
  74056. MultiMaterial.prototype.getClassName = function () {
  74057. return "MultiMaterial";
  74058. };
  74059. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  74060. for (var index = 0; index < this.subMaterials.length; index++) {
  74061. var subMaterial = this.subMaterials[index];
  74062. if (subMaterial) {
  74063. if (subMaterial.storeEffectOnSubMeshes) {
  74064. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  74065. return false;
  74066. }
  74067. continue;
  74068. }
  74069. if (!subMaterial.isReady(mesh)) {
  74070. return false;
  74071. }
  74072. }
  74073. }
  74074. return true;
  74075. };
  74076. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  74077. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  74078. for (var index = 0; index < this.subMaterials.length; index++) {
  74079. var subMaterial = null;
  74080. var current = this.subMaterials[index];
  74081. if (cloneChildren && current) {
  74082. subMaterial = current.clone(name + "-" + current.name);
  74083. }
  74084. else {
  74085. subMaterial = this.subMaterials[index];
  74086. }
  74087. newMultiMaterial.subMaterials.push(subMaterial);
  74088. }
  74089. return newMultiMaterial;
  74090. };
  74091. MultiMaterial.prototype.serialize = function () {
  74092. var serializationObject = {};
  74093. serializationObject.name = this.name;
  74094. serializationObject.id = this.id;
  74095. if (BABYLON.Tags) {
  74096. serializationObject.tags = BABYLON.Tags.GetTags(this);
  74097. }
  74098. serializationObject.materials = [];
  74099. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  74100. var subMat = this.subMaterials[matIndex];
  74101. if (subMat) {
  74102. serializationObject.materials.push(subMat.id);
  74103. }
  74104. else {
  74105. serializationObject.materials.push(null);
  74106. }
  74107. }
  74108. return serializationObject;
  74109. };
  74110. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  74111. var scene = this.getScene();
  74112. if (!scene) {
  74113. return;
  74114. }
  74115. var index = scene.multiMaterials.indexOf(this);
  74116. if (index >= 0) {
  74117. scene.multiMaterials.splice(index, 1);
  74118. }
  74119. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  74120. };
  74121. return MultiMaterial;
  74122. }(BABYLON.Material));
  74123. BABYLON.MultiMaterial = MultiMaterial;
  74124. })(BABYLON || (BABYLON = {}));
  74125. //# sourceMappingURL=babylon.multiMaterial.js.map
  74126. var BABYLON;
  74127. (function (BABYLON) {
  74128. var FreeCameraTouchInput = /** @class */ (function () {
  74129. function FreeCameraTouchInput() {
  74130. this._offsetX = null;
  74131. this._offsetY = null;
  74132. this._pointerPressed = new Array();
  74133. this.touchAngularSensibility = 200000.0;
  74134. this.touchMoveSensibility = 250.0;
  74135. }
  74136. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  74137. var _this = this;
  74138. var previousPosition = null;
  74139. if (this._pointerInput === undefined) {
  74140. this._onLostFocus = function (evt) {
  74141. _this._offsetX = null;
  74142. _this._offsetY = null;
  74143. };
  74144. this._pointerInput = function (p, s) {
  74145. var evt = p.event;
  74146. if (evt.pointerType === "mouse") {
  74147. return;
  74148. }
  74149. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  74150. if (!noPreventDefault) {
  74151. evt.preventDefault();
  74152. }
  74153. _this._pointerPressed.push(evt.pointerId);
  74154. if (_this._pointerPressed.length !== 1) {
  74155. return;
  74156. }
  74157. previousPosition = {
  74158. x: evt.clientX,
  74159. y: evt.clientY
  74160. };
  74161. }
  74162. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  74163. if (!noPreventDefault) {
  74164. evt.preventDefault();
  74165. }
  74166. var index = _this._pointerPressed.indexOf(evt.pointerId);
  74167. if (index === -1) {
  74168. return;
  74169. }
  74170. _this._pointerPressed.splice(index, 1);
  74171. if (index != 0) {
  74172. return;
  74173. }
  74174. previousPosition = null;
  74175. _this._offsetX = null;
  74176. _this._offsetY = null;
  74177. }
  74178. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  74179. if (!noPreventDefault) {
  74180. evt.preventDefault();
  74181. }
  74182. if (!previousPosition) {
  74183. return;
  74184. }
  74185. var index = _this._pointerPressed.indexOf(evt.pointerId);
  74186. if (index != 0) {
  74187. return;
  74188. }
  74189. _this._offsetX = evt.clientX - previousPosition.x;
  74190. _this._offsetY = -(evt.clientY - previousPosition.y);
  74191. }
  74192. };
  74193. }
  74194. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  74195. if (this._onLostFocus) {
  74196. element.addEventListener("blur", this._onLostFocus);
  74197. }
  74198. };
  74199. FreeCameraTouchInput.prototype.detachControl = function (element) {
  74200. if (this._pointerInput && element) {
  74201. if (this._observer) {
  74202. this.camera.getScene().onPointerObservable.remove(this._observer);
  74203. this._observer = null;
  74204. }
  74205. if (this._onLostFocus) {
  74206. element.removeEventListener("blur", this._onLostFocus);
  74207. this._onLostFocus = null;
  74208. }
  74209. this._pointerPressed = [];
  74210. this._offsetX = null;
  74211. this._offsetY = null;
  74212. }
  74213. };
  74214. FreeCameraTouchInput.prototype.checkInputs = function () {
  74215. if (this._offsetX && this._offsetY) {
  74216. var camera = this.camera;
  74217. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  74218. if (this._pointerPressed.length > 1) {
  74219. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  74220. }
  74221. else {
  74222. var speed = camera._computeLocalCameraSpeed();
  74223. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  74224. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  74225. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  74226. }
  74227. }
  74228. };
  74229. FreeCameraTouchInput.prototype.getClassName = function () {
  74230. return "FreeCameraTouchInput";
  74231. };
  74232. FreeCameraTouchInput.prototype.getSimpleName = function () {
  74233. return "touch";
  74234. };
  74235. __decorate([
  74236. BABYLON.serialize()
  74237. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  74238. __decorate([
  74239. BABYLON.serialize()
  74240. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  74241. return FreeCameraTouchInput;
  74242. }());
  74243. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  74244. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  74245. })(BABYLON || (BABYLON = {}));
  74246. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  74247. var BABYLON;
  74248. (function (BABYLON) {
  74249. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  74250. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  74251. });
  74252. // We're mainly based on the logic defined into the FreeCamera code
  74253. var TouchCamera = /** @class */ (function (_super) {
  74254. __extends(TouchCamera, _super);
  74255. //-- end properties for backward compatibility for inputs
  74256. function TouchCamera(name, position, scene) {
  74257. var _this = _super.call(this, name, position, scene) || this;
  74258. _this.inputs.addTouch();
  74259. _this._setupInputs();
  74260. return _this;
  74261. }
  74262. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  74263. //-- Begin properties for backward compatibility for inputs
  74264. get: function () {
  74265. var touch = this.inputs.attached["touch"];
  74266. if (touch)
  74267. return touch.touchAngularSensibility;
  74268. return 0;
  74269. },
  74270. set: function (value) {
  74271. var touch = this.inputs.attached["touch"];
  74272. if (touch)
  74273. touch.touchAngularSensibility = value;
  74274. },
  74275. enumerable: true,
  74276. configurable: true
  74277. });
  74278. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  74279. get: function () {
  74280. var touch = this.inputs.attached["touch"];
  74281. if (touch)
  74282. return touch.touchMoveSensibility;
  74283. return 0;
  74284. },
  74285. set: function (value) {
  74286. var touch = this.inputs.attached["touch"];
  74287. if (touch)
  74288. touch.touchMoveSensibility = value;
  74289. },
  74290. enumerable: true,
  74291. configurable: true
  74292. });
  74293. TouchCamera.prototype.getClassName = function () {
  74294. return "TouchCamera";
  74295. };
  74296. /** @hidden */
  74297. TouchCamera.prototype._setupInputs = function () {
  74298. var mouse = this.inputs.attached["mouse"];
  74299. if (mouse) {
  74300. mouse.touchEnabled = false;
  74301. }
  74302. };
  74303. return TouchCamera;
  74304. }(BABYLON.FreeCamera));
  74305. BABYLON.TouchCamera = TouchCamera;
  74306. })(BABYLON || (BABYLON = {}));
  74307. //# sourceMappingURL=babylon.touchCamera.js.map
  74308. var BABYLON;
  74309. (function (BABYLON) {
  74310. var ProceduralTexture = /** @class */ (function (_super) {
  74311. __extends(ProceduralTexture, _super);
  74312. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  74313. if (fallbackTexture === void 0) { fallbackTexture = null; }
  74314. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74315. if (isCube === void 0) { isCube = false; }
  74316. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  74317. _this.isCube = isCube;
  74318. _this.isEnabled = true;
  74319. _this._currentRefreshId = -1;
  74320. _this._refreshRate = 1;
  74321. /**
  74322. * Event raised when the texture is generated
  74323. */
  74324. _this.onGeneratedObservable = new BABYLON.Observable();
  74325. _this._vertexBuffers = {};
  74326. _this._uniforms = new Array();
  74327. _this._samplers = new Array();
  74328. /** @hidden */
  74329. _this._textures = {};
  74330. _this._floats = {};
  74331. _this._ints = {};
  74332. _this._floatsArrays = {};
  74333. _this._colors3 = {};
  74334. _this._colors4 = {};
  74335. _this._vectors2 = {};
  74336. _this._vectors3 = {};
  74337. _this._matrices = {};
  74338. _this._fallbackTextureUsed = false;
  74339. _this._cachedDefines = "";
  74340. _this._contentUpdateId = -1;
  74341. scene = _this.getScene();
  74342. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  74343. if (!component) {
  74344. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  74345. scene._addComponent(component);
  74346. }
  74347. scene.proceduralTextures.push(_this);
  74348. _this._engine = scene.getEngine();
  74349. _this.name = name;
  74350. _this.isRenderTarget = true;
  74351. _this._size = size;
  74352. _this._generateMipMaps = generateMipMaps;
  74353. _this.setFragment(fragment);
  74354. _this._fallbackTexture = fallbackTexture;
  74355. if (isCube) {
  74356. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  74357. _this.setFloat("face", 0);
  74358. }
  74359. else {
  74360. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  74361. }
  74362. // VBO
  74363. var vertices = [];
  74364. vertices.push(1, 1);
  74365. vertices.push(-1, 1);
  74366. vertices.push(-1, -1);
  74367. vertices.push(1, -1);
  74368. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74369. _this._createIndexBuffer();
  74370. return _this;
  74371. }
  74372. /**
  74373. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  74374. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  74375. */
  74376. ProceduralTexture.prototype.getContent = function () {
  74377. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  74378. return this._contentData;
  74379. }
  74380. this._contentData = this.readPixels(0, 0, this._contentData);
  74381. this._contentUpdateId = this._currentRefreshId;
  74382. return this._contentData;
  74383. };
  74384. ProceduralTexture.prototype._createIndexBuffer = function () {
  74385. var engine = this._engine;
  74386. // Indices
  74387. var indices = [];
  74388. indices.push(0);
  74389. indices.push(1);
  74390. indices.push(2);
  74391. indices.push(0);
  74392. indices.push(2);
  74393. indices.push(3);
  74394. this._indexBuffer = engine.createIndexBuffer(indices);
  74395. };
  74396. /** @hidden */
  74397. ProceduralTexture.prototype._rebuild = function () {
  74398. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74399. if (vb) {
  74400. vb._rebuild();
  74401. }
  74402. this._createIndexBuffer();
  74403. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  74404. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  74405. }
  74406. };
  74407. ProceduralTexture.prototype.reset = function () {
  74408. if (this._effect === undefined) {
  74409. return;
  74410. }
  74411. var engine = this._engine;
  74412. engine._releaseEffect(this._effect);
  74413. };
  74414. ProceduralTexture.prototype._getDefines = function () {
  74415. return "";
  74416. };
  74417. ProceduralTexture.prototype.isReady = function () {
  74418. var _this = this;
  74419. var engine = this._engine;
  74420. var shaders;
  74421. if (!this._fragment) {
  74422. return false;
  74423. }
  74424. if (this._fallbackTextureUsed) {
  74425. return true;
  74426. }
  74427. var defines = this._getDefines();
  74428. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  74429. return true;
  74430. }
  74431. if (this._fragment.fragmentElement !== undefined) {
  74432. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  74433. }
  74434. else {
  74435. shaders = { vertex: "procedural", fragment: this._fragment };
  74436. }
  74437. this._cachedDefines = defines;
  74438. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  74439. _this.releaseInternalTexture();
  74440. if (_this._fallbackTexture) {
  74441. _this._texture = _this._fallbackTexture._texture;
  74442. if (_this._texture) {
  74443. _this._texture.incrementReferences();
  74444. }
  74445. }
  74446. _this._fallbackTextureUsed = true;
  74447. });
  74448. return this._effect.isReady();
  74449. };
  74450. ProceduralTexture.prototype.resetRefreshCounter = function () {
  74451. this._currentRefreshId = -1;
  74452. };
  74453. ProceduralTexture.prototype.setFragment = function (fragment) {
  74454. this._fragment = fragment;
  74455. };
  74456. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  74457. get: function () {
  74458. return this._refreshRate;
  74459. },
  74460. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  74461. set: function (value) {
  74462. this._refreshRate = value;
  74463. this.resetRefreshCounter();
  74464. },
  74465. enumerable: true,
  74466. configurable: true
  74467. });
  74468. /** @hidden */
  74469. ProceduralTexture.prototype._shouldRender = function () {
  74470. if (!this.isEnabled || !this.isReady() || !this._texture) {
  74471. if (this._texture) {
  74472. this._texture.isReady = false;
  74473. }
  74474. return false;
  74475. }
  74476. if (this._fallbackTextureUsed) {
  74477. return false;
  74478. }
  74479. if (this._currentRefreshId === -1) { // At least render once
  74480. this._currentRefreshId = 1;
  74481. return true;
  74482. }
  74483. if (this.refreshRate === this._currentRefreshId) {
  74484. this._currentRefreshId = 1;
  74485. return true;
  74486. }
  74487. this._currentRefreshId++;
  74488. return false;
  74489. };
  74490. ProceduralTexture.prototype.getRenderSize = function () {
  74491. return this._size;
  74492. };
  74493. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  74494. if (this._fallbackTextureUsed) {
  74495. return;
  74496. }
  74497. this.releaseInternalTexture();
  74498. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  74499. // Update properties
  74500. this._size = size;
  74501. this._generateMipMaps = generateMipMaps;
  74502. };
  74503. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  74504. if (this._uniforms.indexOf(uniformName) === -1) {
  74505. this._uniforms.push(uniformName);
  74506. }
  74507. };
  74508. ProceduralTexture.prototype.setTexture = function (name, texture) {
  74509. if (this._samplers.indexOf(name) === -1) {
  74510. this._samplers.push(name);
  74511. }
  74512. this._textures[name] = texture;
  74513. return this;
  74514. };
  74515. ProceduralTexture.prototype.setFloat = function (name, value) {
  74516. this._checkUniform(name);
  74517. this._floats[name] = value;
  74518. return this;
  74519. };
  74520. /**
  74521. * Set the value of an uniform to an integer value
  74522. * @param name defines the name of the uniform
  74523. * @param value defines the value to set
  74524. * @returns the current procedural texture
  74525. */
  74526. ProceduralTexture.prototype.setInt = function (name, value) {
  74527. this._checkUniform(name);
  74528. this._ints[name] = value;
  74529. return this;
  74530. };
  74531. ProceduralTexture.prototype.setFloats = function (name, value) {
  74532. this._checkUniform(name);
  74533. this._floatsArrays[name] = value;
  74534. return this;
  74535. };
  74536. ProceduralTexture.prototype.setColor3 = function (name, value) {
  74537. this._checkUniform(name);
  74538. this._colors3[name] = value;
  74539. return this;
  74540. };
  74541. ProceduralTexture.prototype.setColor4 = function (name, value) {
  74542. this._checkUniform(name);
  74543. this._colors4[name] = value;
  74544. return this;
  74545. };
  74546. ProceduralTexture.prototype.setVector2 = function (name, value) {
  74547. this._checkUniform(name);
  74548. this._vectors2[name] = value;
  74549. return this;
  74550. };
  74551. ProceduralTexture.prototype.setVector3 = function (name, value) {
  74552. this._checkUniform(name);
  74553. this._vectors3[name] = value;
  74554. return this;
  74555. };
  74556. ProceduralTexture.prototype.setMatrix = function (name, value) {
  74557. this._checkUniform(name);
  74558. this._matrices[name] = value;
  74559. return this;
  74560. };
  74561. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  74562. var scene = this.getScene();
  74563. if (!scene) {
  74564. return;
  74565. }
  74566. var engine = this._engine;
  74567. // Render
  74568. engine.enableEffect(this._effect);
  74569. engine.setState(false);
  74570. // Texture
  74571. for (var name in this._textures) {
  74572. this._effect.setTexture(name, this._textures[name]);
  74573. }
  74574. // Float
  74575. for (name in this._ints) {
  74576. this._effect.setInt(name, this._ints[name]);
  74577. }
  74578. // Float
  74579. for (name in this._floats) {
  74580. this._effect.setFloat(name, this._floats[name]);
  74581. }
  74582. // Floats
  74583. for (name in this._floatsArrays) {
  74584. this._effect.setArray(name, this._floatsArrays[name]);
  74585. }
  74586. // Color3
  74587. for (name in this._colors3) {
  74588. this._effect.setColor3(name, this._colors3[name]);
  74589. }
  74590. // Color4
  74591. for (name in this._colors4) {
  74592. var color = this._colors4[name];
  74593. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  74594. }
  74595. // Vector2
  74596. for (name in this._vectors2) {
  74597. this._effect.setVector2(name, this._vectors2[name]);
  74598. }
  74599. // Vector3
  74600. for (name in this._vectors3) {
  74601. this._effect.setVector3(name, this._vectors3[name]);
  74602. }
  74603. // Matrix
  74604. for (name in this._matrices) {
  74605. this._effect.setMatrix(name, this._matrices[name]);
  74606. }
  74607. if (!this._texture) {
  74608. return;
  74609. }
  74610. if (this.isCube) {
  74611. for (var face = 0; face < 6; face++) {
  74612. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  74613. // VBOs
  74614. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74615. this._effect.setFloat("face", face);
  74616. // Clear
  74617. engine.clear(scene.clearColor, true, true, true);
  74618. // Draw order
  74619. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74620. // Mipmaps
  74621. if (face === 5) {
  74622. engine.generateMipMapsForCubemap(this._texture);
  74623. }
  74624. }
  74625. }
  74626. else {
  74627. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  74628. // VBOs
  74629. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74630. // Clear
  74631. engine.clear(scene.clearColor, true, true, true);
  74632. // Draw order
  74633. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74634. }
  74635. // Unbind
  74636. engine.unBindFramebuffer(this._texture, this.isCube);
  74637. if (this.onGenerated) {
  74638. this.onGenerated();
  74639. }
  74640. this.onGeneratedObservable.notifyObservers(this);
  74641. };
  74642. ProceduralTexture.prototype.clone = function () {
  74643. var textureSize = this.getSize();
  74644. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  74645. // Base texture
  74646. newTexture.hasAlpha = this.hasAlpha;
  74647. newTexture.level = this.level;
  74648. // RenderTarget Texture
  74649. newTexture.coordinatesMode = this.coordinatesMode;
  74650. return newTexture;
  74651. };
  74652. ProceduralTexture.prototype.dispose = function () {
  74653. var scene = this.getScene();
  74654. if (!scene) {
  74655. return;
  74656. }
  74657. var index = scene.proceduralTextures.indexOf(this);
  74658. if (index >= 0) {
  74659. scene.proceduralTextures.splice(index, 1);
  74660. }
  74661. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74662. if (vertexBuffer) {
  74663. vertexBuffer.dispose();
  74664. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74665. }
  74666. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  74667. this._indexBuffer = null;
  74668. }
  74669. _super.prototype.dispose.call(this);
  74670. };
  74671. __decorate([
  74672. BABYLON.serialize()
  74673. ], ProceduralTexture.prototype, "_size", void 0);
  74674. __decorate([
  74675. BABYLON.serialize()
  74676. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  74677. __decorate([
  74678. BABYLON.serialize()
  74679. ], ProceduralTexture.prototype, "isEnabled", void 0);
  74680. __decorate([
  74681. BABYLON.serialize()
  74682. ], ProceduralTexture.prototype, "refreshRate", null);
  74683. return ProceduralTexture;
  74684. }(BABYLON.Texture));
  74685. BABYLON.ProceduralTexture = ProceduralTexture;
  74686. })(BABYLON || (BABYLON = {}));
  74687. //# sourceMappingURL=babylon.proceduralTexture.js.map
  74688. var BABYLON;
  74689. (function (BABYLON) {
  74690. /**
  74691. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  74692. * in a given scene.
  74693. */
  74694. var ProceduralTextureSceneComponent = /** @class */ (function () {
  74695. /**
  74696. * Creates a new instance of the component for the given scene
  74697. * @param scene Defines the scene to register the component in
  74698. */
  74699. function ProceduralTextureSceneComponent(scene) {
  74700. /**
  74701. * The component name helpfull to identify the component in the list of scene components.
  74702. */
  74703. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  74704. this.scene = scene;
  74705. this.scene.proceduralTextures = new Array();
  74706. scene.layers = new Array();
  74707. }
  74708. /**
  74709. * Registers the component in a given scene
  74710. */
  74711. ProceduralTextureSceneComponent.prototype.register = function () {
  74712. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  74713. };
  74714. /**
  74715. * Rebuilds the elements related to this component in case of
  74716. * context lost for instance.
  74717. */
  74718. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  74719. // Nothing to do here.
  74720. };
  74721. /**
  74722. * Disposes the component and the associated ressources.
  74723. */
  74724. ProceduralTextureSceneComponent.prototype.dispose = function () {
  74725. // Nothing to do here.
  74726. };
  74727. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  74728. if (this.scene.proceduralTexturesEnabled) {
  74729. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  74730. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  74731. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  74732. if (proceduralTexture._shouldRender()) {
  74733. proceduralTexture.render();
  74734. }
  74735. }
  74736. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  74737. }
  74738. };
  74739. return ProceduralTextureSceneComponent;
  74740. }());
  74741. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  74742. })(BABYLON || (BABYLON = {}));
  74743. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  74744. var BABYLON;
  74745. (function (BABYLON) {
  74746. var CustomProceduralTexture = /** @class */ (function (_super) {
  74747. __extends(CustomProceduralTexture, _super);
  74748. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  74749. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  74750. _this._animate = true;
  74751. _this._time = 0;
  74752. _this._texturePath = texturePath;
  74753. //Try to load json
  74754. _this.loadJson(texturePath);
  74755. _this.refreshRate = 1;
  74756. return _this;
  74757. }
  74758. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  74759. var _this = this;
  74760. var noConfigFile = function () {
  74761. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  74762. try {
  74763. _this.setFragment(_this._texturePath);
  74764. }
  74765. catch (ex) {
  74766. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  74767. }
  74768. };
  74769. var configFileUrl = jsonUrl + "/config.json";
  74770. var xhr = new XMLHttpRequest();
  74771. xhr.open("GET", configFileUrl, true);
  74772. xhr.addEventListener("load", function () {
  74773. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  74774. try {
  74775. _this._config = JSON.parse(xhr.response);
  74776. _this.updateShaderUniforms();
  74777. _this.updateTextures();
  74778. _this.setFragment(_this._texturePath + "/custom");
  74779. _this._animate = _this._config.animate;
  74780. _this.refreshRate = _this._config.refreshrate;
  74781. }
  74782. catch (ex) {
  74783. noConfigFile();
  74784. }
  74785. }
  74786. else {
  74787. noConfigFile();
  74788. }
  74789. }, false);
  74790. xhr.addEventListener("error", function () {
  74791. noConfigFile();
  74792. }, false);
  74793. try {
  74794. xhr.send();
  74795. }
  74796. catch (ex) {
  74797. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  74798. }
  74799. };
  74800. CustomProceduralTexture.prototype.isReady = function () {
  74801. if (!_super.prototype.isReady.call(this)) {
  74802. return false;
  74803. }
  74804. for (var name in this._textures) {
  74805. var texture = this._textures[name];
  74806. if (!texture.isReady()) {
  74807. return false;
  74808. }
  74809. }
  74810. return true;
  74811. };
  74812. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  74813. var scene = this.getScene();
  74814. if (this._animate && scene) {
  74815. this._time += scene.getAnimationRatio() * 0.03;
  74816. this.updateShaderUniforms();
  74817. }
  74818. _super.prototype.render.call(this, useCameraPostProcess);
  74819. };
  74820. CustomProceduralTexture.prototype.updateTextures = function () {
  74821. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  74822. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  74823. }
  74824. };
  74825. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  74826. if (this._config) {
  74827. for (var j = 0; j < this._config.uniforms.length; j++) {
  74828. var uniform = this._config.uniforms[j];
  74829. switch (uniform.type) {
  74830. case "float":
  74831. this.setFloat(uniform.name, uniform.value);
  74832. break;
  74833. case "color3":
  74834. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  74835. break;
  74836. case "color4":
  74837. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  74838. break;
  74839. case "vector2":
  74840. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  74841. break;
  74842. case "vector3":
  74843. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  74844. break;
  74845. }
  74846. }
  74847. }
  74848. this.setFloat("time", this._time);
  74849. };
  74850. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  74851. get: function () {
  74852. return this._animate;
  74853. },
  74854. set: function (value) {
  74855. this._animate = value;
  74856. },
  74857. enumerable: true,
  74858. configurable: true
  74859. });
  74860. return CustomProceduralTexture;
  74861. }(BABYLON.ProceduralTexture));
  74862. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  74863. })(BABYLON || (BABYLON = {}));
  74864. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  74865. var BABYLON;
  74866. (function (BABYLON) {
  74867. var FreeCameraGamepadInput = /** @class */ (function () {
  74868. function FreeCameraGamepadInput() {
  74869. this.gamepadAngularSensibility = 200;
  74870. this.gamepadMoveSensibility = 40;
  74871. // private members
  74872. this._cameraTransform = BABYLON.Matrix.Identity();
  74873. this._deltaTransform = BABYLON.Vector3.Zero();
  74874. this._vector3 = BABYLON.Vector3.Zero();
  74875. this._vector2 = BABYLON.Vector2.Zero();
  74876. }
  74877. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  74878. var _this = this;
  74879. var manager = this.camera.getScene().gamepadManager;
  74880. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74881. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  74882. // prioritize XBOX gamepads.
  74883. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  74884. _this.gamepad = gamepad;
  74885. }
  74886. }
  74887. });
  74888. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74889. if (_this.gamepad === gamepad) {
  74890. _this.gamepad = null;
  74891. }
  74892. });
  74893. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  74894. };
  74895. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  74896. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74897. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74898. this.gamepad = null;
  74899. };
  74900. FreeCameraGamepadInput.prototype.checkInputs = function () {
  74901. if (this.gamepad && this.gamepad.leftStick) {
  74902. var camera = this.camera;
  74903. var LSValues = this.gamepad.leftStick;
  74904. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  74905. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  74906. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  74907. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  74908. var RSValues = this.gamepad.rightStick;
  74909. if (RSValues) {
  74910. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  74911. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  74912. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  74913. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  74914. }
  74915. else {
  74916. RSValues = { x: 0, y: 0 };
  74917. }
  74918. if (!camera.rotationQuaternion) {
  74919. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  74920. }
  74921. else {
  74922. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  74923. }
  74924. var speed = camera._computeLocalCameraSpeed() * 50.0;
  74925. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  74926. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  74927. camera.cameraDirection.addInPlace(this._deltaTransform);
  74928. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  74929. camera.cameraRotation.addInPlace(this._vector2);
  74930. }
  74931. };
  74932. FreeCameraGamepadInput.prototype.getClassName = function () {
  74933. return "FreeCameraGamepadInput";
  74934. };
  74935. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  74936. return "gamepad";
  74937. };
  74938. __decorate([
  74939. BABYLON.serialize()
  74940. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  74941. __decorate([
  74942. BABYLON.serialize()
  74943. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  74944. return FreeCameraGamepadInput;
  74945. }());
  74946. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  74947. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  74948. })(BABYLON || (BABYLON = {}));
  74949. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  74950. var BABYLON;
  74951. (function (BABYLON) {
  74952. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  74953. function ArcRotateCameraGamepadInput() {
  74954. this.gamepadRotationSensibility = 80;
  74955. this.gamepadMoveSensibility = 40;
  74956. }
  74957. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  74958. var _this = this;
  74959. var manager = this.camera.getScene().gamepadManager;
  74960. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74961. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  74962. // prioritize XBOX gamepads.
  74963. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  74964. _this.gamepad = gamepad;
  74965. }
  74966. }
  74967. });
  74968. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74969. if (_this.gamepad === gamepad) {
  74970. _this.gamepad = null;
  74971. }
  74972. });
  74973. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  74974. };
  74975. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  74976. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74977. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74978. this.gamepad = null;
  74979. };
  74980. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  74981. if (this.gamepad) {
  74982. var camera = this.camera;
  74983. var RSValues = this.gamepad.rightStick;
  74984. if (RSValues) {
  74985. if (RSValues.x != 0) {
  74986. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  74987. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  74988. camera.inertialAlphaOffset += normalizedRX;
  74989. }
  74990. }
  74991. if (RSValues.y != 0) {
  74992. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  74993. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  74994. camera.inertialBetaOffset += normalizedRY;
  74995. }
  74996. }
  74997. }
  74998. var LSValues = this.gamepad.leftStick;
  74999. if (LSValues && LSValues.y != 0) {
  75000. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  75001. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  75002. this.camera.inertialRadiusOffset -= normalizedLY;
  75003. }
  75004. }
  75005. }
  75006. };
  75007. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  75008. return "ArcRotateCameraGamepadInput";
  75009. };
  75010. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  75011. return "gamepad";
  75012. };
  75013. __decorate([
  75014. BABYLON.serialize()
  75015. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  75016. __decorate([
  75017. BABYLON.serialize()
  75018. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  75019. return ArcRotateCameraGamepadInput;
  75020. }());
  75021. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  75022. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  75023. })(BABYLON || (BABYLON = {}));
  75024. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  75025. var BABYLON;
  75026. (function (BABYLON) {
  75027. var GamepadManager = /** @class */ (function () {
  75028. function GamepadManager(_scene) {
  75029. var _this = this;
  75030. this._scene = _scene;
  75031. this._babylonGamepads = [];
  75032. this._oneGamepadConnected = false;
  75033. /** @hidden */
  75034. this._isMonitoring = false;
  75035. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  75036. if (!BABYLON.Tools.IsWindowObjectExist()) {
  75037. this._gamepadEventSupported = false;
  75038. }
  75039. else {
  75040. this._gamepadEventSupported = 'GamepadEvent' in window;
  75041. this._gamepadSupport = (navigator.getGamepads ||
  75042. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  75043. }
  75044. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  75045. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  75046. for (var i in _this._babylonGamepads) {
  75047. var gamepad = _this._babylonGamepads[i];
  75048. if (gamepad && gamepad._isConnected) {
  75049. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  75050. }
  75051. }
  75052. });
  75053. this._onGamepadConnectedEvent = function (evt) {
  75054. var gamepad = evt.gamepad;
  75055. if (gamepad.index in _this._babylonGamepads) {
  75056. if (_this._babylonGamepads[gamepad.index].isConnected) {
  75057. return;
  75058. }
  75059. }
  75060. var newGamepad;
  75061. if (_this._babylonGamepads[gamepad.index]) {
  75062. newGamepad = _this._babylonGamepads[gamepad.index];
  75063. newGamepad.browserGamepad = gamepad;
  75064. newGamepad._isConnected = true;
  75065. }
  75066. else {
  75067. newGamepad = _this._addNewGamepad(gamepad);
  75068. }
  75069. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  75070. _this._startMonitoringGamepads();
  75071. };
  75072. this._onGamepadDisconnectedEvent = function (evt) {
  75073. var gamepad = evt.gamepad;
  75074. // Remove the gamepad from the list of gamepads to monitor.
  75075. for (var i in _this._babylonGamepads) {
  75076. if (_this._babylonGamepads[i].index === gamepad.index) {
  75077. var disconnectedGamepad = _this._babylonGamepads[i];
  75078. disconnectedGamepad._isConnected = false;
  75079. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  75080. break;
  75081. }
  75082. }
  75083. };
  75084. if (this._gamepadSupport) {
  75085. //first add already-connected gamepads
  75086. this._updateGamepadObjects();
  75087. if (this._babylonGamepads.length) {
  75088. this._startMonitoringGamepads();
  75089. }
  75090. // Checking if the gamepad connected event is supported (like in Firefox)
  75091. if (this._gamepadEventSupported) {
  75092. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  75093. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  75094. }
  75095. else {
  75096. this._startMonitoringGamepads();
  75097. }
  75098. }
  75099. }
  75100. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  75101. get: function () {
  75102. return this._babylonGamepads;
  75103. },
  75104. enumerable: true,
  75105. configurable: true
  75106. });
  75107. GamepadManager.prototype.getGamepadByType = function (type) {
  75108. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  75109. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  75110. var gamepad = _a[_i];
  75111. if (gamepad && gamepad.type === type) {
  75112. return gamepad;
  75113. }
  75114. }
  75115. return null;
  75116. };
  75117. GamepadManager.prototype.dispose = function () {
  75118. if (this._gamepadEventSupported) {
  75119. if (this._onGamepadConnectedEvent) {
  75120. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  75121. }
  75122. if (this._onGamepadDisconnectedEvent) {
  75123. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  75124. }
  75125. this._onGamepadConnectedEvent = null;
  75126. this._onGamepadDisconnectedEvent = null;
  75127. }
  75128. this._babylonGamepads.forEach(function (gamepad) {
  75129. gamepad.dispose();
  75130. });
  75131. this.onGamepadConnectedObservable.clear();
  75132. this.onGamepadDisconnectedObservable.clear();
  75133. this._oneGamepadConnected = false;
  75134. this._stopMonitoringGamepads();
  75135. this._babylonGamepads = [];
  75136. };
  75137. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  75138. if (!this._oneGamepadConnected) {
  75139. this._oneGamepadConnected = true;
  75140. }
  75141. var newGamepad;
  75142. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  75143. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  75144. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  75145. }
  75146. // if pose is supported, use the (WebVR) pose enabled controller
  75147. else if (gamepad.pose) {
  75148. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  75149. }
  75150. else {
  75151. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  75152. }
  75153. this._babylonGamepads[newGamepad.index] = newGamepad;
  75154. return newGamepad;
  75155. };
  75156. GamepadManager.prototype._startMonitoringGamepads = function () {
  75157. if (!this._isMonitoring) {
  75158. this._isMonitoring = true;
  75159. //back-comp
  75160. if (!this._scene) {
  75161. this._checkGamepadsStatus();
  75162. }
  75163. }
  75164. };
  75165. GamepadManager.prototype._stopMonitoringGamepads = function () {
  75166. this._isMonitoring = false;
  75167. };
  75168. /** @hidden */
  75169. GamepadManager.prototype._checkGamepadsStatus = function () {
  75170. var _this = this;
  75171. // Hack to be compatible Chrome
  75172. this._updateGamepadObjects();
  75173. for (var i in this._babylonGamepads) {
  75174. var gamepad = this._babylonGamepads[i];
  75175. if (!gamepad || !gamepad.isConnected) {
  75176. continue;
  75177. }
  75178. gamepad.update();
  75179. }
  75180. if (this._isMonitoring && !this._scene) {
  75181. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  75182. }
  75183. };
  75184. // This function is called only on Chrome, which does not properly support
  75185. // connection/disconnection events and forces you to recopy again the gamepad object
  75186. GamepadManager.prototype._updateGamepadObjects = function () {
  75187. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  75188. for (var i = 0; i < gamepads.length; i++) {
  75189. var gamepad = gamepads[i];
  75190. if (gamepad) {
  75191. if (!this._babylonGamepads[gamepad.index]) {
  75192. var newGamepad = this._addNewGamepad(gamepad);
  75193. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  75194. }
  75195. else {
  75196. // Forced to copy again this object for Chrome for unknown reason
  75197. this._babylonGamepads[i].browserGamepad = gamepad;
  75198. if (!this._babylonGamepads[i].isConnected) {
  75199. this._babylonGamepads[i]._isConnected = true;
  75200. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  75201. }
  75202. }
  75203. }
  75204. }
  75205. };
  75206. return GamepadManager;
  75207. }());
  75208. BABYLON.GamepadManager = GamepadManager;
  75209. })(BABYLON || (BABYLON = {}));
  75210. //# sourceMappingURL=babylon.gamepadManager.js.map
  75211. var BABYLON;
  75212. (function (BABYLON) {
  75213. var StickValues = /** @class */ (function () {
  75214. function StickValues(x, y) {
  75215. this.x = x;
  75216. this.y = y;
  75217. }
  75218. return StickValues;
  75219. }());
  75220. BABYLON.StickValues = StickValues;
  75221. var Gamepad = /** @class */ (function () {
  75222. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  75223. if (leftStickX === void 0) { leftStickX = 0; }
  75224. if (leftStickY === void 0) { leftStickY = 1; }
  75225. if (rightStickX === void 0) { rightStickX = 2; }
  75226. if (rightStickY === void 0) { rightStickY = 3; }
  75227. this.id = id;
  75228. this.index = index;
  75229. this.browserGamepad = browserGamepad;
  75230. this._leftStick = { x: 0, y: 0 };
  75231. this._rightStick = { x: 0, y: 0 };
  75232. /** @hidden */
  75233. this._isConnected = true;
  75234. this._invertLeftStickY = false;
  75235. this.type = Gamepad.GAMEPAD;
  75236. this._leftStickAxisX = leftStickX;
  75237. this._leftStickAxisY = leftStickY;
  75238. this._rightStickAxisX = rightStickX;
  75239. this._rightStickAxisY = rightStickY;
  75240. if (this.browserGamepad.axes.length >= 2) {
  75241. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  75242. }
  75243. if (this.browserGamepad.axes.length >= 4) {
  75244. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  75245. }
  75246. }
  75247. Object.defineProperty(Gamepad.prototype, "isConnected", {
  75248. get: function () {
  75249. return this._isConnected;
  75250. },
  75251. enumerable: true,
  75252. configurable: true
  75253. });
  75254. Gamepad.prototype.onleftstickchanged = function (callback) {
  75255. this._onleftstickchanged = callback;
  75256. };
  75257. Gamepad.prototype.onrightstickchanged = function (callback) {
  75258. this._onrightstickchanged = callback;
  75259. };
  75260. Object.defineProperty(Gamepad.prototype, "leftStick", {
  75261. get: function () {
  75262. return this._leftStick;
  75263. },
  75264. set: function (newValues) {
  75265. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  75266. this._onleftstickchanged(newValues);
  75267. }
  75268. this._leftStick = newValues;
  75269. },
  75270. enumerable: true,
  75271. configurable: true
  75272. });
  75273. Object.defineProperty(Gamepad.prototype, "rightStick", {
  75274. get: function () {
  75275. return this._rightStick;
  75276. },
  75277. set: function (newValues) {
  75278. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  75279. this._onrightstickchanged(newValues);
  75280. }
  75281. this._rightStick = newValues;
  75282. },
  75283. enumerable: true,
  75284. configurable: true
  75285. });
  75286. Gamepad.prototype.update = function () {
  75287. if (this._leftStick) {
  75288. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  75289. if (this._invertLeftStickY) {
  75290. this.leftStick.y *= -1;
  75291. }
  75292. }
  75293. if (this._rightStick) {
  75294. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  75295. }
  75296. };
  75297. Gamepad.prototype.dispose = function () {
  75298. };
  75299. Gamepad.GAMEPAD = 0;
  75300. Gamepad.GENERIC = 1;
  75301. Gamepad.XBOX = 2;
  75302. Gamepad.POSE_ENABLED = 3;
  75303. return Gamepad;
  75304. }());
  75305. BABYLON.Gamepad = Gamepad;
  75306. var GenericPad = /** @class */ (function (_super) {
  75307. __extends(GenericPad, _super);
  75308. function GenericPad(id, index, browserGamepad) {
  75309. var _this = _super.call(this, id, index, browserGamepad) || this;
  75310. _this.onButtonDownObservable = new BABYLON.Observable();
  75311. _this.onButtonUpObservable = new BABYLON.Observable();
  75312. _this.type = Gamepad.GENERIC;
  75313. _this._buttons = new Array(browserGamepad.buttons.length);
  75314. return _this;
  75315. }
  75316. GenericPad.prototype.onbuttondown = function (callback) {
  75317. this._onbuttondown = callback;
  75318. };
  75319. GenericPad.prototype.onbuttonup = function (callback) {
  75320. this._onbuttonup = callback;
  75321. };
  75322. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  75323. if (newValue !== currentValue) {
  75324. if (newValue === 1) {
  75325. if (this._onbuttondown) {
  75326. this._onbuttondown(buttonIndex);
  75327. }
  75328. this.onButtonDownObservable.notifyObservers(buttonIndex);
  75329. }
  75330. if (newValue === 0) {
  75331. if (this._onbuttonup) {
  75332. this._onbuttonup(buttonIndex);
  75333. }
  75334. this.onButtonUpObservable.notifyObservers(buttonIndex);
  75335. }
  75336. }
  75337. return newValue;
  75338. };
  75339. GenericPad.prototype.update = function () {
  75340. _super.prototype.update.call(this);
  75341. for (var index = 0; index < this._buttons.length; index++) {
  75342. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  75343. }
  75344. };
  75345. GenericPad.prototype.dispose = function () {
  75346. _super.prototype.dispose.call(this);
  75347. this.onButtonDownObservable.clear();
  75348. this.onButtonUpObservable.clear();
  75349. };
  75350. return GenericPad;
  75351. }(Gamepad));
  75352. BABYLON.GenericPad = GenericPad;
  75353. })(BABYLON || (BABYLON = {}));
  75354. //# sourceMappingURL=babylon.gamepad.js.map
  75355. var BABYLON;
  75356. (function (BABYLON) {
  75357. /**
  75358. * Defines supported buttons for XBox360 compatible gamepads
  75359. */
  75360. var Xbox360Button;
  75361. (function (Xbox360Button) {
  75362. /** A */
  75363. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  75364. /** B */
  75365. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  75366. /** X */
  75367. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  75368. /** Y */
  75369. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  75370. /** Start */
  75371. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  75372. /** Back */
  75373. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  75374. /** Left button */
  75375. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  75376. /** Right button */
  75377. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  75378. /** Left stick */
  75379. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  75380. /** Right stick */
  75381. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  75382. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  75383. /** Defines values for XBox360 DPad */
  75384. var Xbox360Dpad;
  75385. (function (Xbox360Dpad) {
  75386. /** Up */
  75387. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  75388. /** Down */
  75389. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  75390. /** Left */
  75391. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  75392. /** Right */
  75393. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  75394. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  75395. /**
  75396. * Defines a XBox360 gamepad
  75397. */
  75398. var Xbox360Pad = /** @class */ (function (_super) {
  75399. __extends(Xbox360Pad, _super);
  75400. /**
  75401. * Creates a new XBox360 gamepad object
  75402. * @param id defines the id of this gamepad
  75403. * @param index defines its index
  75404. * @param gamepad defines the internal HTML gamepad object
  75405. * @param xboxOne defines if it is a XBox One gamepad
  75406. */
  75407. function Xbox360Pad(id, index, gamepad, xboxOne) {
  75408. if (xboxOne === void 0) { xboxOne = false; }
  75409. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  75410. _this._leftTrigger = 0;
  75411. _this._rightTrigger = 0;
  75412. /** Observable raised when a button is pressed */
  75413. _this.onButtonDownObservable = new BABYLON.Observable();
  75414. /** Observable raised when a button is released */
  75415. _this.onButtonUpObservable = new BABYLON.Observable();
  75416. /** Observable raised when a pad is pressed */
  75417. _this.onPadDownObservable = new BABYLON.Observable();
  75418. /** Observable raised when a pad is released */
  75419. _this.onPadUpObservable = new BABYLON.Observable();
  75420. _this._buttonA = 0;
  75421. _this._buttonB = 0;
  75422. _this._buttonX = 0;
  75423. _this._buttonY = 0;
  75424. _this._buttonBack = 0;
  75425. _this._buttonStart = 0;
  75426. _this._buttonLB = 0;
  75427. _this._buttonRB = 0;
  75428. _this._buttonLeftStick = 0;
  75429. _this._buttonRightStick = 0;
  75430. _this._dPadUp = 0;
  75431. _this._dPadDown = 0;
  75432. _this._dPadLeft = 0;
  75433. _this._dPadRight = 0;
  75434. _this._isXboxOnePad = false;
  75435. _this.type = BABYLON.Gamepad.XBOX;
  75436. _this._isXboxOnePad = xboxOne;
  75437. return _this;
  75438. }
  75439. /**
  75440. * Defines the callback to call when left trigger is pressed
  75441. * @param callback defines the callback to use
  75442. */
  75443. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  75444. this._onlefttriggerchanged = callback;
  75445. };
  75446. /**
  75447. * Defines the callback to call when right trigger is pressed
  75448. * @param callback defines the callback to use
  75449. */
  75450. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  75451. this._onrighttriggerchanged = callback;
  75452. };
  75453. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  75454. /**
  75455. * Gets or sets left trigger value
  75456. */
  75457. get: function () {
  75458. return this._leftTrigger;
  75459. },
  75460. set: function (newValue) {
  75461. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  75462. this._onlefttriggerchanged(newValue);
  75463. }
  75464. this._leftTrigger = newValue;
  75465. },
  75466. enumerable: true,
  75467. configurable: true
  75468. });
  75469. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  75470. /**
  75471. * Gets or sets right trigger value
  75472. */
  75473. get: function () {
  75474. return this._rightTrigger;
  75475. },
  75476. set: function (newValue) {
  75477. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  75478. this._onrighttriggerchanged(newValue);
  75479. }
  75480. this._rightTrigger = newValue;
  75481. },
  75482. enumerable: true,
  75483. configurable: true
  75484. });
  75485. /**
  75486. * Defines the callback to call when a button is pressed
  75487. * @param callback defines the callback to use
  75488. */
  75489. Xbox360Pad.prototype.onbuttondown = function (callback) {
  75490. this._onbuttondown = callback;
  75491. };
  75492. /**
  75493. * Defines the callback to call when a button is released
  75494. * @param callback defines the callback to use
  75495. */
  75496. Xbox360Pad.prototype.onbuttonup = function (callback) {
  75497. this._onbuttonup = callback;
  75498. };
  75499. /**
  75500. * Defines the callback to call when a pad is pressed
  75501. * @param callback defines the callback to use
  75502. */
  75503. Xbox360Pad.prototype.ondpaddown = function (callback) {
  75504. this._ondpaddown = callback;
  75505. };
  75506. /**
  75507. * Defines the callback to call when a pad is released
  75508. * @param callback defines the callback to use
  75509. */
  75510. Xbox360Pad.prototype.ondpadup = function (callback) {
  75511. this._ondpadup = callback;
  75512. };
  75513. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  75514. if (newValue !== currentValue) {
  75515. if (newValue === 1) {
  75516. if (this._onbuttondown) {
  75517. this._onbuttondown(buttonType);
  75518. }
  75519. this.onButtonDownObservable.notifyObservers(buttonType);
  75520. }
  75521. if (newValue === 0) {
  75522. if (this._onbuttonup) {
  75523. this._onbuttonup(buttonType);
  75524. }
  75525. this.onButtonUpObservable.notifyObservers(buttonType);
  75526. }
  75527. }
  75528. return newValue;
  75529. };
  75530. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  75531. if (newValue !== currentValue) {
  75532. if (newValue === 1) {
  75533. if (this._ondpaddown) {
  75534. this._ondpaddown(buttonType);
  75535. }
  75536. this.onPadDownObservable.notifyObservers(buttonType);
  75537. }
  75538. if (newValue === 0) {
  75539. if (this._ondpadup) {
  75540. this._ondpadup(buttonType);
  75541. }
  75542. this.onPadUpObservable.notifyObservers(buttonType);
  75543. }
  75544. }
  75545. return newValue;
  75546. };
  75547. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  75548. /** Gets or sets value of A button */
  75549. get: function () {
  75550. return this._buttonA;
  75551. },
  75552. set: function (value) {
  75553. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  75554. },
  75555. enumerable: true,
  75556. configurable: true
  75557. });
  75558. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  75559. /** Gets or sets value of B button */
  75560. get: function () {
  75561. return this._buttonB;
  75562. },
  75563. set: function (value) {
  75564. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  75565. },
  75566. enumerable: true,
  75567. configurable: true
  75568. });
  75569. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  75570. /** Gets or sets value of X button */
  75571. get: function () {
  75572. return this._buttonX;
  75573. },
  75574. set: function (value) {
  75575. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  75576. },
  75577. enumerable: true,
  75578. configurable: true
  75579. });
  75580. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  75581. /** Gets or sets value of Y button */
  75582. get: function () {
  75583. return this._buttonY;
  75584. },
  75585. set: function (value) {
  75586. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  75587. },
  75588. enumerable: true,
  75589. configurable: true
  75590. });
  75591. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  75592. /** Gets or sets value of Start button */
  75593. get: function () {
  75594. return this._buttonStart;
  75595. },
  75596. set: function (value) {
  75597. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  75598. },
  75599. enumerable: true,
  75600. configurable: true
  75601. });
  75602. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  75603. /** Gets or sets value of Back button */
  75604. get: function () {
  75605. return this._buttonBack;
  75606. },
  75607. set: function (value) {
  75608. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  75609. },
  75610. enumerable: true,
  75611. configurable: true
  75612. });
  75613. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  75614. /** Gets or sets value of Left button */
  75615. get: function () {
  75616. return this._buttonLB;
  75617. },
  75618. set: function (value) {
  75619. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  75620. },
  75621. enumerable: true,
  75622. configurable: true
  75623. });
  75624. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  75625. /** Gets or sets value of Right button */
  75626. get: function () {
  75627. return this._buttonRB;
  75628. },
  75629. set: function (value) {
  75630. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  75631. },
  75632. enumerable: true,
  75633. configurable: true
  75634. });
  75635. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  75636. /** Gets or sets value of left stick */
  75637. get: function () {
  75638. return this._buttonLeftStick;
  75639. },
  75640. set: function (value) {
  75641. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  75642. },
  75643. enumerable: true,
  75644. configurable: true
  75645. });
  75646. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  75647. /** Gets or sets value of right stick */
  75648. get: function () {
  75649. return this._buttonRightStick;
  75650. },
  75651. set: function (value) {
  75652. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  75653. },
  75654. enumerable: true,
  75655. configurable: true
  75656. });
  75657. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  75658. /** Gets or sets value of DPad up */
  75659. get: function () {
  75660. return this._dPadUp;
  75661. },
  75662. set: function (value) {
  75663. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  75664. },
  75665. enumerable: true,
  75666. configurable: true
  75667. });
  75668. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  75669. /** Gets or sets value of DPad down */
  75670. get: function () {
  75671. return this._dPadDown;
  75672. },
  75673. set: function (value) {
  75674. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  75675. },
  75676. enumerable: true,
  75677. configurable: true
  75678. });
  75679. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  75680. /** Gets or sets value of DPad left */
  75681. get: function () {
  75682. return this._dPadLeft;
  75683. },
  75684. set: function (value) {
  75685. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  75686. },
  75687. enumerable: true,
  75688. configurable: true
  75689. });
  75690. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  75691. /** Gets or sets value of DPad right */
  75692. get: function () {
  75693. return this._dPadRight;
  75694. },
  75695. set: function (value) {
  75696. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  75697. },
  75698. enumerable: true,
  75699. configurable: true
  75700. });
  75701. /**
  75702. * Force the gamepad to synchronize with device values
  75703. */
  75704. Xbox360Pad.prototype.update = function () {
  75705. _super.prototype.update.call(this);
  75706. if (this._isXboxOnePad) {
  75707. this.buttonA = this.browserGamepad.buttons[0].value;
  75708. this.buttonB = this.browserGamepad.buttons[1].value;
  75709. this.buttonX = this.browserGamepad.buttons[2].value;
  75710. this.buttonY = this.browserGamepad.buttons[3].value;
  75711. this.buttonLB = this.browserGamepad.buttons[4].value;
  75712. this.buttonRB = this.browserGamepad.buttons[5].value;
  75713. this.leftTrigger = this.browserGamepad.axes[2];
  75714. this.rightTrigger = this.browserGamepad.axes[5];
  75715. this.buttonBack = this.browserGamepad.buttons[9].value;
  75716. this.buttonStart = this.browserGamepad.buttons[8].value;
  75717. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  75718. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  75719. this.dPadUp = this.browserGamepad.buttons[11].value;
  75720. this.dPadDown = this.browserGamepad.buttons[12].value;
  75721. this.dPadLeft = this.browserGamepad.buttons[13].value;
  75722. this.dPadRight = this.browserGamepad.buttons[14].value;
  75723. }
  75724. else {
  75725. this.buttonA = this.browserGamepad.buttons[0].value;
  75726. this.buttonB = this.browserGamepad.buttons[1].value;
  75727. this.buttonX = this.browserGamepad.buttons[2].value;
  75728. this.buttonY = this.browserGamepad.buttons[3].value;
  75729. this.buttonLB = this.browserGamepad.buttons[4].value;
  75730. this.buttonRB = this.browserGamepad.buttons[5].value;
  75731. this.leftTrigger = this.browserGamepad.buttons[6].value;
  75732. this.rightTrigger = this.browserGamepad.buttons[7].value;
  75733. this.buttonBack = this.browserGamepad.buttons[8].value;
  75734. this.buttonStart = this.browserGamepad.buttons[9].value;
  75735. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  75736. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  75737. this.dPadUp = this.browserGamepad.buttons[12].value;
  75738. this.dPadDown = this.browserGamepad.buttons[13].value;
  75739. this.dPadLeft = this.browserGamepad.buttons[14].value;
  75740. this.dPadRight = this.browserGamepad.buttons[15].value;
  75741. }
  75742. };
  75743. Xbox360Pad.prototype.dispose = function () {
  75744. _super.prototype.dispose.call(this);
  75745. this.onButtonDownObservable.clear();
  75746. this.onButtonUpObservable.clear();
  75747. this.onPadDownObservable.clear();
  75748. this.onPadUpObservable.clear();
  75749. };
  75750. return Xbox360Pad;
  75751. }(BABYLON.Gamepad));
  75752. BABYLON.Xbox360Pad = Xbox360Pad;
  75753. })(BABYLON || (BABYLON = {}));
  75754. //# sourceMappingURL=babylon.xboxGamepad.js.map
  75755. var BABYLON;
  75756. (function (BABYLON) {
  75757. /**
  75758. * Defines the types of pose enabled controllers that are supported
  75759. */
  75760. var PoseEnabledControllerType;
  75761. (function (PoseEnabledControllerType) {
  75762. /**
  75763. * HTC Vive
  75764. */
  75765. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  75766. /**
  75767. * Oculus Rift
  75768. */
  75769. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  75770. /**
  75771. * Windows mixed reality
  75772. */
  75773. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  75774. /**
  75775. * Samsung gear VR
  75776. */
  75777. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  75778. /**
  75779. * Google Daydream
  75780. */
  75781. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  75782. /**
  75783. * Generic
  75784. */
  75785. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  75786. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  75787. /**
  75788. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  75789. */
  75790. var PoseEnabledControllerHelper = /** @class */ (function () {
  75791. function PoseEnabledControllerHelper() {
  75792. }
  75793. /**
  75794. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  75795. * @param vrGamepad the gamepad to initialized
  75796. * @returns a vr controller of the type the gamepad identified as
  75797. */
  75798. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  75799. // Oculus Touch
  75800. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  75801. return new BABYLON.OculusTouchController(vrGamepad);
  75802. }
  75803. // Windows Mixed Reality controllers
  75804. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  75805. return new BABYLON.WindowsMotionController(vrGamepad);
  75806. }
  75807. // HTC Vive
  75808. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  75809. return new BABYLON.ViveController(vrGamepad);
  75810. }
  75811. // Samsung/Oculus Gear VR or Oculus Go
  75812. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  75813. return new BABYLON.GearVRController(vrGamepad);
  75814. }
  75815. // Google Daydream
  75816. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  75817. return new BABYLON.DaydreamController(vrGamepad);
  75818. }
  75819. // Generic
  75820. else {
  75821. return new BABYLON.GenericController(vrGamepad);
  75822. }
  75823. };
  75824. return PoseEnabledControllerHelper;
  75825. }());
  75826. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  75827. /**
  75828. * Defines the PoseEnabledController object that contains state of a vr capable controller
  75829. */
  75830. var PoseEnabledController = /** @class */ (function (_super) {
  75831. __extends(PoseEnabledController, _super);
  75832. /**
  75833. * Creates a new PoseEnabledController from a gamepad
  75834. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  75835. */
  75836. function PoseEnabledController(browserGamepad) {
  75837. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  75838. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  75839. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  75840. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  75841. /**
  75842. * The device position in babylon space
  75843. */
  75844. _this.devicePosition = BABYLON.Vector3.Zero();
  75845. /**
  75846. * The device rotation in babylon space
  75847. */
  75848. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  75849. /**
  75850. * The scale factor of the device in babylon space
  75851. */
  75852. _this.deviceScaleFactor = 1;
  75853. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  75854. /**
  75855. * Internal, matrix used to convert room space to babylon space
  75856. * @hidden
  75857. */
  75858. _this._deviceToWorld = BABYLON.Matrix.Identity();
  75859. /**
  75860. * Node to be used when casting a ray from the controller
  75861. * @hidden
  75862. */
  75863. _this._pointingPoseNode = null;
  75864. _this._workingMatrix = BABYLON.Matrix.Identity();
  75865. /**
  75866. * @hidden
  75867. */
  75868. _this._meshAttachedObservable = new BABYLON.Observable();
  75869. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  75870. _this.controllerType = PoseEnabledControllerType.GENERIC;
  75871. _this.position = BABYLON.Vector3.Zero();
  75872. _this.rotationQuaternion = new BABYLON.Quaternion();
  75873. _this._calculatedPosition = BABYLON.Vector3.Zero();
  75874. _this._calculatedRotation = new BABYLON.Quaternion();
  75875. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  75876. return _this;
  75877. }
  75878. /**
  75879. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  75880. */
  75881. PoseEnabledController.prototype.update = function () {
  75882. _super.prototype.update.call(this);
  75883. this._updatePoseAndMesh();
  75884. };
  75885. /**
  75886. * Updates only the pose device and mesh without doing any button event checking
  75887. */
  75888. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  75889. var pose = this.browserGamepad.pose;
  75890. this.updateFromDevice(pose);
  75891. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  75892. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  75893. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  75894. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  75895. if (this._mesh) {
  75896. this._mesh.position.copyFrom(this.devicePosition);
  75897. if (this._mesh.rotationQuaternion) {
  75898. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  75899. }
  75900. }
  75901. };
  75902. /**
  75903. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  75904. * @param poseData raw pose fromthe device
  75905. */
  75906. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  75907. if (poseData) {
  75908. this.rawPose = poseData;
  75909. if (poseData.position) {
  75910. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  75911. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  75912. this._deviceRoomPosition.z *= -1;
  75913. }
  75914. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  75915. this._calculatedPosition.addInPlace(this.position);
  75916. }
  75917. var pose = this.rawPose;
  75918. if (poseData.orientation && pose.orientation) {
  75919. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  75920. if (this._mesh) {
  75921. if (this._mesh.getScene().useRightHandedSystem) {
  75922. this._deviceRoomRotationQuaternion.z *= -1;
  75923. this._deviceRoomRotationQuaternion.w *= -1;
  75924. }
  75925. else {
  75926. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  75927. }
  75928. }
  75929. // if the camera is set, rotate to the camera's rotation
  75930. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  75931. }
  75932. }
  75933. };
  75934. /**
  75935. * Attaches a mesh to the controller
  75936. * @param mesh the mesh to be attached
  75937. */
  75938. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  75939. if (this._mesh) {
  75940. this._mesh.parent = null;
  75941. }
  75942. this._mesh = mesh;
  75943. if (this._poseControlledCamera) {
  75944. this._mesh.parent = this._poseControlledCamera;
  75945. }
  75946. if (!this._mesh.rotationQuaternion) {
  75947. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  75948. }
  75949. // 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
  75950. this._updatePoseAndMesh();
  75951. if (this._pointingPoseNode) {
  75952. var parents = [];
  75953. var obj = this._pointingPoseNode;
  75954. while (obj.parent) {
  75955. parents.push(obj.parent);
  75956. obj = obj.parent;
  75957. }
  75958. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  75959. }
  75960. this._meshAttachedObservable.notifyObservers(mesh);
  75961. };
  75962. /**
  75963. * Attaches the controllers mesh to a camera
  75964. * @param camera the camera the mesh should be attached to
  75965. */
  75966. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  75967. this._poseControlledCamera = camera;
  75968. if (this._mesh) {
  75969. this._mesh.parent = this._poseControlledCamera;
  75970. }
  75971. };
  75972. /**
  75973. * Disposes of the controller
  75974. */
  75975. PoseEnabledController.prototype.dispose = function () {
  75976. if (this._mesh) {
  75977. this._mesh.dispose();
  75978. }
  75979. this._mesh = null;
  75980. _super.prototype.dispose.call(this);
  75981. };
  75982. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  75983. /**
  75984. * The mesh that is attached to the controller
  75985. */
  75986. get: function () {
  75987. return this._mesh;
  75988. },
  75989. enumerable: true,
  75990. configurable: true
  75991. });
  75992. /**
  75993. * Gets the ray of the controller in the direction the controller is pointing
  75994. * @param length the length the resulting ray should be
  75995. * @returns a ray in the direction the controller is pointing
  75996. */
  75997. PoseEnabledController.prototype.getForwardRay = function (length) {
  75998. if (length === void 0) { length = 100; }
  75999. if (!this.mesh) {
  76000. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  76001. }
  76002. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  76003. var origin = m.getTranslation();
  76004. var forward = new BABYLON.Vector3(0, 0, -1);
  76005. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  76006. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  76007. return new BABYLON.Ray(origin, direction, length);
  76008. };
  76009. /**
  76010. * Name of the child mesh that can be used to cast a ray from the controller
  76011. */
  76012. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  76013. return PoseEnabledController;
  76014. }(BABYLON.Gamepad));
  76015. BABYLON.PoseEnabledController = PoseEnabledController;
  76016. })(BABYLON || (BABYLON = {}));
  76017. //# sourceMappingURL=babylon.poseEnabledController.js.map
  76018. var BABYLON;
  76019. (function (BABYLON) {
  76020. /**
  76021. * Defines the WebVRController object that represents controllers tracked in 3D space
  76022. */
  76023. var WebVRController = /** @class */ (function (_super) {
  76024. __extends(WebVRController, _super);
  76025. /**
  76026. * Creates a new WebVRController from a gamepad
  76027. * @param vrGamepad the gamepad that the WebVRController should be created from
  76028. */
  76029. function WebVRController(vrGamepad) {
  76030. var _this = _super.call(this, vrGamepad) || this;
  76031. // Observables
  76032. /**
  76033. * Fired when the trigger state has changed
  76034. */
  76035. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  76036. /**
  76037. * Fired when the main button state has changed
  76038. */
  76039. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  76040. /**
  76041. * Fired when the secondary button state has changed
  76042. */
  76043. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  76044. /**
  76045. * Fired when the pad state has changed
  76046. */
  76047. _this.onPadStateChangedObservable = new BABYLON.Observable();
  76048. /**
  76049. * Fired when controllers stick values have changed
  76050. */
  76051. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  76052. /**
  76053. * X and Y axis corrisponding to the controllers joystick
  76054. */
  76055. _this.pad = { x: 0, y: 0 };
  76056. // avoid GC, store state in a tmp object
  76057. _this._changes = {
  76058. pressChanged: false,
  76059. touchChanged: false,
  76060. valueChanged: false,
  76061. changed: false
  76062. };
  76063. _this._buttons = new Array(vrGamepad.buttons.length);
  76064. _this.hand = vrGamepad.hand;
  76065. return _this;
  76066. }
  76067. /**
  76068. * Fired when a controller button's state has changed
  76069. * @param callback the callback containing the button that was modified
  76070. */
  76071. WebVRController.prototype.onButtonStateChange = function (callback) {
  76072. this._onButtonStateChange = callback;
  76073. };
  76074. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  76075. /**
  76076. * The default controller model for the controller
  76077. */
  76078. get: function () {
  76079. return this._defaultModel;
  76080. },
  76081. enumerable: true,
  76082. configurable: true
  76083. });
  76084. /**
  76085. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  76086. */
  76087. WebVRController.prototype.update = function () {
  76088. _super.prototype.update.call(this);
  76089. for (var index = 0; index < this._buttons.length; index++) {
  76090. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  76091. }
  76092. ;
  76093. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  76094. this.pad.x = this.leftStick.x;
  76095. this.pad.y = this.leftStick.y;
  76096. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  76097. }
  76098. };
  76099. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  76100. if (!newState) {
  76101. newState = {
  76102. pressed: false,
  76103. touched: false,
  76104. value: 0
  76105. };
  76106. }
  76107. if (!currentState) {
  76108. this._buttons[buttonIndex] = {
  76109. pressed: newState.pressed,
  76110. touched: newState.touched,
  76111. value: newState.value
  76112. };
  76113. return;
  76114. }
  76115. this._checkChanges(newState, currentState);
  76116. if (this._changes.changed) {
  76117. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  76118. this._handleButtonChange(buttonIndex, newState, this._changes);
  76119. }
  76120. this._buttons[buttonIndex].pressed = newState.pressed;
  76121. this._buttons[buttonIndex].touched = newState.touched;
  76122. // oculus triggers are never 0, thou not touched.
  76123. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  76124. };
  76125. WebVRController.prototype._checkChanges = function (newState, currentState) {
  76126. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  76127. this._changes.touchChanged = newState.touched !== currentState.touched;
  76128. this._changes.valueChanged = newState.value !== currentState.value;
  76129. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  76130. return this._changes;
  76131. };
  76132. /**
  76133. * Disposes of th webVRCOntroller
  76134. */
  76135. WebVRController.prototype.dispose = function () {
  76136. _super.prototype.dispose.call(this);
  76137. this.onTriggerStateChangedObservable.clear();
  76138. this.onMainButtonStateChangedObservable.clear();
  76139. this.onSecondaryButtonStateChangedObservable.clear();
  76140. this.onPadStateChangedObservable.clear();
  76141. this.onPadValuesChangedObservable.clear();
  76142. };
  76143. return WebVRController;
  76144. }(BABYLON.PoseEnabledController));
  76145. BABYLON.WebVRController = WebVRController;
  76146. })(BABYLON || (BABYLON = {}));
  76147. //# sourceMappingURL=babylon.webVRController.js.map
  76148. var BABYLON;
  76149. (function (BABYLON) {
  76150. /**
  76151. * Oculus Touch Controller
  76152. */
  76153. var OculusTouchController = /** @class */ (function (_super) {
  76154. __extends(OculusTouchController, _super);
  76155. /**
  76156. * Creates a new OculusTouchController from a gamepad
  76157. * @param vrGamepad the gamepad that the controller should be created from
  76158. */
  76159. function OculusTouchController(vrGamepad) {
  76160. var _this = _super.call(this, vrGamepad) || this;
  76161. /**
  76162. * Fired when the secondary trigger on this controller is modified
  76163. */
  76164. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  76165. /**
  76166. * Fired when the thumb rest on this controller is modified
  76167. */
  76168. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  76169. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  76170. return _this;
  76171. }
  76172. /**
  76173. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76174. * @param scene scene in which to add meshes
  76175. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76176. */
  76177. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76178. var _this = this;
  76179. var meshName;
  76180. // Hand
  76181. if (this.hand === 'left') {
  76182. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  76183. }
  76184. else { // Right is the default if no hand is specified
  76185. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  76186. }
  76187. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  76188. /*
  76189. Parent Mesh name: oculus_touch_left
  76190. - body
  76191. - trigger
  76192. - thumbstick
  76193. - grip
  76194. - button_y
  76195. - button_x
  76196. - button_enter
  76197. */
  76198. _this._defaultModel = newMeshes[1];
  76199. _this.attachToMesh(_this._defaultModel);
  76200. if (meshLoaded) {
  76201. meshLoaded(_this._defaultModel);
  76202. }
  76203. });
  76204. };
  76205. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  76206. /**
  76207. * Fired when the A button on this controller is modified
  76208. */
  76209. get: function () {
  76210. if (this.hand === 'right') {
  76211. return this.onMainButtonStateChangedObservable;
  76212. }
  76213. else {
  76214. throw new Error('No A button on left hand');
  76215. }
  76216. },
  76217. enumerable: true,
  76218. configurable: true
  76219. });
  76220. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  76221. /**
  76222. * Fired when the B button on this controller is modified
  76223. */
  76224. get: function () {
  76225. if (this.hand === 'right') {
  76226. return this.onSecondaryButtonStateChangedObservable;
  76227. }
  76228. else {
  76229. throw new Error('No B button on left hand');
  76230. }
  76231. },
  76232. enumerable: true,
  76233. configurable: true
  76234. });
  76235. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  76236. /**
  76237. * Fired when the X button on this controller is modified
  76238. */
  76239. get: function () {
  76240. if (this.hand === 'left') {
  76241. return this.onMainButtonStateChangedObservable;
  76242. }
  76243. else {
  76244. throw new Error('No X button on right hand');
  76245. }
  76246. },
  76247. enumerable: true,
  76248. configurable: true
  76249. });
  76250. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  76251. /**
  76252. * Fired when the Y button on this controller is modified
  76253. */
  76254. get: function () {
  76255. if (this.hand === 'left') {
  76256. return this.onSecondaryButtonStateChangedObservable;
  76257. }
  76258. else {
  76259. throw new Error('No Y button on right hand');
  76260. }
  76261. },
  76262. enumerable: true,
  76263. configurable: true
  76264. });
  76265. /**
  76266. * Called once for each button that changed state since the last frame
  76267. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  76268. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  76269. * 2) secondary trigger (same)
  76270. * 3) A (right) X (left), touch, pressed = value
  76271. * 4) B / Y
  76272. * 5) thumb rest
  76273. * @param buttonIdx Which button index changed
  76274. * @param state New state of the button
  76275. * @param changes Which properties on the state changed since last frame
  76276. */
  76277. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76278. var notifyObject = state; //{ state: state, changes: changes };
  76279. var triggerDirection = this.hand === 'right' ? -1 : 1;
  76280. switch (buttonIdx) {
  76281. case 0:
  76282. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  76283. return;
  76284. case 1: // index trigger
  76285. if (this._defaultModel) {
  76286. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  76287. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  76288. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  76289. }
  76290. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  76291. return;
  76292. case 2: // secondary trigger
  76293. if (this._defaultModel) {
  76294. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  76295. }
  76296. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  76297. return;
  76298. case 3:
  76299. if (this._defaultModel) {
  76300. if (notifyObject.pressed) {
  76301. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  76302. }
  76303. else {
  76304. (this._defaultModel.getChildren()[1]).position.y = 0;
  76305. }
  76306. }
  76307. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  76308. return;
  76309. case 4:
  76310. if (this._defaultModel) {
  76311. if (notifyObject.pressed) {
  76312. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  76313. }
  76314. else {
  76315. (this._defaultModel.getChildren()[2]).position.y = 0;
  76316. }
  76317. }
  76318. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  76319. return;
  76320. case 5:
  76321. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  76322. return;
  76323. }
  76324. };
  76325. /**
  76326. * Base Url for the controller model.
  76327. */
  76328. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  76329. /**
  76330. * File name for the left controller model.
  76331. */
  76332. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  76333. /**
  76334. * File name for the right controller model.
  76335. */
  76336. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  76337. return OculusTouchController;
  76338. }(BABYLON.WebVRController));
  76339. BABYLON.OculusTouchController = OculusTouchController;
  76340. })(BABYLON || (BABYLON = {}));
  76341. //# sourceMappingURL=babylon.oculusTouchController.js.map
  76342. var BABYLON;
  76343. (function (BABYLON) {
  76344. /**
  76345. * Vive Controller
  76346. */
  76347. var ViveController = /** @class */ (function (_super) {
  76348. __extends(ViveController, _super);
  76349. /**
  76350. * Creates a new ViveController from a gamepad
  76351. * @param vrGamepad the gamepad that the controller should be created from
  76352. */
  76353. function ViveController(vrGamepad) {
  76354. var _this = _super.call(this, vrGamepad) || this;
  76355. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  76356. _this._invertLeftStickY = true;
  76357. return _this;
  76358. }
  76359. /**
  76360. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76361. * @param scene scene in which to add meshes
  76362. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76363. */
  76364. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76365. var _this = this;
  76366. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  76367. /*
  76368. Parent Mesh name: ViveWand
  76369. - body
  76370. - r_gripper
  76371. - l_gripper
  76372. - menu_button
  76373. - system_button
  76374. - trackpad
  76375. - trigger
  76376. - LED
  76377. */
  76378. _this._defaultModel = newMeshes[1];
  76379. _this.attachToMesh(_this._defaultModel);
  76380. if (meshLoaded) {
  76381. meshLoaded(_this._defaultModel);
  76382. }
  76383. });
  76384. };
  76385. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  76386. /**
  76387. * Fired when the left button on this controller is modified
  76388. */
  76389. get: function () {
  76390. return this.onMainButtonStateChangedObservable;
  76391. },
  76392. enumerable: true,
  76393. configurable: true
  76394. });
  76395. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  76396. /**
  76397. * Fired when the right button on this controller is modified
  76398. */
  76399. get: function () {
  76400. return this.onMainButtonStateChangedObservable;
  76401. },
  76402. enumerable: true,
  76403. configurable: true
  76404. });
  76405. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  76406. /**
  76407. * Fired when the menu button on this controller is modified
  76408. */
  76409. get: function () {
  76410. return this.onSecondaryButtonStateChangedObservable;
  76411. },
  76412. enumerable: true,
  76413. configurable: true
  76414. });
  76415. /**
  76416. * Called once for each button that changed state since the last frame
  76417. * Vive mapping:
  76418. * 0: touchpad
  76419. * 1: trigger
  76420. * 2: left AND right buttons
  76421. * 3: menu button
  76422. * @param buttonIdx Which button index changed
  76423. * @param state New state of the button
  76424. * @param changes Which properties on the state changed since last frame
  76425. */
  76426. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76427. var notifyObject = state; //{ state: state, changes: changes };
  76428. switch (buttonIdx) {
  76429. case 0:
  76430. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  76431. return;
  76432. case 1: // index trigger
  76433. if (this._defaultModel) {
  76434. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  76435. }
  76436. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  76437. return;
  76438. case 2: // left AND right button
  76439. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  76440. return;
  76441. case 3:
  76442. if (this._defaultModel) {
  76443. if (notifyObject.pressed) {
  76444. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  76445. }
  76446. else {
  76447. (this._defaultModel.getChildren()[2]).position.y = 0;
  76448. }
  76449. }
  76450. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  76451. return;
  76452. }
  76453. };
  76454. /**
  76455. * Base Url for the controller model.
  76456. */
  76457. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  76458. /**
  76459. * File name for the controller model.
  76460. */
  76461. ViveController.MODEL_FILENAME = 'wand.babylon';
  76462. return ViveController;
  76463. }(BABYLON.WebVRController));
  76464. BABYLON.ViveController = ViveController;
  76465. })(BABYLON || (BABYLON = {}));
  76466. //# sourceMappingURL=babylon.viveController.js.map
  76467. var BABYLON;
  76468. (function (BABYLON) {
  76469. /**
  76470. * Generic Controller
  76471. */
  76472. var GenericController = /** @class */ (function (_super) {
  76473. __extends(GenericController, _super);
  76474. /**
  76475. * Creates a new GenericController from a gamepad
  76476. * @param vrGamepad the gamepad that the controller should be created from
  76477. */
  76478. function GenericController(vrGamepad) {
  76479. return _super.call(this, vrGamepad) || this;
  76480. }
  76481. /**
  76482. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76483. * @param scene scene in which to add meshes
  76484. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76485. */
  76486. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76487. var _this = this;
  76488. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  76489. _this._defaultModel = newMeshes[1];
  76490. _this.attachToMesh(_this._defaultModel);
  76491. if (meshLoaded) {
  76492. meshLoaded(_this._defaultModel);
  76493. }
  76494. });
  76495. };
  76496. /**
  76497. * Called once for each button that changed state since the last frame
  76498. * @param buttonIdx Which button index changed
  76499. * @param state New state of the button
  76500. * @param changes Which properties on the state changed since last frame
  76501. */
  76502. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76503. console.log("Button id: " + buttonIdx + "state: ");
  76504. console.dir(state);
  76505. };
  76506. /**
  76507. * Base Url for the controller model.
  76508. */
  76509. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  76510. /**
  76511. * File name for the controller model.
  76512. */
  76513. GenericController.MODEL_FILENAME = 'generic.babylon';
  76514. return GenericController;
  76515. }(BABYLON.WebVRController));
  76516. BABYLON.GenericController = GenericController;
  76517. })(BABYLON || (BABYLON = {}));
  76518. //# sourceMappingURL=babylon.genericController.js.map
  76519. var BABYLON;
  76520. (function (BABYLON) {
  76521. /**
  76522. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  76523. */
  76524. var LoadedMeshInfo = /** @class */ (function () {
  76525. function LoadedMeshInfo() {
  76526. /**
  76527. * Map of the button meshes contained in the controller
  76528. */
  76529. this.buttonMeshes = {};
  76530. /**
  76531. * Map of the axis meshes contained in the controller
  76532. */
  76533. this.axisMeshes = {};
  76534. }
  76535. return LoadedMeshInfo;
  76536. }());
  76537. /**
  76538. * Defines the WindowsMotionController object that the state of the windows motion controller
  76539. */
  76540. var WindowsMotionController = /** @class */ (function (_super) {
  76541. __extends(WindowsMotionController, _super);
  76542. /**
  76543. * Creates a new WindowsMotionController from a gamepad
  76544. * @param vrGamepad the gamepad that the controller should be created from
  76545. */
  76546. function WindowsMotionController(vrGamepad) {
  76547. var _this = _super.call(this, vrGamepad) || this;
  76548. _this._mapping = {
  76549. // Semantic button names
  76550. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  76551. // A mapping of the button name to glTF model node name
  76552. // that should be transformed by button value.
  76553. buttonMeshNames: {
  76554. 'trigger': 'SELECT',
  76555. 'menu': 'MENU',
  76556. 'grip': 'GRASP',
  76557. 'thumbstick': 'THUMBSTICK_PRESS',
  76558. 'trackpad': 'TOUCHPAD_PRESS'
  76559. },
  76560. // This mapping is used to translate from the Motion Controller to Babylon semantics
  76561. buttonObservableNames: {
  76562. 'trigger': 'onTriggerStateChangedObservable',
  76563. 'menu': 'onSecondaryButtonStateChangedObservable',
  76564. 'grip': 'onMainButtonStateChangedObservable',
  76565. 'thumbstick': 'onPadStateChangedObservable',
  76566. 'trackpad': 'onTrackpadChangedObservable'
  76567. },
  76568. // A mapping of the axis name to glTF model node name
  76569. // that should be transformed by axis value.
  76570. // This array mirrors the browserGamepad.axes array, such that
  76571. // the mesh corresponding to axis 0 is in this array index 0.
  76572. axisMeshNames: [
  76573. 'THUMBSTICK_X',
  76574. 'THUMBSTICK_Y',
  76575. 'TOUCHPAD_TOUCH_X',
  76576. 'TOUCHPAD_TOUCH_Y'
  76577. ],
  76578. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  76579. };
  76580. /**
  76581. * Fired when the trackpad on this controller is clicked
  76582. */
  76583. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  76584. /**
  76585. * Fired when the trackpad on this controller is modified
  76586. */
  76587. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  76588. /**
  76589. * The current x and y values of this controller's trackpad
  76590. */
  76591. _this.trackpad = { x: 0, y: 0 };
  76592. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  76593. _this._loadedMeshInfo = null;
  76594. return _this;
  76595. }
  76596. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  76597. /**
  76598. * Fired when the trigger on this controller is modified
  76599. */
  76600. get: function () {
  76601. return this.onTriggerStateChangedObservable;
  76602. },
  76603. enumerable: true,
  76604. configurable: true
  76605. });
  76606. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  76607. /**
  76608. * Fired when the menu button on this controller is modified
  76609. */
  76610. get: function () {
  76611. return this.onSecondaryButtonStateChangedObservable;
  76612. },
  76613. enumerable: true,
  76614. configurable: true
  76615. });
  76616. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  76617. /**
  76618. * Fired when the grip button on this controller is modified
  76619. */
  76620. get: function () {
  76621. return this.onMainButtonStateChangedObservable;
  76622. },
  76623. enumerable: true,
  76624. configurable: true
  76625. });
  76626. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  76627. /**
  76628. * Fired when the thumbstick button on this controller is modified
  76629. */
  76630. get: function () {
  76631. return this.onPadStateChangedObservable;
  76632. },
  76633. enumerable: true,
  76634. configurable: true
  76635. });
  76636. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  76637. /**
  76638. * Fired when the touchpad button on this controller is modified
  76639. */
  76640. get: function () {
  76641. return this.onTrackpadChangedObservable;
  76642. },
  76643. enumerable: true,
  76644. configurable: true
  76645. });
  76646. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  76647. /**
  76648. * Fired when the touchpad values on this controller are modified
  76649. */
  76650. get: function () {
  76651. return this.onTrackpadValuesChangedObservable;
  76652. },
  76653. enumerable: true,
  76654. configurable: true
  76655. });
  76656. WindowsMotionController.prototype._updateTrackpad = function () {
  76657. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  76658. this.trackpad.x = this.browserGamepad["axes"][2];
  76659. this.trackpad.y = this.browserGamepad["axes"][3];
  76660. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  76661. }
  76662. };
  76663. /**
  76664. * Called once per frame by the engine.
  76665. */
  76666. WindowsMotionController.prototype.update = function () {
  76667. _super.prototype.update.call(this);
  76668. if (this.browserGamepad.axes) {
  76669. this._updateTrackpad();
  76670. // Only need to animate axes if there is a loaded mesh
  76671. if (this._loadedMeshInfo) {
  76672. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  76673. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  76674. }
  76675. }
  76676. }
  76677. };
  76678. /**
  76679. * Called once for each button that changed state since the last frame
  76680. * @param buttonIdx Which button index changed
  76681. * @param state New state of the button
  76682. * @param changes Which properties on the state changed since last frame
  76683. */
  76684. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76685. var buttonName = this._mapping.buttons[buttonIdx];
  76686. if (!buttonName) {
  76687. return;
  76688. }
  76689. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  76690. this._updateTrackpad();
  76691. // Only emit events for buttons that we know how to map from index to name
  76692. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  76693. if (observable) {
  76694. observable.notifyObservers(state);
  76695. }
  76696. this._lerpButtonTransform(buttonName, state.value);
  76697. };
  76698. /**
  76699. * Moves the buttons on the controller mesh based on their current state
  76700. * @param buttonName the name of the button to move
  76701. * @param buttonValue the value of the button which determines the buttons new position
  76702. */
  76703. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  76704. // If there is no loaded mesh, there is nothing to transform.
  76705. if (!this._loadedMeshInfo) {
  76706. return;
  76707. }
  76708. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  76709. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  76710. return;
  76711. }
  76712. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  76713. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  76714. };
  76715. /**
  76716. * Moves the axis on the controller mesh based on its current state
  76717. * @param axis the index of the axis
  76718. * @param axisValue the value of the axis which determines the meshes new position
  76719. * @hidden
  76720. */
  76721. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  76722. if (!this._loadedMeshInfo) {
  76723. return;
  76724. }
  76725. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  76726. if (!meshInfo) {
  76727. return;
  76728. }
  76729. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  76730. return;
  76731. }
  76732. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  76733. var lerpValue = axisValue * 0.5 + 0.5;
  76734. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  76735. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  76736. };
  76737. /**
  76738. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76739. * @param scene scene in which to add meshes
  76740. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76741. */
  76742. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  76743. var _this = this;
  76744. if (forceDefault === void 0) { forceDefault = false; }
  76745. var path;
  76746. var filename;
  76747. // Checking if GLB loader is present
  76748. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  76749. // Determine the device specific folder based on the ID suffix
  76750. var device = 'default';
  76751. if (this.id && !forceDefault) {
  76752. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  76753. device = ((match && match[0]) || device);
  76754. }
  76755. // Hand
  76756. if (this.hand === 'left') {
  76757. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  76758. }
  76759. else { // Right is the default if no hand is specified
  76760. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  76761. }
  76762. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  76763. }
  76764. else {
  76765. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  76766. path = BABYLON.GenericController.MODEL_BASE_URL;
  76767. filename = BABYLON.GenericController.MODEL_FILENAME;
  76768. }
  76769. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  76770. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  76771. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  76772. if (!_this._loadedMeshInfo) {
  76773. return;
  76774. }
  76775. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  76776. _this.attachToMesh(_this._defaultModel);
  76777. if (meshLoaded) {
  76778. meshLoaded(_this._defaultModel);
  76779. }
  76780. }, null, function (scene, message) {
  76781. BABYLON.Tools.Log(message);
  76782. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  76783. if (!forceDefault) {
  76784. _this.initControllerMesh(scene, meshLoaded, true);
  76785. }
  76786. });
  76787. };
  76788. /**
  76789. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  76790. * can be transformed by button presses and axes values, based on this._mapping.
  76791. *
  76792. * @param scene scene in which the meshes exist
  76793. * @param meshes list of meshes that make up the controller model to process
  76794. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  76795. */
  76796. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  76797. var loadedMeshInfo = null;
  76798. // Create a new mesh to contain the glTF hierarchy
  76799. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  76800. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  76801. var childMesh = null;
  76802. for (var i = 0; i < meshes.length; i++) {
  76803. var mesh = meshes[i];
  76804. if (!mesh.parent) {
  76805. // Exclude controller meshes from picking results
  76806. mesh.isPickable = false;
  76807. // Handle root node, attach to the new parentMesh
  76808. childMesh = mesh;
  76809. break;
  76810. }
  76811. }
  76812. if (childMesh) {
  76813. childMesh.setParent(parentMesh);
  76814. // Create our mesh info. Note that this method will always return non-null.
  76815. loadedMeshInfo = this.createMeshInfo(parentMesh);
  76816. }
  76817. else {
  76818. BABYLON.Tools.Warn('Could not find root node in model file.');
  76819. }
  76820. return loadedMeshInfo;
  76821. };
  76822. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  76823. var loadedMeshInfo = new LoadedMeshInfo();
  76824. var i;
  76825. loadedMeshInfo.rootNode = rootNode;
  76826. // Reset the caches
  76827. loadedMeshInfo.buttonMeshes = {};
  76828. loadedMeshInfo.axisMeshes = {};
  76829. // Button Meshes
  76830. for (i = 0; i < this._mapping.buttons.length; i++) {
  76831. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  76832. if (!buttonMeshName) {
  76833. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  76834. continue;
  76835. }
  76836. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  76837. if (!buttonMesh) {
  76838. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  76839. continue;
  76840. }
  76841. var buttonMeshInfo = {
  76842. index: i,
  76843. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  76844. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  76845. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  76846. };
  76847. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  76848. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  76849. }
  76850. else {
  76851. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  76852. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  76853. '(VALUE: ' + !!buttonMeshInfo.value +
  76854. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  76855. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  76856. ')');
  76857. }
  76858. }
  76859. // Axis Meshes
  76860. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  76861. var axisMeshName = this._mapping.axisMeshNames[i];
  76862. if (!axisMeshName) {
  76863. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  76864. continue;
  76865. }
  76866. var axisMesh = getChildByName(rootNode, axisMeshName);
  76867. if (!axisMesh) {
  76868. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  76869. continue;
  76870. }
  76871. var axisMeshInfo = {
  76872. index: i,
  76873. value: getImmediateChildByName(axisMesh, 'VALUE'),
  76874. min: getImmediateChildByName(axisMesh, 'MIN'),
  76875. max: getImmediateChildByName(axisMesh, 'MAX')
  76876. };
  76877. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  76878. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  76879. }
  76880. else {
  76881. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  76882. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  76883. '(VALUE: ' + !!axisMeshInfo.value +
  76884. ', MIN: ' + !!axisMeshInfo.min +
  76885. ', MAX:' + !!axisMeshInfo.max +
  76886. ')');
  76887. }
  76888. }
  76889. // Pointing Ray
  76890. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  76891. if (!loadedMeshInfo.pointingPoseNode) {
  76892. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  76893. }
  76894. else {
  76895. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  76896. }
  76897. return loadedMeshInfo;
  76898. // Look through all children recursively. This will return null if no mesh exists with the given name.
  76899. function getChildByName(node, name) {
  76900. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  76901. }
  76902. // Look through only immediate children. This will return null if no mesh exists with the given name.
  76903. function getImmediateChildByName(node, name) {
  76904. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  76905. }
  76906. };
  76907. /**
  76908. * Gets the ray of the controller in the direction the controller is pointing
  76909. * @param length the length the resulting ray should be
  76910. * @returns a ray in the direction the controller is pointing
  76911. */
  76912. WindowsMotionController.prototype.getForwardRay = function (length) {
  76913. if (length === void 0) { length = 100; }
  76914. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  76915. return _super.prototype.getForwardRay.call(this, length);
  76916. }
  76917. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  76918. var origin = m.getTranslation();
  76919. var forward = new BABYLON.Vector3(0, 0, -1);
  76920. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  76921. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  76922. return new BABYLON.Ray(origin, direction, length);
  76923. };
  76924. /**
  76925. * Disposes of the controller
  76926. */
  76927. WindowsMotionController.prototype.dispose = function () {
  76928. _super.prototype.dispose.call(this);
  76929. this.onTrackpadChangedObservable.clear();
  76930. };
  76931. /**
  76932. * The base url used to load the left and right controller models
  76933. */
  76934. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  76935. /**
  76936. * The name of the left controller model file
  76937. */
  76938. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  76939. /**
  76940. * The name of the right controller model file
  76941. */
  76942. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  76943. /**
  76944. * The controller name prefix for this controller type
  76945. */
  76946. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  76947. /**
  76948. * The controller id pattern for this controller type
  76949. */
  76950. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  76951. return WindowsMotionController;
  76952. }(BABYLON.WebVRController));
  76953. BABYLON.WindowsMotionController = WindowsMotionController;
  76954. })(BABYLON || (BABYLON = {}));
  76955. //# sourceMappingURL=babylon.windowsMotionController.js.map
  76956. var BABYLON;
  76957. (function (BABYLON) {
  76958. /**
  76959. * Gear VR Controller
  76960. */
  76961. var GearVRController = /** @class */ (function (_super) {
  76962. __extends(GearVRController, _super);
  76963. /**
  76964. * Creates a new GearVRController from a gamepad
  76965. * @param vrGamepad the gamepad that the controller should be created from
  76966. */
  76967. function GearVRController(vrGamepad) {
  76968. var _this = _super.call(this, vrGamepad) || this;
  76969. _this._maxRotationDistFromHeadset = Math.PI / 5;
  76970. _this._draggedRoomRotation = 0;
  76971. _this._tmpVector = new BABYLON.Vector3();
  76972. _this._buttonIndexToObservableNameMap = [
  76973. 'onTrackpadChangedObservable',
  76974. 'onTriggerStateChangedObservable' // Trigger
  76975. ];
  76976. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  76977. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  76978. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  76979. return _this;
  76980. }
  76981. /**
  76982. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  76983. * @param poseData raw pose fromthe device
  76984. */
  76985. GearVRController.prototype.updateFromDevice = function (poseData) {
  76986. _super.prototype.updateFromDevice.call(this, poseData);
  76987. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  76988. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  76989. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  76990. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  76991. // Find the radian distance away that the headset is from the controllers rotation
  76992. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  76993. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  76994. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  76995. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  76996. this._draggedRoomRotation += rotationAmount;
  76997. // Rotate controller around headset
  76998. var sin = Math.sin(-rotationAmount);
  76999. var cos = Math.cos(-rotationAmount);
  77000. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  77001. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  77002. }
  77003. }
  77004. }
  77005. };
  77006. /**
  77007. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  77008. * @param scene scene in which to add meshes
  77009. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  77010. */
  77011. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  77012. var _this = this;
  77013. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  77014. // Offset the controller so it will rotate around the users wrist
  77015. var mesh = new BABYLON.Mesh("", scene);
  77016. newMeshes[1].parent = mesh;
  77017. newMeshes[1].position.z = -0.15;
  77018. _this._defaultModel = mesh;
  77019. _this.attachToMesh(_this._defaultModel);
  77020. if (meshLoaded) {
  77021. meshLoaded(_this._defaultModel);
  77022. }
  77023. });
  77024. };
  77025. /**
  77026. * Called once for each button that changed state since the last frame
  77027. * @param buttonIdx Which button index changed
  77028. * @param state New state of the button
  77029. * @param changes Which properties on the state changed since last frame
  77030. */
  77031. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  77032. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  77033. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  77034. // Only emit events for buttons that we know how to map from index to observable
  77035. var observable = this[observableName];
  77036. if (observable) {
  77037. observable.notifyObservers(state);
  77038. }
  77039. }
  77040. };
  77041. /**
  77042. * Base Url for the controller model.
  77043. */
  77044. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  77045. /**
  77046. * File name for the controller model.
  77047. */
  77048. GearVRController.MODEL_FILENAME = 'generic.babylon';
  77049. /**
  77050. * Gamepad Id prefix used to identify this controller.
  77051. */
  77052. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  77053. return GearVRController;
  77054. }(BABYLON.WebVRController));
  77055. BABYLON.GearVRController = GearVRController;
  77056. })(BABYLON || (BABYLON = {}));
  77057. //# sourceMappingURL=babylon.gearVRController.js.map
  77058. var BABYLON;
  77059. (function (BABYLON) {
  77060. /**
  77061. * Google Daydream controller
  77062. */
  77063. var DaydreamController = /** @class */ (function (_super) {
  77064. __extends(DaydreamController, _super);
  77065. /**
  77066. * Creates a new DaydreamController from a gamepad
  77067. * @param vrGamepad the gamepad that the controller should be created from
  77068. */
  77069. function DaydreamController(vrGamepad) {
  77070. var _this = _super.call(this, vrGamepad) || this;
  77071. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  77072. return _this;
  77073. }
  77074. /**
  77075. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  77076. * @param scene scene in which to add meshes
  77077. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  77078. */
  77079. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  77080. var _this = this;
  77081. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  77082. _this._defaultModel = newMeshes[1];
  77083. _this.attachToMesh(_this._defaultModel);
  77084. if (meshLoaded) {
  77085. meshLoaded(_this._defaultModel);
  77086. }
  77087. });
  77088. };
  77089. /**
  77090. * Called once for each button that changed state since the last frame
  77091. * @param buttonIdx Which button index changed
  77092. * @param state New state of the button
  77093. * @param changes Which properties on the state changed since last frame
  77094. */
  77095. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  77096. // Daydream controller only has 1 GamepadButton (on the trackpad).
  77097. if (buttonIdx === 0) {
  77098. var observable = this.onTriggerStateChangedObservable;
  77099. if (observable) {
  77100. observable.notifyObservers(state);
  77101. }
  77102. }
  77103. else {
  77104. // If the app or home buttons are ever made available
  77105. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  77106. }
  77107. };
  77108. /**
  77109. * Base Url for the controller model.
  77110. */
  77111. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  77112. /**
  77113. * File name for the controller model.
  77114. */
  77115. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  77116. /**
  77117. * Gamepad Id prefix used to identify Daydream Controller.
  77118. */
  77119. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  77120. return DaydreamController;
  77121. }(BABYLON.WebVRController));
  77122. BABYLON.DaydreamController = DaydreamController;
  77123. })(BABYLON || (BABYLON = {}));
  77124. //# sourceMappingURL=babylon.daydreamController.js.map
  77125. var BABYLON;
  77126. (function (BABYLON) {
  77127. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  77128. get: function () {
  77129. if (!this._gamepadManager) {
  77130. this._gamepadManager = new BABYLON.GamepadManager(this);
  77131. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  77132. if (!component) {
  77133. component = new GamepadSystemSceneComponent(this);
  77134. this._addComponent(component);
  77135. }
  77136. }
  77137. return this._gamepadManager;
  77138. },
  77139. enumerable: true,
  77140. configurable: true
  77141. });
  77142. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  77143. this.add(new BABYLON.FreeCameraGamepadInput());
  77144. return this;
  77145. };
  77146. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  77147. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  77148. return this;
  77149. };
  77150. /**
  77151. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  77152. */
  77153. var GamepadSystemSceneComponent = /** @class */ (function () {
  77154. /**
  77155. * Creates a new instance of the component for the given scene
  77156. * @param scene Defines the scene to register the component in
  77157. */
  77158. function GamepadSystemSceneComponent(scene) {
  77159. /**
  77160. * The component name helpfull to identify the component in the list of scene components.
  77161. */
  77162. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  77163. this.scene = scene;
  77164. }
  77165. /**
  77166. * Registers the component in a given scene
  77167. */
  77168. GamepadSystemSceneComponent.prototype.register = function () {
  77169. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  77170. };
  77171. /**
  77172. * Rebuilds the elements related to this component in case of
  77173. * context lost for instance.
  77174. */
  77175. GamepadSystemSceneComponent.prototype.rebuild = function () {
  77176. // Nothing to do for gamepads
  77177. };
  77178. /**
  77179. * Disposes the component and the associated ressources
  77180. */
  77181. GamepadSystemSceneComponent.prototype.dispose = function () {
  77182. var gamepadManager = this.scene._gamepadManager;
  77183. if (gamepadManager) {
  77184. gamepadManager.dispose();
  77185. this.scene._gamepadManager = null;
  77186. }
  77187. };
  77188. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  77189. var gamepadManager = this.scene._gamepadManager;
  77190. if (gamepadManager && gamepadManager._isMonitoring) {
  77191. gamepadManager._checkGamepadsStatus();
  77192. }
  77193. };
  77194. return GamepadSystemSceneComponent;
  77195. }());
  77196. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  77197. })(BABYLON || (BABYLON = {}));
  77198. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  77199. var BABYLON;
  77200. (function (BABYLON) {
  77201. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  77202. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  77203. });
  77204. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  77205. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  77206. });
  77207. var FollowCamera = /** @class */ (function (_super) {
  77208. __extends(FollowCamera, _super);
  77209. function FollowCamera(name, position, scene, lockedTarget) {
  77210. if (lockedTarget === void 0) { lockedTarget = null; }
  77211. var _this = _super.call(this, name, position, scene) || this;
  77212. _this.radius = 12;
  77213. _this.rotationOffset = 0;
  77214. _this.heightOffset = 4;
  77215. _this.cameraAcceleration = 0.05;
  77216. _this.maxCameraSpeed = 20;
  77217. _this.lockedTarget = lockedTarget;
  77218. return _this;
  77219. }
  77220. FollowCamera.prototype.getRadians = function (degrees) {
  77221. return degrees * Math.PI / 180;
  77222. };
  77223. FollowCamera.prototype.follow = function (cameraTarget) {
  77224. if (!cameraTarget)
  77225. return;
  77226. var yRotation;
  77227. if (cameraTarget.rotationQuaternion) {
  77228. var rotMatrix = new BABYLON.Matrix();
  77229. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  77230. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  77231. }
  77232. else {
  77233. yRotation = cameraTarget.rotation.y;
  77234. }
  77235. var radians = this.getRadians(this.rotationOffset) + yRotation;
  77236. var targetPosition = cameraTarget.getAbsolutePosition();
  77237. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  77238. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  77239. var dx = targetX - this.position.x;
  77240. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  77241. var dz = (targetZ) - this.position.z;
  77242. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  77243. var vy = dy * this.cameraAcceleration;
  77244. var vz = dz * this.cameraAcceleration * 2;
  77245. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  77246. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  77247. }
  77248. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  77249. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  77250. }
  77251. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  77252. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  77253. }
  77254. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  77255. this.setTarget(targetPosition);
  77256. };
  77257. /** @hidden */
  77258. FollowCamera.prototype._checkInputs = function () {
  77259. _super.prototype._checkInputs.call(this);
  77260. if (this.lockedTarget) {
  77261. this.follow(this.lockedTarget);
  77262. }
  77263. };
  77264. FollowCamera.prototype.getClassName = function () {
  77265. return "FollowCamera";
  77266. };
  77267. __decorate([
  77268. BABYLON.serialize()
  77269. ], FollowCamera.prototype, "radius", void 0);
  77270. __decorate([
  77271. BABYLON.serialize()
  77272. ], FollowCamera.prototype, "rotationOffset", void 0);
  77273. __decorate([
  77274. BABYLON.serialize()
  77275. ], FollowCamera.prototype, "heightOffset", void 0);
  77276. __decorate([
  77277. BABYLON.serialize()
  77278. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  77279. __decorate([
  77280. BABYLON.serialize()
  77281. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  77282. __decorate([
  77283. BABYLON.serializeAsMeshReference("lockedTargetId")
  77284. ], FollowCamera.prototype, "lockedTarget", void 0);
  77285. return FollowCamera;
  77286. }(BABYLON.TargetCamera));
  77287. BABYLON.FollowCamera = FollowCamera;
  77288. var ArcFollowCamera = /** @class */ (function (_super) {
  77289. __extends(ArcFollowCamera, _super);
  77290. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  77291. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  77292. _this.alpha = alpha;
  77293. _this.beta = beta;
  77294. _this.radius = radius;
  77295. _this.target = target;
  77296. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  77297. _this.follow();
  77298. return _this;
  77299. }
  77300. ArcFollowCamera.prototype.follow = function () {
  77301. if (!this.target) {
  77302. return;
  77303. }
  77304. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  77305. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  77306. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  77307. var targetPosition = this.target.getAbsolutePosition();
  77308. this.position = targetPosition.add(this._cartesianCoordinates);
  77309. this.setTarget(targetPosition);
  77310. };
  77311. /** @hidden */
  77312. ArcFollowCamera.prototype._checkInputs = function () {
  77313. _super.prototype._checkInputs.call(this);
  77314. this.follow();
  77315. };
  77316. ArcFollowCamera.prototype.getClassName = function () {
  77317. return "ArcFollowCamera";
  77318. };
  77319. return ArcFollowCamera;
  77320. }(BABYLON.TargetCamera));
  77321. BABYLON.ArcFollowCamera = ArcFollowCamera;
  77322. })(BABYLON || (BABYLON = {}));
  77323. //# sourceMappingURL=babylon.followCamera.js.map
  77324. var BABYLON;
  77325. (function (BABYLON) {
  77326. // We're mainly based on the logic defined into the FreeCamera code
  77327. var UniversalCamera = /** @class */ (function (_super) {
  77328. __extends(UniversalCamera, _super);
  77329. //-- end properties for backward compatibility for inputs
  77330. function UniversalCamera(name, position, scene) {
  77331. var _this = _super.call(this, name, position, scene) || this;
  77332. _this.inputs.addGamepad();
  77333. return _this;
  77334. }
  77335. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  77336. //-- Begin properties for backward compatibility for inputs
  77337. get: function () {
  77338. var gamepad = this.inputs.attached["gamepad"];
  77339. if (gamepad)
  77340. return gamepad.gamepadAngularSensibility;
  77341. return 0;
  77342. },
  77343. set: function (value) {
  77344. var gamepad = this.inputs.attached["gamepad"];
  77345. if (gamepad)
  77346. gamepad.gamepadAngularSensibility = value;
  77347. },
  77348. enumerable: true,
  77349. configurable: true
  77350. });
  77351. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  77352. get: function () {
  77353. var gamepad = this.inputs.attached["gamepad"];
  77354. if (gamepad)
  77355. return gamepad.gamepadMoveSensibility;
  77356. return 0;
  77357. },
  77358. set: function (value) {
  77359. var gamepad = this.inputs.attached["gamepad"];
  77360. if (gamepad)
  77361. gamepad.gamepadMoveSensibility = value;
  77362. },
  77363. enumerable: true,
  77364. configurable: true
  77365. });
  77366. UniversalCamera.prototype.getClassName = function () {
  77367. return "UniversalCamera";
  77368. };
  77369. return UniversalCamera;
  77370. }(BABYLON.TouchCamera));
  77371. BABYLON.UniversalCamera = UniversalCamera;
  77372. })(BABYLON || (BABYLON = {}));
  77373. //# sourceMappingURL=babylon.universalCamera.js.map
  77374. var BABYLON;
  77375. (function (BABYLON) {
  77376. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  77377. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  77378. });
  77379. // We're mainly based on the logic defined into the FreeCamera code
  77380. var GamepadCamera = /** @class */ (function (_super) {
  77381. __extends(GamepadCamera, _super);
  77382. //-- end properties for backward compatibility for inputs
  77383. function GamepadCamera(name, position, scene) {
  77384. return _super.call(this, name, position, scene) || this;
  77385. }
  77386. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  77387. //-- Begin properties for backward compatibility for inputs
  77388. get: function () {
  77389. var gamepad = this.inputs.attached["gamepad"];
  77390. if (gamepad)
  77391. return gamepad.gamepadAngularSensibility;
  77392. return 0;
  77393. },
  77394. set: function (value) {
  77395. var gamepad = this.inputs.attached["gamepad"];
  77396. if (gamepad)
  77397. gamepad.gamepadAngularSensibility = value;
  77398. },
  77399. enumerable: true,
  77400. configurable: true
  77401. });
  77402. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  77403. get: function () {
  77404. var gamepad = this.inputs.attached["gamepad"];
  77405. if (gamepad)
  77406. return gamepad.gamepadMoveSensibility;
  77407. return 0;
  77408. },
  77409. set: function (value) {
  77410. var gamepad = this.inputs.attached["gamepad"];
  77411. if (gamepad)
  77412. gamepad.gamepadMoveSensibility = value;
  77413. },
  77414. enumerable: true,
  77415. configurable: true
  77416. });
  77417. GamepadCamera.prototype.getClassName = function () {
  77418. return "GamepadCamera";
  77419. };
  77420. return GamepadCamera;
  77421. }(BABYLON.UniversalCamera));
  77422. BABYLON.GamepadCamera = GamepadCamera;
  77423. })(BABYLON || (BABYLON = {}));
  77424. //# sourceMappingURL=babylon.gamepadCamera.js.map
  77425. var BABYLON;
  77426. (function (BABYLON) {
  77427. var PostProcessRenderPipelineManager = /** @class */ (function () {
  77428. function PostProcessRenderPipelineManager() {
  77429. this._renderPipelines = {};
  77430. }
  77431. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  77432. this._renderPipelines[renderPipeline._name] = renderPipeline;
  77433. };
  77434. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  77435. if (unique === void 0) { unique = false; }
  77436. var renderPipeline = this._renderPipelines[renderPipelineName];
  77437. if (!renderPipeline) {
  77438. return;
  77439. }
  77440. renderPipeline._attachCameras(cameras, unique);
  77441. };
  77442. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  77443. var renderPipeline = this._renderPipelines[renderPipelineName];
  77444. if (!renderPipeline) {
  77445. return;
  77446. }
  77447. renderPipeline._detachCameras(cameras);
  77448. };
  77449. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  77450. var renderPipeline = this._renderPipelines[renderPipelineName];
  77451. if (!renderPipeline) {
  77452. return;
  77453. }
  77454. renderPipeline._enableEffect(renderEffectName, cameras);
  77455. };
  77456. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  77457. var renderPipeline = this._renderPipelines[renderPipelineName];
  77458. if (!renderPipeline) {
  77459. return;
  77460. }
  77461. renderPipeline._disableEffect(renderEffectName, cameras);
  77462. };
  77463. PostProcessRenderPipelineManager.prototype.update = function () {
  77464. for (var renderPipelineName in this._renderPipelines) {
  77465. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77466. var pipeline = this._renderPipelines[renderPipelineName];
  77467. if (!pipeline.isSupported) {
  77468. pipeline.dispose();
  77469. delete this._renderPipelines[renderPipelineName];
  77470. }
  77471. else {
  77472. pipeline._update();
  77473. }
  77474. }
  77475. }
  77476. };
  77477. /** @hidden */
  77478. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  77479. for (var renderPipelineName in this._renderPipelines) {
  77480. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77481. var pipeline = this._renderPipelines[renderPipelineName];
  77482. pipeline._rebuild();
  77483. }
  77484. }
  77485. };
  77486. PostProcessRenderPipelineManager.prototype.dispose = function () {
  77487. for (var renderPipelineName in this._renderPipelines) {
  77488. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77489. var pipeline = this._renderPipelines[renderPipelineName];
  77490. pipeline.dispose();
  77491. }
  77492. }
  77493. };
  77494. return PostProcessRenderPipelineManager;
  77495. }());
  77496. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  77497. })(BABYLON || (BABYLON = {}));
  77498. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  77499. var BABYLON;
  77500. (function (BABYLON) {
  77501. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  77502. get: function () {
  77503. if (!this._postProcessRenderPipelineManager) {
  77504. // Register the G Buffer component to the scene.
  77505. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  77506. if (!component) {
  77507. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  77508. this._addComponent(component);
  77509. }
  77510. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  77511. }
  77512. return this._postProcessRenderPipelineManager;
  77513. },
  77514. enumerable: true,
  77515. configurable: true
  77516. });
  77517. /**
  77518. * Defines the Render Pipeline scene component responsible to rendering pipelines
  77519. */
  77520. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  77521. /**
  77522. * Creates a new instance of the component for the given scene
  77523. * @param scene Defines the scene to register the component in
  77524. */
  77525. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  77526. /**
  77527. * The component name helpfull to identify the component in the list of scene components.
  77528. */
  77529. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  77530. this.scene = scene;
  77531. }
  77532. /**
  77533. * Registers the component in a given scene
  77534. */
  77535. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  77536. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  77537. };
  77538. /**
  77539. * Rebuilds the elements related to this component in case of
  77540. * context lost for instance.
  77541. */
  77542. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  77543. if (this.scene._postProcessRenderPipelineManager) {
  77544. this.scene._postProcessRenderPipelineManager._rebuild();
  77545. }
  77546. };
  77547. /**
  77548. * Disposes the component and the associated ressources
  77549. */
  77550. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  77551. if (this.scene._postProcessRenderPipelineManager) {
  77552. this.scene._postProcessRenderPipelineManager.dispose();
  77553. }
  77554. };
  77555. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77556. if (this.scene._postProcessRenderPipelineManager) {
  77557. this.scene._postProcessRenderPipelineManager.update();
  77558. }
  77559. };
  77560. return PostProcessRenderPipelineManagerSceneComponent;
  77561. }());
  77562. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  77563. })(BABYLON || (BABYLON = {}));
  77564. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  77565. var BABYLON;
  77566. (function (BABYLON) {
  77567. /**
  77568. * This represents a set of one or more post processes in Babylon.
  77569. * A post process can be used to apply a shader to a texture after it is rendered.
  77570. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  77571. */
  77572. var PostProcessRenderEffect = /** @class */ (function () {
  77573. /**
  77574. * Instantiates a post process render effect.
  77575. * A post process can be used to apply a shader to a texture after it is rendered.
  77576. * @param engine The engine the effect is tied to
  77577. * @param name The name of the effect
  77578. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  77579. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  77580. */
  77581. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  77582. this._name = name;
  77583. this._singleInstance = singleInstance || true;
  77584. this._getPostProcesses = getPostProcesses;
  77585. this._cameras = {};
  77586. this._indicesForCamera = {};
  77587. this._postProcesses = {};
  77588. }
  77589. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  77590. /**
  77591. * Checks if all the post processes in the effect are supported.
  77592. */
  77593. get: function () {
  77594. for (var index in this._postProcesses) {
  77595. if (this._postProcesses.hasOwnProperty(index)) {
  77596. var pps = this._postProcesses[index];
  77597. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  77598. if (!pps[ppIndex].isSupported) {
  77599. return false;
  77600. }
  77601. }
  77602. }
  77603. }
  77604. return true;
  77605. },
  77606. enumerable: true,
  77607. configurable: true
  77608. });
  77609. /**
  77610. * Updates the current state of the effect
  77611. * @hidden
  77612. */
  77613. PostProcessRenderEffect.prototype._update = function () {
  77614. };
  77615. /**
  77616. * Attaches the effect on cameras
  77617. * @param cameras The camera to attach to.
  77618. * @hidden
  77619. */
  77620. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  77621. var _this = this;
  77622. var cameraKey;
  77623. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77624. if (!cams) {
  77625. return;
  77626. }
  77627. for (var i = 0; i < cams.length; i++) {
  77628. var camera = cams[i];
  77629. var cameraName = camera.name;
  77630. if (this._singleInstance) {
  77631. cameraKey = 0;
  77632. }
  77633. else {
  77634. cameraKey = cameraName;
  77635. }
  77636. if (!this._postProcesses[cameraKey]) {
  77637. var postProcess = this._getPostProcesses();
  77638. if (postProcess) {
  77639. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  77640. }
  77641. }
  77642. if (!this._indicesForCamera[cameraName]) {
  77643. this._indicesForCamera[cameraName] = [];
  77644. }
  77645. this._postProcesses[cameraKey].forEach(function (postProcess) {
  77646. var index = camera.attachPostProcess(postProcess);
  77647. _this._indicesForCamera[cameraName].push(index);
  77648. });
  77649. if (!this._cameras[cameraName]) {
  77650. this._cameras[cameraName] = camera;
  77651. }
  77652. }
  77653. };
  77654. /**
  77655. * Detatches the effect on cameras
  77656. * @param cameras The camera to detatch from.
  77657. * @hidden
  77658. */
  77659. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  77660. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77661. if (!cams) {
  77662. return;
  77663. }
  77664. for (var i = 0; i < cams.length; i++) {
  77665. var camera = cams[i];
  77666. var cameraName = camera.name;
  77667. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77668. camera.detachPostProcess(postProcess);
  77669. });
  77670. if (this._cameras[cameraName]) {
  77671. //this._indicesForCamera.splice(index, 1);
  77672. this._cameras[cameraName] = null;
  77673. }
  77674. }
  77675. };
  77676. /**
  77677. * Enables the effect on given cameras
  77678. * @param cameras The camera to enable.
  77679. * @hidden
  77680. */
  77681. PostProcessRenderEffect.prototype._enable = function (cameras) {
  77682. var _this = this;
  77683. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77684. if (!cams) {
  77685. return;
  77686. }
  77687. for (var i = 0; i < cams.length; i++) {
  77688. var camera = cams[i];
  77689. var cameraName = camera.name;
  77690. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  77691. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  77692. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77693. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  77694. });
  77695. }
  77696. }
  77697. }
  77698. };
  77699. /**
  77700. * Disables the effect on the given cameras
  77701. * @param cameras The camera to disable.
  77702. * @hidden
  77703. */
  77704. PostProcessRenderEffect.prototype._disable = function (cameras) {
  77705. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77706. if (!cams) {
  77707. return;
  77708. }
  77709. for (var i = 0; i < cams.length; i++) {
  77710. var camera = cams[i];
  77711. var cameraName = camera.name;
  77712. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77713. camera.detachPostProcess(postProcess);
  77714. });
  77715. }
  77716. };
  77717. /**
  77718. * Gets a list of the post processes contained in the effect.
  77719. * @param camera The camera to get the post processes on.
  77720. * @returns The list of the post processes in the effect.
  77721. */
  77722. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  77723. if (this._singleInstance) {
  77724. return this._postProcesses[0];
  77725. }
  77726. else {
  77727. if (!camera) {
  77728. return null;
  77729. }
  77730. return this._postProcesses[camera.name];
  77731. }
  77732. };
  77733. return PostProcessRenderEffect;
  77734. }());
  77735. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  77736. })(BABYLON || (BABYLON = {}));
  77737. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  77738. var BABYLON;
  77739. (function (BABYLON) {
  77740. var PostProcessRenderPipeline = /** @class */ (function () {
  77741. function PostProcessRenderPipeline(engine, name) {
  77742. this.engine = engine;
  77743. this._name = name;
  77744. this._renderEffects = {};
  77745. this._renderEffectsForIsolatedPass = new Array();
  77746. this._cameras = [];
  77747. }
  77748. PostProcessRenderPipeline.prototype.getClassName = function () {
  77749. return "PostProcessRenderPipeline";
  77750. };
  77751. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  77752. get: function () {
  77753. for (var renderEffectName in this._renderEffects) {
  77754. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77755. if (!this._renderEffects[renderEffectName].isSupported) {
  77756. return false;
  77757. }
  77758. }
  77759. }
  77760. return true;
  77761. },
  77762. enumerable: true,
  77763. configurable: true
  77764. });
  77765. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  77766. this._renderEffects[renderEffect._name] = renderEffect;
  77767. };
  77768. // private
  77769. /** @hidden */
  77770. PostProcessRenderPipeline.prototype._rebuild = function () {
  77771. };
  77772. /** @hidden */
  77773. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  77774. var renderEffects = this._renderEffects[renderEffectName];
  77775. if (!renderEffects) {
  77776. return;
  77777. }
  77778. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  77779. };
  77780. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  77781. var renderEffects = this._renderEffects[renderEffectName];
  77782. if (!renderEffects) {
  77783. return;
  77784. }
  77785. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  77786. };
  77787. /** @hidden */
  77788. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  77789. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77790. if (!cams) {
  77791. return;
  77792. }
  77793. var indicesToDelete = [];
  77794. var i;
  77795. for (i = 0; i < cams.length; i++) {
  77796. var camera = cams[i];
  77797. var cameraName = camera.name;
  77798. if (this._cameras.indexOf(camera) === -1) {
  77799. this._cameras[cameraName] = camera;
  77800. }
  77801. else if (unique) {
  77802. indicesToDelete.push(i);
  77803. }
  77804. }
  77805. for (i = 0; i < indicesToDelete.length; i++) {
  77806. cameras.splice(indicesToDelete[i], 1);
  77807. }
  77808. for (var renderEffectName in this._renderEffects) {
  77809. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77810. this._renderEffects[renderEffectName]._attachCameras(cams);
  77811. }
  77812. }
  77813. };
  77814. /** @hidden */
  77815. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  77816. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77817. if (!cams) {
  77818. return;
  77819. }
  77820. for (var renderEffectName in this._renderEffects) {
  77821. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77822. this._renderEffects[renderEffectName]._detachCameras(cams);
  77823. }
  77824. }
  77825. for (var i = 0; i < cams.length; i++) {
  77826. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  77827. }
  77828. };
  77829. /** @hidden */
  77830. PostProcessRenderPipeline.prototype._update = function () {
  77831. for (var renderEffectName in this._renderEffects) {
  77832. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77833. this._renderEffects[renderEffectName]._update();
  77834. }
  77835. }
  77836. for (var i = 0; i < this._cameras.length; i++) {
  77837. var cameraName = this._cameras[i].name;
  77838. if (this._renderEffectsForIsolatedPass[cameraName]) {
  77839. this._renderEffectsForIsolatedPass[cameraName]._update();
  77840. }
  77841. }
  77842. };
  77843. /** @hidden */
  77844. PostProcessRenderPipeline.prototype._reset = function () {
  77845. this._renderEffects = {};
  77846. this._renderEffectsForIsolatedPass = new Array();
  77847. };
  77848. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  77849. // 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)
  77850. var effectKeys = Object.keys(this._renderEffects);
  77851. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  77852. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  77853. if (postProcesses) {
  77854. postProcesses[0].samples = sampleCount;
  77855. return true;
  77856. }
  77857. }
  77858. return false;
  77859. };
  77860. PostProcessRenderPipeline.prototype.dispose = function () {
  77861. // Must be implemented by children
  77862. };
  77863. __decorate([
  77864. BABYLON.serialize()
  77865. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  77866. return PostProcessRenderPipeline;
  77867. }());
  77868. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  77869. })(BABYLON || (BABYLON = {}));
  77870. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  77871. var BABYLON;
  77872. (function (BABYLON) {
  77873. /**
  77874. * This represents a depth renderer in Babylon.
  77875. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  77876. */
  77877. var DepthRenderer = /** @class */ (function () {
  77878. /**
  77879. * Instantiates a depth renderer
  77880. * @param scene The scene the renderer belongs to
  77881. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  77882. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  77883. */
  77884. function DepthRenderer(scene, type, camera) {
  77885. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  77886. if (camera === void 0) { camera = null; }
  77887. var _this = this;
  77888. /**
  77889. * Specifiess that the depth renderer will only be used within
  77890. * the camera it is created for.
  77891. * This can help forcing its rendering during the camera processing.
  77892. */
  77893. this.useOnlyInActiveCamera = false;
  77894. this._scene = scene;
  77895. // Register the G Buffer component to the scene.
  77896. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  77897. if (!component) {
  77898. component = new BABYLON.DepthRendererSceneComponent(scene);
  77899. scene._addComponent(component);
  77900. }
  77901. this._camera = camera;
  77902. var engine = scene.getEngine();
  77903. // Render target
  77904. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  77905. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77906. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77907. this._depthMap.refreshRate = 1;
  77908. this._depthMap.renderParticles = false;
  77909. this._depthMap.renderList = null;
  77910. // Camera to get depth map from to support multiple concurrent cameras
  77911. this._depthMap.activeCamera = this._camera;
  77912. this._depthMap.ignoreCameraViewport = true;
  77913. this._depthMap.useCameraPostProcesses = false;
  77914. // set default depth value to 1.0 (far away)
  77915. this._depthMap.onClearObservable.add(function (engine) {
  77916. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  77917. });
  77918. // Custom render function
  77919. var renderSubMesh = function (subMesh) {
  77920. var mesh = subMesh.getRenderingMesh();
  77921. var scene = _this._scene;
  77922. var engine = scene.getEngine();
  77923. var material = subMesh.getMaterial();
  77924. if (!material) {
  77925. return;
  77926. }
  77927. // Culling and reverse (right handed system)
  77928. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77929. // Managing instances
  77930. var batch = mesh._getInstancesRenderList(subMesh._id);
  77931. if (batch.mustReturn) {
  77932. return;
  77933. }
  77934. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77935. var camera = _this._camera || scene.activeCamera;
  77936. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  77937. engine.enableEffect(_this._effect);
  77938. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77939. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77940. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  77941. // Alpha test
  77942. if (material && material.needAlphaTesting()) {
  77943. var alphaTexture = material.getAlphaTestTexture();
  77944. if (alphaTexture) {
  77945. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77946. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77947. }
  77948. }
  77949. // Bones
  77950. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77951. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77952. }
  77953. // Draw
  77954. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77955. }
  77956. };
  77957. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77958. var index;
  77959. if (depthOnlySubMeshes.length) {
  77960. engine.setColorWrite(false);
  77961. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77962. renderSubMesh(depthOnlySubMeshes.data[index]);
  77963. }
  77964. engine.setColorWrite(true);
  77965. }
  77966. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77967. renderSubMesh(opaqueSubMeshes.data[index]);
  77968. }
  77969. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77970. renderSubMesh(alphaTestSubMeshes.data[index]);
  77971. }
  77972. };
  77973. }
  77974. /**
  77975. * Creates the depth rendering effect and checks if the effect is ready.
  77976. * @param subMesh The submesh to be used to render the depth map of
  77977. * @param useInstances If multiple world instances should be used
  77978. * @returns if the depth renderer is ready to render the depth map
  77979. */
  77980. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  77981. var material = subMesh.getMaterial();
  77982. if (material.disableDepthWrite) {
  77983. return false;
  77984. }
  77985. var defines = [];
  77986. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77987. var mesh = subMesh.getMesh();
  77988. // Alpha test
  77989. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  77990. defines.push("#define ALPHATEST");
  77991. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77992. attribs.push(BABYLON.VertexBuffer.UVKind);
  77993. defines.push("#define UV1");
  77994. }
  77995. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77996. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77997. defines.push("#define UV2");
  77998. }
  77999. }
  78000. // Bones
  78001. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78002. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78003. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78004. if (mesh.numBoneInfluencers > 4) {
  78005. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78006. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78007. }
  78008. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78009. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78010. }
  78011. else {
  78012. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78013. }
  78014. // Instances
  78015. if (useInstances) {
  78016. defines.push("#define INSTANCES");
  78017. attribs.push("world0");
  78018. attribs.push("world1");
  78019. attribs.push("world2");
  78020. attribs.push("world3");
  78021. }
  78022. // Get correct effect
  78023. var join = defines.join("\n");
  78024. if (this._cachedDefines !== join) {
  78025. this._cachedDefines = join;
  78026. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  78027. }
  78028. return this._effect.isReady();
  78029. };
  78030. /**
  78031. * Gets the texture which the depth map will be written to.
  78032. * @returns The depth map texture
  78033. */
  78034. DepthRenderer.prototype.getDepthMap = function () {
  78035. return this._depthMap;
  78036. };
  78037. /**
  78038. * Disposes of the depth renderer.
  78039. */
  78040. DepthRenderer.prototype.dispose = function () {
  78041. this._depthMap.dispose();
  78042. };
  78043. return DepthRenderer;
  78044. }());
  78045. BABYLON.DepthRenderer = DepthRenderer;
  78046. })(BABYLON || (BABYLON = {}));
  78047. //# sourceMappingURL=babylon.depthRenderer.js.map
  78048. var BABYLON;
  78049. (function (BABYLON) {
  78050. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  78051. camera = camera || this.activeCamera;
  78052. if (!camera) {
  78053. throw "No camera available to enable depth renderer";
  78054. }
  78055. if (!this._depthRenderer) {
  78056. this._depthRenderer = {};
  78057. }
  78058. if (!this._depthRenderer[camera.id]) {
  78059. var textureType = 0;
  78060. if (this.getEngine().getCaps().textureHalfFloatRender) {
  78061. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78062. }
  78063. else if (this.getEngine().getCaps().textureFloatRender) {
  78064. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78065. }
  78066. else {
  78067. throw "Depth renderer does not support int texture type";
  78068. }
  78069. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  78070. }
  78071. return this._depthRenderer[camera.id];
  78072. };
  78073. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  78074. camera = camera || this.activeCamera;
  78075. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  78076. return;
  78077. }
  78078. this._depthRenderer[camera.id].dispose();
  78079. delete this._depthRenderer[camera.id];
  78080. };
  78081. /**
  78082. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  78083. * in several rendering techniques.
  78084. */
  78085. var DepthRendererSceneComponent = /** @class */ (function () {
  78086. /**
  78087. * Creates a new instance of the component for the given scene
  78088. * @param scene Defines the scene to register the component in
  78089. */
  78090. function DepthRendererSceneComponent(scene) {
  78091. /**
  78092. * The component name helpfull to identify the component in the list of scene components.
  78093. */
  78094. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  78095. this.scene = scene;
  78096. }
  78097. /**
  78098. * Registers the component in a given scene
  78099. */
  78100. DepthRendererSceneComponent.prototype.register = function () {
  78101. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  78102. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  78103. };
  78104. /**
  78105. * Rebuilds the elements related to this component in case of
  78106. * context lost for instance.
  78107. */
  78108. DepthRendererSceneComponent.prototype.rebuild = function () {
  78109. // Nothing to do for this component
  78110. };
  78111. /**
  78112. * Disposes the component and the associated ressources
  78113. */
  78114. DepthRendererSceneComponent.prototype.dispose = function () {
  78115. for (var key in this.scene._depthRenderer) {
  78116. this.scene._depthRenderer[key].dispose();
  78117. }
  78118. };
  78119. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  78120. if (this.scene._depthRenderer) {
  78121. for (var key in this.scene._depthRenderer) {
  78122. var depthRenderer = this.scene._depthRenderer[key];
  78123. if (!depthRenderer.useOnlyInActiveCamera) {
  78124. renderTargets.push(depthRenderer.getDepthMap());
  78125. }
  78126. }
  78127. }
  78128. };
  78129. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  78130. if (this.scene._depthRenderer) {
  78131. for (var key in this.scene._depthRenderer) {
  78132. var depthRenderer = this.scene._depthRenderer[key];
  78133. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  78134. renderTargets.push(depthRenderer.getDepthMap());
  78135. }
  78136. }
  78137. }
  78138. };
  78139. return DepthRendererSceneComponent;
  78140. }());
  78141. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  78142. })(BABYLON || (BABYLON = {}));
  78143. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  78144. var BABYLON;
  78145. (function (BABYLON) {
  78146. /**
  78147. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  78148. */
  78149. var GeometryBufferRenderer = /** @class */ (function () {
  78150. /**
  78151. * Creates a new G Buffer for the scene
  78152. * @param scene The scene the buffer belongs to
  78153. * @param ratio How big is the buffer related to the main canvas.
  78154. */
  78155. function GeometryBufferRenderer(scene, ratio) {
  78156. if (ratio === void 0) { ratio = 1; }
  78157. this._enablePosition = false;
  78158. this._scene = scene;
  78159. this._ratio = ratio;
  78160. // Register the G Buffer component to the scene.
  78161. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  78162. if (!component) {
  78163. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  78164. scene._addComponent(component);
  78165. }
  78166. // Render target
  78167. this._createRenderTargets();
  78168. }
  78169. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  78170. /**
  78171. * Set the render list (meshes to be rendered) used in the G buffer.
  78172. */
  78173. set: function (meshes) {
  78174. this._multiRenderTarget.renderList = meshes;
  78175. },
  78176. enumerable: true,
  78177. configurable: true
  78178. });
  78179. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  78180. /**
  78181. * Gets wether or not G buffer are supported by the running hardware.
  78182. * This requires draw buffer supports
  78183. */
  78184. get: function () {
  78185. return this._multiRenderTarget.isSupported;
  78186. },
  78187. enumerable: true,
  78188. configurable: true
  78189. });
  78190. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  78191. /**
  78192. * Gets wether or not position are enabled for the G buffer.
  78193. */
  78194. get: function () {
  78195. return this._enablePosition;
  78196. },
  78197. /**
  78198. * Sets wether or not position are enabled for the G buffer.
  78199. */
  78200. set: function (enable) {
  78201. this._enablePosition = enable;
  78202. this.dispose();
  78203. this._createRenderTargets();
  78204. },
  78205. enumerable: true,
  78206. configurable: true
  78207. });
  78208. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  78209. /**
  78210. * Gets the scene associated with the buffer.
  78211. */
  78212. get: function () {
  78213. return this._scene;
  78214. },
  78215. enumerable: true,
  78216. configurable: true
  78217. });
  78218. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  78219. /**
  78220. * Gets the ratio used by the buffer during its creation.
  78221. * How big is the buffer related to the main canvas.
  78222. */
  78223. get: function () {
  78224. return this._ratio;
  78225. },
  78226. enumerable: true,
  78227. configurable: true
  78228. });
  78229. /**
  78230. * Checks wether everything is ready to render a submesh to the G buffer.
  78231. * @param subMesh the submesh to check readiness for
  78232. * @param useInstances is the mesh drawn using instance or not
  78233. * @returns true if ready otherwise false
  78234. */
  78235. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  78236. var material = subMesh.getMaterial();
  78237. if (material && material.disableDepthWrite) {
  78238. return false;
  78239. }
  78240. var defines = [];
  78241. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78242. var mesh = subMesh.getMesh();
  78243. // Alpha test
  78244. if (material && material.needAlphaTesting()) {
  78245. defines.push("#define ALPHATEST");
  78246. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78247. attribs.push(BABYLON.VertexBuffer.UVKind);
  78248. defines.push("#define UV1");
  78249. }
  78250. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78251. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78252. defines.push("#define UV2");
  78253. }
  78254. }
  78255. // Buffers
  78256. if (this._enablePosition) {
  78257. defines.push("#define POSITION");
  78258. }
  78259. // Bones
  78260. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78261. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78262. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78263. if (mesh.numBoneInfluencers > 4) {
  78264. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78265. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78266. }
  78267. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78268. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78269. }
  78270. else {
  78271. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78272. }
  78273. // Instances
  78274. if (useInstances) {
  78275. defines.push("#define INSTANCES");
  78276. attribs.push("world0");
  78277. attribs.push("world1");
  78278. attribs.push("world2");
  78279. attribs.push("world3");
  78280. }
  78281. // Get correct effect
  78282. var join = defines.join("\n");
  78283. if (this._cachedDefines !== join) {
  78284. this._cachedDefines = join;
  78285. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  78286. }
  78287. return this._effect.isReady();
  78288. };
  78289. /**
  78290. * Gets the current underlying G Buffer.
  78291. * @returns the buffer
  78292. */
  78293. GeometryBufferRenderer.prototype.getGBuffer = function () {
  78294. return this._multiRenderTarget;
  78295. };
  78296. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  78297. /**
  78298. * Gets the number of samples used to render the buffer (anti aliasing).
  78299. */
  78300. get: function () {
  78301. return this._multiRenderTarget.samples;
  78302. },
  78303. /**
  78304. * Sets the number of samples used to render the buffer (anti aliasing).
  78305. */
  78306. set: function (value) {
  78307. this._multiRenderTarget.samples = value;
  78308. },
  78309. enumerable: true,
  78310. configurable: true
  78311. });
  78312. /**
  78313. * Disposes the renderer and frees up associated resources.
  78314. */
  78315. GeometryBufferRenderer.prototype.dispose = function () {
  78316. this.getGBuffer().dispose();
  78317. };
  78318. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  78319. var _this = this;
  78320. var engine = this._scene.getEngine();
  78321. var count = this._enablePosition ? 3 : 2;
  78322. 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 });
  78323. if (!this.isSupported) {
  78324. return;
  78325. }
  78326. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78327. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78328. this._multiRenderTarget.refreshRate = 1;
  78329. this._multiRenderTarget.renderParticles = false;
  78330. this._multiRenderTarget.renderList = null;
  78331. // set default depth value to 1.0 (far away)
  78332. this._multiRenderTarget.onClearObservable.add(function (engine) {
  78333. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  78334. });
  78335. // Custom render function
  78336. var renderSubMesh = function (subMesh) {
  78337. var mesh = subMesh.getRenderingMesh();
  78338. var scene = _this._scene;
  78339. var engine = scene.getEngine();
  78340. var material = subMesh.getMaterial();
  78341. if (!material) {
  78342. return;
  78343. }
  78344. // Culling
  78345. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  78346. // Managing instances
  78347. var batch = mesh._getInstancesRenderList(subMesh._id);
  78348. if (batch.mustReturn) {
  78349. return;
  78350. }
  78351. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78352. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  78353. engine.enableEffect(_this._effect);
  78354. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  78355. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78356. _this._effect.setMatrix("view", scene.getViewMatrix());
  78357. // Alpha test
  78358. if (material && material.needAlphaTesting()) {
  78359. var alphaTexture = material.getAlphaTestTexture();
  78360. if (alphaTexture) {
  78361. _this._effect.setTexture("diffuseSampler", alphaTexture);
  78362. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78363. }
  78364. }
  78365. // Bones
  78366. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78367. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78368. }
  78369. // Draw
  78370. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  78371. }
  78372. };
  78373. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78374. var index;
  78375. if (depthOnlySubMeshes.length) {
  78376. engine.setColorWrite(false);
  78377. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78378. renderSubMesh(depthOnlySubMeshes.data[index]);
  78379. }
  78380. engine.setColorWrite(true);
  78381. }
  78382. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78383. renderSubMesh(opaqueSubMeshes.data[index]);
  78384. }
  78385. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78386. renderSubMesh(alphaTestSubMeshes.data[index]);
  78387. }
  78388. };
  78389. };
  78390. return GeometryBufferRenderer;
  78391. }());
  78392. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  78393. })(BABYLON || (BABYLON = {}));
  78394. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  78395. var BABYLON;
  78396. (function (BABYLON) {
  78397. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  78398. get: function () {
  78399. this._geometryBufferRenderer;
  78400. },
  78401. set: function (value) {
  78402. if (value && value.isSupported) {
  78403. this._geometryBufferRenderer = value;
  78404. }
  78405. ;
  78406. },
  78407. enumerable: true,
  78408. configurable: true
  78409. });
  78410. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  78411. if (ratio === void 0) { ratio = 1; }
  78412. if (this._geometryBufferRenderer) {
  78413. return this._geometryBufferRenderer;
  78414. }
  78415. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  78416. if (!this._geometryBufferRenderer.isSupported) {
  78417. this._geometryBufferRenderer = null;
  78418. }
  78419. return this._geometryBufferRenderer;
  78420. };
  78421. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  78422. if (!this._geometryBufferRenderer) {
  78423. return;
  78424. }
  78425. this._geometryBufferRenderer.dispose();
  78426. this._geometryBufferRenderer = null;
  78427. };
  78428. /**
  78429. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  78430. * in several rendering techniques.
  78431. */
  78432. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  78433. /**
  78434. * Creates a new instance of the component for the given scene
  78435. * @param scene Defines the scene to register the component in
  78436. */
  78437. function GeometryBufferRendererSceneComponent(scene) {
  78438. /**
  78439. * The component name helpful to identify the component in the list of scene components.
  78440. */
  78441. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  78442. this.scene = scene;
  78443. }
  78444. /**
  78445. * Registers the component in a given scene
  78446. */
  78447. GeometryBufferRendererSceneComponent.prototype.register = function () {
  78448. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  78449. };
  78450. /**
  78451. * Rebuilds the elements related to this component in case of
  78452. * context lost for instance.
  78453. */
  78454. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  78455. // Nothing to do for this component
  78456. };
  78457. /**
  78458. * Disposes the component and the associated ressources
  78459. */
  78460. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  78461. // Nothing to do for this component
  78462. };
  78463. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  78464. if (this.scene._geometryBufferRenderer) {
  78465. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  78466. }
  78467. };
  78468. return GeometryBufferRendererSceneComponent;
  78469. }());
  78470. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  78471. })(BABYLON || (BABYLON = {}));
  78472. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  78473. var BABYLON;
  78474. (function (BABYLON) {
  78475. var SSAORenderingPipeline = /** @class */ (function (_super) {
  78476. __extends(SSAORenderingPipeline, _super);
  78477. /**
  78478. * @constructor
  78479. * @param {string} name - The rendering pipeline name
  78480. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78481. * @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 }
  78482. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78483. */
  78484. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  78485. var _this = _super.call(this, scene.getEngine(), name) || this;
  78486. // Members
  78487. /**
  78488. * The PassPostProcess id in the pipeline that contains the original scene color
  78489. */
  78490. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  78491. /**
  78492. * The SSAO PostProcess id in the pipeline
  78493. */
  78494. _this.SSAORenderEffect = "SSAORenderEffect";
  78495. /**
  78496. * The horizontal blur PostProcess id in the pipeline
  78497. */
  78498. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  78499. /**
  78500. * The vertical blur PostProcess id in the pipeline
  78501. */
  78502. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  78503. /**
  78504. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  78505. */
  78506. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  78507. /**
  78508. * The output strength of the SSAO post-process. Default value is 1.0.
  78509. */
  78510. _this.totalStrength = 1.0;
  78511. /**
  78512. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  78513. */
  78514. _this.radius = 0.0001;
  78515. /**
  78516. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  78517. * Must not be equal to fallOff and superior to fallOff.
  78518. * Default value is 0.975
  78519. */
  78520. _this.area = 0.0075;
  78521. /**
  78522. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  78523. * Must not be equal to area and inferior to area.
  78524. * Default value is 0.0
  78525. */
  78526. _this.fallOff = 0.000001;
  78527. /**
  78528. * The base color of the SSAO post-process
  78529. * The final result is "base + ssao" between [0, 1]
  78530. */
  78531. _this.base = 0.5;
  78532. _this._firstUpdate = true;
  78533. _this._scene = scene;
  78534. // Set up assets
  78535. _this._createRandomTexture();
  78536. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  78537. var ssaoRatio = ratio.ssaoRatio || ratio;
  78538. var combineRatio = ratio.combineRatio || ratio;
  78539. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  78540. _this._createSSAOPostProcess(ssaoRatio);
  78541. _this._createBlurPostProcess(ssaoRatio);
  78542. _this._createSSAOCombinePostProcess(combineRatio);
  78543. // Set up pipeline
  78544. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  78545. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  78546. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  78547. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  78548. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  78549. // Finish
  78550. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78551. if (cameras)
  78552. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  78553. return _this;
  78554. }
  78555. // Public Methods
  78556. /**
  78557. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  78558. */
  78559. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  78560. if (disableDepthRender === void 0) { disableDepthRender = false; }
  78561. for (var i = 0; i < this._scene.cameras.length; i++) {
  78562. var camera = this._scene.cameras[i];
  78563. this._originalColorPostProcess.dispose(camera);
  78564. this._ssaoPostProcess.dispose(camera);
  78565. this._blurHPostProcess.dispose(camera);
  78566. this._blurVPostProcess.dispose(camera);
  78567. this._ssaoCombinePostProcess.dispose(camera);
  78568. }
  78569. this._randomTexture.dispose();
  78570. if (disableDepthRender)
  78571. this._scene.disableDepthRenderer();
  78572. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78573. _super.prototype.dispose.call(this);
  78574. };
  78575. // Private Methods
  78576. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  78577. var _this = this;
  78578. var size = 16;
  78579. 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);
  78580. 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);
  78581. this._blurHPostProcess.onActivateObservable.add(function () {
  78582. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  78583. _this._blurHPostProcess.kernel = size * dw;
  78584. });
  78585. this._blurVPostProcess.onActivateObservable.add(function () {
  78586. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  78587. _this._blurVPostProcess.kernel = size * dw;
  78588. });
  78589. };
  78590. /** @hidden */
  78591. SSAORenderingPipeline.prototype._rebuild = function () {
  78592. this._firstUpdate = true;
  78593. _super.prototype._rebuild.call(this);
  78594. };
  78595. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  78596. var _this = this;
  78597. var numSamples = 16;
  78598. var sampleSphere = [
  78599. 0.5381, 0.1856, -0.4319,
  78600. 0.1379, 0.2486, 0.4430,
  78601. 0.3371, 0.5679, -0.0057,
  78602. -0.6999, -0.0451, -0.0019,
  78603. 0.0689, -0.1598, -0.8547,
  78604. 0.0560, 0.0069, -0.1843,
  78605. -0.0146, 0.1402, 0.0762,
  78606. 0.0100, -0.1924, -0.0344,
  78607. -0.3577, -0.5301, -0.4358,
  78608. -0.3169, 0.1063, 0.0158,
  78609. 0.0103, -0.5869, 0.0046,
  78610. -0.0897, -0.4940, 0.3287,
  78611. 0.7119, -0.0154, -0.0918,
  78612. -0.0533, 0.0596, -0.5411,
  78613. 0.0352, -0.0631, 0.5460,
  78614. -0.4776, 0.2847, -0.0271
  78615. ];
  78616. var samplesFactor = 1.0 / numSamples;
  78617. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  78618. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  78619. "area", "fallOff", "base", "range", "viewport"
  78620. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  78621. this._ssaoPostProcess.onApply = function (effect) {
  78622. if (_this._firstUpdate) {
  78623. effect.setArray3("sampleSphere", sampleSphere);
  78624. effect.setFloat("samplesFactor", samplesFactor);
  78625. effect.setFloat("randTextureTiles", 4.0);
  78626. }
  78627. effect.setFloat("totalStrength", _this.totalStrength);
  78628. effect.setFloat("radius", _this.radius);
  78629. effect.setFloat("area", _this.area);
  78630. effect.setFloat("fallOff", _this.fallOff);
  78631. effect.setFloat("base", _this.base);
  78632. effect.setTexture("textureSampler", _this._depthTexture);
  78633. effect.setTexture("randomSampler", _this._randomTexture);
  78634. };
  78635. };
  78636. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  78637. var _this = this;
  78638. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78639. this._ssaoCombinePostProcess.onApply = function (effect) {
  78640. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  78641. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  78642. };
  78643. };
  78644. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  78645. var size = 512;
  78646. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78647. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78648. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78649. var context = this._randomTexture.getContext();
  78650. var rand = function (min, max) {
  78651. return Math.random() * (max - min) + min;
  78652. };
  78653. var randVector = BABYLON.Vector3.Zero();
  78654. for (var x = 0; x < size; x++) {
  78655. for (var y = 0; y < size; y++) {
  78656. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  78657. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  78658. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  78659. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  78660. context.fillRect(x, y, 1, 1);
  78661. }
  78662. }
  78663. this._randomTexture.update(false);
  78664. };
  78665. __decorate([
  78666. BABYLON.serialize()
  78667. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  78668. __decorate([
  78669. BABYLON.serialize()
  78670. ], SSAORenderingPipeline.prototype, "radius", void 0);
  78671. __decorate([
  78672. BABYLON.serialize()
  78673. ], SSAORenderingPipeline.prototype, "area", void 0);
  78674. __decorate([
  78675. BABYLON.serialize()
  78676. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  78677. __decorate([
  78678. BABYLON.serialize()
  78679. ], SSAORenderingPipeline.prototype, "base", void 0);
  78680. return SSAORenderingPipeline;
  78681. }(BABYLON.PostProcessRenderPipeline));
  78682. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  78683. })(BABYLON || (BABYLON = {}));
  78684. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  78685. var BABYLON;
  78686. (function (BABYLON) {
  78687. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  78688. __extends(SSAO2RenderingPipeline, _super);
  78689. /**
  78690. * @constructor
  78691. * @param {string} name - The rendering pipeline name
  78692. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78693. * @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 }
  78694. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78695. */
  78696. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  78697. var _this = _super.call(this, scene.getEngine(), name) || this;
  78698. // Members
  78699. /**
  78700. * The PassPostProcess id in the pipeline that contains the original scene color
  78701. */
  78702. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  78703. /**
  78704. * The SSAO PostProcess id in the pipeline
  78705. */
  78706. _this.SSAORenderEffect = "SSAORenderEffect";
  78707. /**
  78708. * The horizontal blur PostProcess id in the pipeline
  78709. */
  78710. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  78711. /**
  78712. * The vertical blur PostProcess id in the pipeline
  78713. */
  78714. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  78715. /**
  78716. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  78717. */
  78718. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  78719. /**
  78720. * The output strength of the SSAO post-process. Default value is 1.0.
  78721. */
  78722. _this.totalStrength = 1.0;
  78723. /**
  78724. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  78725. */
  78726. _this.maxZ = 100.0;
  78727. /**
  78728. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  78729. */
  78730. _this.minZAspect = 0.2;
  78731. _this._samples = 8;
  78732. _this._textureSamples = 1;
  78733. /**
  78734. * Are we using bilateral blur ?
  78735. */
  78736. _this._expensiveBlur = true;
  78737. /**
  78738. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  78739. */
  78740. _this.radius = 2.0;
  78741. /**
  78742. * The base color of the SSAO post-process
  78743. * The final result is "base + ssao" between [0, 1]
  78744. */
  78745. _this.base = 0;
  78746. _this._firstUpdate = true;
  78747. _this._bits = new Uint32Array(1);
  78748. _this._scene = scene;
  78749. _this._ratio = ratio;
  78750. if (!_this.isSupported) {
  78751. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  78752. return _this;
  78753. }
  78754. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  78755. var blurRatio = _this._ratio.blurRatio || ratio;
  78756. // Set up assets
  78757. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  78758. _this._createRandomTexture();
  78759. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  78760. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  78761. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  78762. _this._originalColorPostProcess.samples = _this.textureSamples;
  78763. _this._createSSAOPostProcess(1.0);
  78764. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  78765. _this._createSSAOCombinePostProcess(blurRatio);
  78766. // Set up pipeline
  78767. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  78768. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  78769. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  78770. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  78771. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  78772. // Finish
  78773. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78774. if (cameras)
  78775. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  78776. return _this;
  78777. }
  78778. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  78779. get: function () {
  78780. return this._samples;
  78781. },
  78782. /**
  78783. * Number of samples used for the SSAO calculations. Default value is 8
  78784. */
  78785. set: function (n) {
  78786. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  78787. this._samples = n;
  78788. this._sampleSphere = this._generateHemisphere();
  78789. this._firstUpdate = true;
  78790. },
  78791. enumerable: true,
  78792. configurable: true
  78793. });
  78794. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  78795. get: function () {
  78796. return this._textureSamples;
  78797. },
  78798. /**
  78799. * Number of samples to use for antialiasing
  78800. */
  78801. set: function (n) {
  78802. this._textureSamples = n;
  78803. this._originalColorPostProcess.samples = n;
  78804. this._blurHPostProcess.samples = n;
  78805. this._blurVPostProcess.samples = n;
  78806. this._ssaoPostProcess.samples = n;
  78807. this._ssaoCombinePostProcess.samples = n;
  78808. },
  78809. enumerable: true,
  78810. configurable: true
  78811. });
  78812. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  78813. get: function () {
  78814. return this._expensiveBlur;
  78815. },
  78816. set: function (b) {
  78817. 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"]);
  78818. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  78819. this._expensiveBlur = b;
  78820. this._firstUpdate = true;
  78821. },
  78822. enumerable: true,
  78823. configurable: true
  78824. });
  78825. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  78826. /**
  78827. * Support test.
  78828. */
  78829. get: function () {
  78830. var engine = BABYLON.Engine.LastCreatedEngine;
  78831. if (!engine) {
  78832. return false;
  78833. }
  78834. return engine.getCaps().drawBuffersExtension;
  78835. },
  78836. enumerable: true,
  78837. configurable: true
  78838. });
  78839. // Public Methods
  78840. /**
  78841. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  78842. */
  78843. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  78844. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  78845. for (var i = 0; i < this._scene.cameras.length; i++) {
  78846. var camera = this._scene.cameras[i];
  78847. this._originalColorPostProcess.dispose(camera);
  78848. this._ssaoPostProcess.dispose(camera);
  78849. this._blurHPostProcess.dispose(camera);
  78850. this._blurVPostProcess.dispose(camera);
  78851. this._ssaoCombinePostProcess.dispose(camera);
  78852. }
  78853. this._randomTexture.dispose();
  78854. if (disableGeometryBufferRenderer)
  78855. this._scene.disableGeometryBufferRenderer();
  78856. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78857. _super.prototype.dispose.call(this);
  78858. };
  78859. // Private Methods
  78860. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  78861. var _this = this;
  78862. this._samplerOffsets = [];
  78863. var expensive = this.expensiveBlur;
  78864. for (var i = -8; i < 8; i++) {
  78865. this._samplerOffsets.push(i * 2 + 0.5);
  78866. }
  78867. 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");
  78868. this._blurHPostProcess.onApply = function (effect) {
  78869. if (!_this._scene.activeCamera) {
  78870. return;
  78871. }
  78872. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  78873. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78874. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78875. effect.setFloat("radius", _this.radius);
  78876. effect.setTexture("depthSampler", _this._depthTexture);
  78877. if (_this._firstUpdate) {
  78878. effect.setArray("samplerOffsets", _this._samplerOffsets);
  78879. }
  78880. };
  78881. 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");
  78882. this._blurVPostProcess.onApply = function (effect) {
  78883. if (!_this._scene.activeCamera) {
  78884. return;
  78885. }
  78886. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  78887. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78888. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78889. effect.setFloat("radius", _this.radius);
  78890. effect.setTexture("depthSampler", _this._depthTexture);
  78891. if (_this._firstUpdate) {
  78892. effect.setArray("samplerOffsets", _this._samplerOffsets);
  78893. _this._firstUpdate = false;
  78894. }
  78895. };
  78896. this._blurHPostProcess.samples = this.textureSamples;
  78897. this._blurVPostProcess.samples = this.textureSamples;
  78898. };
  78899. /** @hidden */
  78900. SSAO2RenderingPipeline.prototype._rebuild = function () {
  78901. this._firstUpdate = true;
  78902. _super.prototype._rebuild.call(this);
  78903. };
  78904. //Van der Corput radical inverse
  78905. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  78906. this._bits[0] = i;
  78907. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  78908. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  78909. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  78910. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  78911. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  78912. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  78913. };
  78914. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  78915. return [i / n, this._radicalInverse_VdC(i)];
  78916. };
  78917. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  78918. var phi = v * 2.0 * Math.PI;
  78919. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  78920. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  78921. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  78922. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  78923. };
  78924. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  78925. var numSamples = this.samples;
  78926. var result = [];
  78927. var vector;
  78928. var i = 0;
  78929. while (i < numSamples) {
  78930. if (numSamples < 16) {
  78931. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  78932. }
  78933. else {
  78934. var rand = this._hammersley(i, numSamples);
  78935. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  78936. }
  78937. result.push(vector.x, vector.y, vector.z);
  78938. i++;
  78939. }
  78940. return result;
  78941. };
  78942. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  78943. var _this = this;
  78944. var numSamples = this.samples;
  78945. this._sampleSphere = this._generateHemisphere();
  78946. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  78947. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  78948. "base", "range", "projection", "near", "far", "texelSize",
  78949. "xViewport", "yViewport", "maxZ", "minZAspect"
  78950. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  78951. this._ssaoPostProcess.onApply = function (effect) {
  78952. if (_this._firstUpdate) {
  78953. effect.setArray3("sampleSphere", _this._sampleSphere);
  78954. effect.setFloat("randTextureTiles", 32.0);
  78955. }
  78956. if (!_this._scene.activeCamera) {
  78957. return;
  78958. }
  78959. effect.setFloat("samplesFactor", 1 / _this.samples);
  78960. effect.setFloat("totalStrength", _this.totalStrength);
  78961. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  78962. effect.setFloat("radius", _this.radius);
  78963. effect.setFloat("maxZ", _this.maxZ);
  78964. effect.setFloat("minZAspect", _this.minZAspect);
  78965. effect.setFloat("base", _this.base);
  78966. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78967. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78968. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  78969. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  78970. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  78971. effect.setTexture("textureSampler", _this._depthTexture);
  78972. effect.setTexture("normalSampler", _this._normalTexture);
  78973. effect.setTexture("randomSampler", _this._randomTexture);
  78974. };
  78975. this._ssaoPostProcess.samples = this.textureSamples;
  78976. };
  78977. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  78978. var _this = this;
  78979. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78980. this._ssaoCombinePostProcess.onApply = function (effect) {
  78981. var viewport = _this._scene.activeCamera.viewport;
  78982. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  78983. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  78984. };
  78985. this._ssaoCombinePostProcess.samples = this.textureSamples;
  78986. };
  78987. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  78988. var size = 128;
  78989. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78990. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78991. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78992. var context = this._randomTexture.getContext();
  78993. var rand = function (min, max) {
  78994. return Math.random() * (max - min) + min;
  78995. };
  78996. var randVector = BABYLON.Vector3.Zero();
  78997. for (var x = 0; x < size; x++) {
  78998. for (var y = 0; y < size; y++) {
  78999. randVector.x = rand(0.0, 1.0);
  79000. randVector.y = rand(0.0, 1.0);
  79001. randVector.z = 0.0;
  79002. randVector.normalize();
  79003. randVector.scaleInPlace(255);
  79004. randVector.x = Math.floor(randVector.x);
  79005. randVector.y = Math.floor(randVector.y);
  79006. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  79007. context.fillRect(x, y, 1, 1);
  79008. }
  79009. }
  79010. this._randomTexture.update(false);
  79011. };
  79012. /**
  79013. * Serialize the rendering pipeline (Used when exporting)
  79014. * @returns the serialized object
  79015. */
  79016. SSAO2RenderingPipeline.prototype.serialize = function () {
  79017. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  79018. serializationObject.customType = "SSAO2RenderingPipeline";
  79019. return serializationObject;
  79020. };
  79021. /**
  79022. * Parse the serialized pipeline
  79023. * @param source Source pipeline.
  79024. * @param scene The scene to load the pipeline to.
  79025. * @param rootUrl The URL of the serialized pipeline.
  79026. * @returns An instantiated pipeline from the serialized object.
  79027. */
  79028. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  79029. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  79030. };
  79031. __decorate([
  79032. BABYLON.serialize()
  79033. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  79034. __decorate([
  79035. BABYLON.serialize()
  79036. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  79037. __decorate([
  79038. BABYLON.serialize()
  79039. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  79040. __decorate([
  79041. BABYLON.serialize("samples")
  79042. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  79043. __decorate([
  79044. BABYLON.serialize("textureSamples")
  79045. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  79046. __decorate([
  79047. BABYLON.serialize()
  79048. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  79049. __decorate([
  79050. BABYLON.serialize("expensiveBlur")
  79051. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  79052. __decorate([
  79053. BABYLON.serialize()
  79054. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  79055. __decorate([
  79056. BABYLON.serialize()
  79057. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  79058. return SSAO2RenderingPipeline;
  79059. }(BABYLON.PostProcessRenderPipeline));
  79060. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  79061. })(BABYLON || (BABYLON = {}));
  79062. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  79063. // BABYLON.JS Chromatic Aberration GLSL Shader
  79064. // Author: Olivier Guyot
  79065. // Separates very slightly R, G and B colors on the edges of the screen
  79066. // Inspired by Francois Tarlier & Martins Upitis
  79067. var BABYLON;
  79068. (function (BABYLON) {
  79069. var LensRenderingPipeline = /** @class */ (function (_super) {
  79070. __extends(LensRenderingPipeline, _super);
  79071. /**
  79072. * @constructor
  79073. *
  79074. * Effect parameters are as follow:
  79075. * {
  79076. * chromatic_aberration: number; // from 0 to x (1 for realism)
  79077. * edge_blur: number; // from 0 to x (1 for realism)
  79078. * distortion: number; // from 0 to x (1 for realism)
  79079. * grain_amount: number; // from 0 to 1
  79080. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  79081. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  79082. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  79083. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  79084. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  79085. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  79086. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  79087. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  79088. * }
  79089. * Note: if an effect parameter is unset, effect is disabled
  79090. *
  79091. * @param {string} name - The rendering pipeline name
  79092. * @param {object} parameters - An object containing all parameters (see above)
  79093. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  79094. * @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)
  79095. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  79096. */
  79097. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  79098. if (ratio === void 0) { ratio = 1.0; }
  79099. var _this = _super.call(this, scene.getEngine(), name) || this;
  79100. // Lens effects can be of the following:
  79101. // - chromatic aberration (slight shift of RGB colors)
  79102. // - blur on the edge of the lens
  79103. // - lens distortion
  79104. // - depth-of-field blur & highlights enhancing
  79105. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  79106. // - grain effect (noise or custom texture)
  79107. // Two additional texture samplers are needed:
  79108. // - depth map (for depth-of-field)
  79109. // - grain texture
  79110. /**
  79111. * The chromatic aberration PostProcess id in the pipeline
  79112. */
  79113. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  79114. /**
  79115. * The highlights enhancing PostProcess id in the pipeline
  79116. */
  79117. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  79118. /**
  79119. * The depth-of-field PostProcess id in the pipeline
  79120. */
  79121. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  79122. _this._scene = scene;
  79123. // Fetch texture samplers
  79124. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  79125. if (parameters.grain_texture) {
  79126. _this._grainTexture = parameters.grain_texture;
  79127. }
  79128. else {
  79129. _this._createGrainTexture();
  79130. }
  79131. // save parameters
  79132. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  79133. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  79134. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  79135. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  79136. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  79137. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  79138. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  79139. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  79140. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  79141. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  79142. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  79143. // Create effects
  79144. _this._createChromaticAberrationPostProcess(ratio);
  79145. _this._createHighlightsPostProcess(ratio);
  79146. _this._createDepthOfFieldPostProcess(ratio / 4);
  79147. // Set up pipeline
  79148. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  79149. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  79150. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  79151. if (_this._highlightsGain === -1) {
  79152. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  79153. }
  79154. // Finish
  79155. scene.postProcessRenderPipelineManager.addPipeline(_this);
  79156. if (cameras) {
  79157. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  79158. }
  79159. return _this;
  79160. }
  79161. // public methods (self explanatory)
  79162. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  79163. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  79164. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  79165. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  79166. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  79167. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  79168. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  79169. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  79170. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  79171. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  79172. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  79173. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  79174. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  79175. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  79176. };
  79177. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  79178. this._highlightsPostProcess.updateEffect();
  79179. };
  79180. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  79181. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  79182. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  79183. this._highlightsGain = amount;
  79184. };
  79185. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  79186. if (this._highlightsGain === -1) {
  79187. this._highlightsGain = 1.0;
  79188. }
  79189. this._highlightsThreshold = amount;
  79190. };
  79191. LensRenderingPipeline.prototype.disableHighlights = function () {
  79192. this._highlightsGain = -1;
  79193. };
  79194. /**
  79195. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  79196. */
  79197. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  79198. if (disableDepthRender === void 0) { disableDepthRender = false; }
  79199. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  79200. this._chromaticAberrationPostProcess = null;
  79201. this._highlightsPostProcess = null;
  79202. this._depthOfFieldPostProcess = null;
  79203. this._grainTexture.dispose();
  79204. if (disableDepthRender)
  79205. this._scene.disableDepthRenderer();
  79206. };
  79207. // colors shifting and distortion
  79208. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  79209. var _this = this;
  79210. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  79211. [], // samplers
  79212. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  79213. this._chromaticAberrationPostProcess.onApply = function (effect) {
  79214. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  79215. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  79216. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  79217. effect.setFloat('radialIntensity', 1);
  79218. effect.setFloat2('direction', 17, 17);
  79219. effect.setFloat2('centerPosition', 0.5, 0.5);
  79220. };
  79221. };
  79222. // highlights enhancing
  79223. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  79224. var _this = this;
  79225. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  79226. [], // samplers
  79227. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  79228. this._highlightsPostProcess.onApply = function (effect) {
  79229. effect.setFloat('gain', _this._highlightsGain);
  79230. effect.setFloat('threshold', _this._highlightsThreshold);
  79231. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  79232. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  79233. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  79234. };
  79235. };
  79236. // colors shifting and distortion
  79237. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  79238. var _this = this;
  79239. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  79240. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  79241. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  79242. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  79243. this._depthOfFieldPostProcess.onApply = function (effect) {
  79244. effect.setTexture("depthSampler", _this._depthTexture);
  79245. effect.setTexture("grainSampler", _this._grainTexture);
  79246. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  79247. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  79248. effect.setFloat('grain_amount', _this._grainAmount);
  79249. effect.setBool('blur_noise', _this._blurNoise);
  79250. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  79251. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  79252. effect.setFloat('distortion', _this._distortion);
  79253. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  79254. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  79255. effect.setFloat('aperture', _this._dofAperture);
  79256. effect.setFloat('darken', _this._dofDarken);
  79257. effect.setFloat('edge_blur', _this._edgeBlur);
  79258. effect.setBool('highlights', (_this._highlightsGain !== -1));
  79259. if (_this._scene.activeCamera) {
  79260. effect.setFloat('near', _this._scene.activeCamera.minZ);
  79261. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  79262. }
  79263. };
  79264. };
  79265. // creates a black and white random noise texture, 512x512
  79266. LensRenderingPipeline.prototype._createGrainTexture = function () {
  79267. var size = 512;
  79268. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  79269. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  79270. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  79271. var context = this._grainTexture.getContext();
  79272. var rand = function (min, max) {
  79273. return Math.random() * (max - min) + min;
  79274. };
  79275. var value;
  79276. for (var x = 0; x < size; x++) {
  79277. for (var y = 0; y < size; y++) {
  79278. value = Math.floor(rand(0.42, 0.58) * 255);
  79279. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  79280. context.fillRect(x, y, 1, 1);
  79281. }
  79282. }
  79283. this._grainTexture.update(false);
  79284. };
  79285. return LensRenderingPipeline;
  79286. }(BABYLON.PostProcessRenderPipeline));
  79287. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  79288. })(BABYLON || (BABYLON = {}));
  79289. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  79290. var BABYLON;
  79291. (function (BABYLON) {
  79292. var StandardRenderingPipeline = /** @class */ (function (_super) {
  79293. __extends(StandardRenderingPipeline, _super);
  79294. /**
  79295. * @constructor
  79296. * @param {string} name - The rendering pipeline name
  79297. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  79298. * @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)
  79299. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  79300. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  79301. */
  79302. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  79303. if (originalPostProcess === void 0) { originalPostProcess = null; }
  79304. var _this = _super.call(this, scene.getEngine(), name) || this;
  79305. /**
  79306. * Post-process used to down scale an image x4
  79307. */
  79308. _this.downSampleX4PostProcess = null;
  79309. /**
  79310. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  79311. */
  79312. _this.brightPassPostProcess = null;
  79313. /**
  79314. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  79315. */
  79316. _this.blurHPostProcesses = [];
  79317. /**
  79318. * Post-process array storing all the vertical blur post-processes used by the pipeline
  79319. */
  79320. _this.blurVPostProcesses = [];
  79321. /**
  79322. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  79323. */
  79324. _this.textureAdderPostProcess = null;
  79325. /**
  79326. * Post-process used to create volumetric lighting effect
  79327. */
  79328. _this.volumetricLightPostProcess = null;
  79329. /**
  79330. * Post-process used to smooth the previous volumetric light post-process on the X axis
  79331. */
  79332. _this.volumetricLightSmoothXPostProcess = null;
  79333. /**
  79334. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  79335. */
  79336. _this.volumetricLightSmoothYPostProcess = null;
  79337. /**
  79338. * Post-process used to merge the volumetric light effect and the real scene color
  79339. */
  79340. _this.volumetricLightMergePostProces = null;
  79341. /**
  79342. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  79343. */
  79344. _this.volumetricLightFinalPostProcess = null;
  79345. /**
  79346. * Base post-process used to calculate the average luminance of the final image for HDR
  79347. */
  79348. _this.luminancePostProcess = null;
  79349. /**
  79350. * Post-processes used to create down sample post-processes in order to get
  79351. * the average luminance of the final image for HDR
  79352. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  79353. */
  79354. _this.luminanceDownSamplePostProcesses = [];
  79355. /**
  79356. * Post-process used to create a HDR effect (light adaptation)
  79357. */
  79358. _this.hdrPostProcess = null;
  79359. /**
  79360. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  79361. */
  79362. _this.textureAdderFinalPostProcess = null;
  79363. /**
  79364. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  79365. */
  79366. _this.lensFlareFinalPostProcess = null;
  79367. /**
  79368. * Post-process used to merge the final HDR post-process and the real scene color
  79369. */
  79370. _this.hdrFinalPostProcess = null;
  79371. /**
  79372. * Post-process used to create a lens flare effect
  79373. */
  79374. _this.lensFlarePostProcess = null;
  79375. /**
  79376. * Post-process that merges the result of the lens flare post-process and the real scene color
  79377. */
  79378. _this.lensFlareComposePostProcess = null;
  79379. /**
  79380. * Post-process used to create a motion blur effect
  79381. */
  79382. _this.motionBlurPostProcess = null;
  79383. /**
  79384. * Post-process used to create a depth of field effect
  79385. */
  79386. _this.depthOfFieldPostProcess = null;
  79387. /**
  79388. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  79389. */
  79390. _this.fxaaPostProcess = null;
  79391. // Values
  79392. /**
  79393. * Represents the brightness threshold in order to configure the illuminated surfaces
  79394. */
  79395. _this.brightThreshold = 1.0;
  79396. /**
  79397. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  79398. */
  79399. _this.blurWidth = 512.0;
  79400. /**
  79401. * Sets if the blur for highlighted surfaces must be only horizontal
  79402. */
  79403. _this.horizontalBlur = false;
  79404. /**
  79405. * Sets the overall exposure used by the pipeline
  79406. */
  79407. _this.exposure = 1.0;
  79408. /**
  79409. * Texture used typically to simulate "dirty" on camera lens
  79410. */
  79411. _this.lensTexture = null;
  79412. /**
  79413. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  79414. */
  79415. _this.volumetricLightCoefficient = 0.2;
  79416. /**
  79417. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  79418. */
  79419. _this.volumetricLightPower = 4.0;
  79420. /**
  79421. * Used the set the blur intensity to smooth the volumetric lights
  79422. */
  79423. _this.volumetricLightBlurScale = 64.0;
  79424. /**
  79425. * Light (spot or directional) used to generate the volumetric lights rays
  79426. * The source light must have a shadow generate so the pipeline can get its
  79427. * depth map
  79428. */
  79429. _this.sourceLight = null;
  79430. /**
  79431. * For eye adaptation, represents the minimum luminance the eye can see
  79432. */
  79433. _this.hdrMinimumLuminance = 1.0;
  79434. /**
  79435. * For eye adaptation, represents the decrease luminance speed
  79436. */
  79437. _this.hdrDecreaseRate = 0.5;
  79438. /**
  79439. * For eye adaptation, represents the increase luminance speed
  79440. */
  79441. _this.hdrIncreaseRate = 0.5;
  79442. /**
  79443. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  79444. */
  79445. _this.lensColorTexture = null;
  79446. /**
  79447. * The overall strengh for the lens flare effect
  79448. */
  79449. _this.lensFlareStrength = 20.0;
  79450. /**
  79451. * Dispersion coefficient for lens flare ghosts
  79452. */
  79453. _this.lensFlareGhostDispersal = 1.4;
  79454. /**
  79455. * Main lens flare halo width
  79456. */
  79457. _this.lensFlareHaloWidth = 0.7;
  79458. /**
  79459. * Based on the lens distortion effect, defines how much the lens flare result
  79460. * is distorted
  79461. */
  79462. _this.lensFlareDistortionStrength = 16.0;
  79463. /**
  79464. * Lens star texture must be used to simulate rays on the flares and is available
  79465. * in the documentation
  79466. */
  79467. _this.lensStarTexture = null;
  79468. /**
  79469. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  79470. * flare effect by taking account of the dirt texture
  79471. */
  79472. _this.lensFlareDirtTexture = null;
  79473. /**
  79474. * Represents the focal length for the depth of field effect
  79475. */
  79476. _this.depthOfFieldDistance = 10.0;
  79477. /**
  79478. * Represents the blur intensity for the blurred part of the depth of field effect
  79479. */
  79480. _this.depthOfFieldBlurWidth = 64.0;
  79481. /**
  79482. * For motion blur, defines how much the image is blurred by the movement
  79483. */
  79484. _this.motionStrength = 1.0;
  79485. /**
  79486. * List of animations for the pipeline (IAnimatable implementation)
  79487. */
  79488. _this.animations = [];
  79489. _this._currentDepthOfFieldSource = null;
  79490. _this._hdrCurrentLuminance = 1.0;
  79491. // Getters and setters
  79492. _this._bloomEnabled = false;
  79493. _this._depthOfFieldEnabled = false;
  79494. _this._vlsEnabled = false;
  79495. _this._lensFlareEnabled = false;
  79496. _this._hdrEnabled = false;
  79497. _this._motionBlurEnabled = false;
  79498. _this._fxaaEnabled = false;
  79499. _this._motionBlurSamples = 64.0;
  79500. _this._volumetricLightStepsCount = 50.0;
  79501. _this._samples = 1;
  79502. _this._cameras = cameras || [];
  79503. // Initialize
  79504. _this._scene = scene;
  79505. _this._basePostProcess = originalPostProcess;
  79506. _this._ratio = ratio;
  79507. // Misc
  79508. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79509. // Finish
  79510. scene.postProcessRenderPipelineManager.addPipeline(_this);
  79511. _this._buildPipeline();
  79512. return _this;
  79513. }
  79514. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  79515. /**
  79516. * Specifies if the bloom pipeline is enabled
  79517. */
  79518. get: function () {
  79519. return this._bloomEnabled;
  79520. },
  79521. set: function (enabled) {
  79522. if (this._bloomEnabled === enabled) {
  79523. return;
  79524. }
  79525. this._bloomEnabled = enabled;
  79526. this._buildPipeline();
  79527. },
  79528. enumerable: true,
  79529. configurable: true
  79530. });
  79531. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  79532. /**
  79533. * Specifies if the depth of field pipeline is enabed
  79534. */
  79535. get: function () {
  79536. return this._depthOfFieldEnabled;
  79537. },
  79538. set: function (enabled) {
  79539. if (this._depthOfFieldEnabled === enabled) {
  79540. return;
  79541. }
  79542. this._depthOfFieldEnabled = enabled;
  79543. this._buildPipeline();
  79544. },
  79545. enumerable: true,
  79546. configurable: true
  79547. });
  79548. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  79549. /**
  79550. * Specifies if the lens flare pipeline is enabed
  79551. */
  79552. get: function () {
  79553. return this._lensFlareEnabled;
  79554. },
  79555. set: function (enabled) {
  79556. if (this._lensFlareEnabled === enabled) {
  79557. return;
  79558. }
  79559. this._lensFlareEnabled = enabled;
  79560. this._buildPipeline();
  79561. },
  79562. enumerable: true,
  79563. configurable: true
  79564. });
  79565. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  79566. /**
  79567. * Specifies if the HDR pipeline is enabled
  79568. */
  79569. get: function () {
  79570. return this._hdrEnabled;
  79571. },
  79572. set: function (enabled) {
  79573. if (this._hdrEnabled === enabled) {
  79574. return;
  79575. }
  79576. this._hdrEnabled = enabled;
  79577. this._buildPipeline();
  79578. },
  79579. enumerable: true,
  79580. configurable: true
  79581. });
  79582. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  79583. /**
  79584. * Specifies if the volumetric lights scattering effect is enabled
  79585. */
  79586. get: function () {
  79587. return this._vlsEnabled;
  79588. },
  79589. set: function (enabled) {
  79590. if (this._vlsEnabled === enabled) {
  79591. return;
  79592. }
  79593. if (enabled) {
  79594. var geometry = this._scene.enableGeometryBufferRenderer();
  79595. if (!geometry) {
  79596. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  79597. return;
  79598. }
  79599. }
  79600. this._vlsEnabled = enabled;
  79601. this._buildPipeline();
  79602. },
  79603. enumerable: true,
  79604. configurable: true
  79605. });
  79606. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  79607. /**
  79608. * Specifies if the motion blur effect is enabled
  79609. */
  79610. get: function () {
  79611. return this._motionBlurEnabled;
  79612. },
  79613. set: function (enabled) {
  79614. if (this._motionBlurEnabled === enabled) {
  79615. return;
  79616. }
  79617. this._motionBlurEnabled = enabled;
  79618. this._buildPipeline();
  79619. },
  79620. enumerable: true,
  79621. configurable: true
  79622. });
  79623. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  79624. /**
  79625. * Specifies if anti-aliasing is enabled
  79626. */
  79627. get: function () {
  79628. return this._fxaaEnabled;
  79629. },
  79630. set: function (enabled) {
  79631. if (this._fxaaEnabled === enabled) {
  79632. return;
  79633. }
  79634. this._fxaaEnabled = enabled;
  79635. this._buildPipeline();
  79636. },
  79637. enumerable: true,
  79638. configurable: true
  79639. });
  79640. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  79641. /**
  79642. * Specifies the number of steps used to calculate the volumetric lights
  79643. * Typically in interval [50, 200]
  79644. */
  79645. get: function () {
  79646. return this._volumetricLightStepsCount;
  79647. },
  79648. set: function (count) {
  79649. if (this.volumetricLightPostProcess) {
  79650. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  79651. }
  79652. this._volumetricLightStepsCount = count;
  79653. },
  79654. enumerable: true,
  79655. configurable: true
  79656. });
  79657. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  79658. /**
  79659. * Specifies the number of samples used for the motion blur effect
  79660. * Typically in interval [16, 64]
  79661. */
  79662. get: function () {
  79663. return this._motionBlurSamples;
  79664. },
  79665. set: function (samples) {
  79666. if (this.motionBlurPostProcess) {
  79667. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  79668. }
  79669. this._motionBlurSamples = samples;
  79670. },
  79671. enumerable: true,
  79672. configurable: true
  79673. });
  79674. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  79675. /**
  79676. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  79677. */
  79678. get: function () {
  79679. return this._samples;
  79680. },
  79681. set: function (sampleCount) {
  79682. if (this._samples === sampleCount) {
  79683. return;
  79684. }
  79685. this._samples = sampleCount;
  79686. this._buildPipeline();
  79687. },
  79688. enumerable: true,
  79689. configurable: true
  79690. });
  79691. StandardRenderingPipeline.prototype._buildPipeline = function () {
  79692. var _this = this;
  79693. var ratio = this._ratio;
  79694. var scene = this._scene;
  79695. this._disposePostProcesses();
  79696. this._reset();
  79697. // Create pass post-process
  79698. if (!this._basePostProcess) {
  79699. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  79700. this.originalPostProcess.onApply = function (effect) {
  79701. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  79702. };
  79703. }
  79704. else {
  79705. this.originalPostProcess = this._basePostProcess;
  79706. }
  79707. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  79708. this._currentDepthOfFieldSource = this.originalPostProcess;
  79709. if (this._bloomEnabled) {
  79710. // Create down sample X4 post-process
  79711. this._createDownSampleX4PostProcess(scene, ratio / 2);
  79712. // Create bright pass post-process
  79713. this._createBrightPassPostProcess(scene, ratio / 2);
  79714. // Create gaussian blur post-processes (down sampling blurs)
  79715. this._createBlurPostProcesses(scene, ratio / 4, 1);
  79716. // Create texture adder post-process
  79717. this._createTextureAdderPostProcess(scene, ratio);
  79718. // Create depth-of-field source post-process
  79719. 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);
  79720. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  79721. }
  79722. if (this._vlsEnabled) {
  79723. // Create volumetric light
  79724. this._createVolumetricLightPostProcess(scene, ratio);
  79725. // Create volumetric light final post-process
  79726. 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);
  79727. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  79728. }
  79729. if (this._lensFlareEnabled) {
  79730. // Create lens flare post-process
  79731. this._createLensFlarePostProcess(scene, ratio);
  79732. // Create depth-of-field source post-process post lens-flare and disable it now
  79733. 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);
  79734. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  79735. }
  79736. if (this._hdrEnabled) {
  79737. // Create luminance
  79738. this._createLuminancePostProcesses(scene, this._floatTextureType);
  79739. // Create HDR
  79740. this._createHdrPostProcess(scene, ratio);
  79741. // Create depth-of-field source post-process post hdr and disable it now
  79742. 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);
  79743. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  79744. }
  79745. if (this._depthOfFieldEnabled) {
  79746. // Create gaussian blur used by depth-of-field
  79747. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  79748. // Create depth-of-field post-process
  79749. this._createDepthOfFieldPostProcess(scene, ratio);
  79750. }
  79751. if (this._motionBlurEnabled) {
  79752. // Create motion blur post-process
  79753. this._createMotionBlurPostProcess(scene, ratio);
  79754. }
  79755. if (this._fxaaEnabled) {
  79756. // Create fxaa post-process
  79757. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  79758. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  79759. }
  79760. if (this._cameras !== null) {
  79761. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  79762. }
  79763. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  79764. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  79765. }
  79766. };
  79767. // Down Sample X4 Post-Processs
  79768. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  79769. var _this = this;
  79770. var downSampleX4Offsets = new Array(32);
  79771. 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);
  79772. this.downSampleX4PostProcess.onApply = function (effect) {
  79773. var id = 0;
  79774. var width = _this.downSampleX4PostProcess.width;
  79775. var height = _this.downSampleX4PostProcess.height;
  79776. for (var i = -2; i < 2; i++) {
  79777. for (var j = -2; j < 2; j++) {
  79778. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  79779. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  79780. id += 2;
  79781. }
  79782. }
  79783. effect.setArray2("dsOffsets", downSampleX4Offsets);
  79784. };
  79785. // Add to pipeline
  79786. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  79787. };
  79788. // Brightpass Post-Process
  79789. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  79790. var _this = this;
  79791. var brightOffsets = new Array(8);
  79792. 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);
  79793. this.brightPassPostProcess.onApply = function (effect) {
  79794. var sU = (1.0 / _this.brightPassPostProcess.width);
  79795. var sV = (1.0 / _this.brightPassPostProcess.height);
  79796. brightOffsets[0] = -0.5 * sU;
  79797. brightOffsets[1] = 0.5 * sV;
  79798. brightOffsets[2] = 0.5 * sU;
  79799. brightOffsets[3] = 0.5 * sV;
  79800. brightOffsets[4] = -0.5 * sU;
  79801. brightOffsets[5] = -0.5 * sV;
  79802. brightOffsets[6] = 0.5 * sU;
  79803. brightOffsets[7] = -0.5 * sV;
  79804. effect.setArray2("dsOffsets", brightOffsets);
  79805. effect.setFloat("brightThreshold", _this.brightThreshold);
  79806. };
  79807. // Add to pipeline
  79808. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  79809. };
  79810. // Create blur H&V post-processes
  79811. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  79812. var _this = this;
  79813. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  79814. var engine = scene.getEngine();
  79815. 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);
  79816. 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);
  79817. blurX.onActivateObservable.add(function () {
  79818. var dw = blurX.width / engine.getRenderWidth();
  79819. blurX.kernel = _this[blurWidthKey] * dw;
  79820. });
  79821. blurY.onActivateObservable.add(function () {
  79822. var dw = blurY.height / engine.getRenderHeight();
  79823. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  79824. });
  79825. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  79826. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  79827. this.blurHPostProcesses.push(blurX);
  79828. this.blurVPostProcesses.push(blurY);
  79829. };
  79830. // Create texture adder post-process
  79831. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  79832. var _this = this;
  79833. 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);
  79834. this.textureAdderPostProcess.onApply = function (effect) {
  79835. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  79836. effect.setTexture("lensSampler", _this.lensTexture);
  79837. effect.setFloat("exposure", _this.exposure);
  79838. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  79839. };
  79840. // Add to pipeline
  79841. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  79842. };
  79843. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  79844. var _this = this;
  79845. var geometryRenderer = scene.enableGeometryBufferRenderer();
  79846. geometryRenderer.enablePosition = true;
  79847. var geometry = geometryRenderer.getGBuffer();
  79848. // Base post-process
  79849. 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));
  79850. var depthValues = BABYLON.Vector2.Zero();
  79851. this.volumetricLightPostProcess.onApply = function (effect) {
  79852. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  79853. var generator = _this.sourceLight.getShadowGenerator();
  79854. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  79855. effect.setTexture("positionSampler", geometry.textures[2]);
  79856. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  79857. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  79858. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  79859. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  79860. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  79861. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  79862. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  79863. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  79864. effect.setVector2("depthValues", depthValues);
  79865. }
  79866. };
  79867. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  79868. // Smooth
  79869. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  79870. // Merge
  79871. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  79872. this.volumetricLightMergePostProces.onApply = function (effect) {
  79873. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  79874. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  79875. };
  79876. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  79877. };
  79878. // Create luminance
  79879. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  79880. var _this = this;
  79881. // Create luminance
  79882. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  79883. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  79884. var offsets = [];
  79885. this.luminancePostProcess.onApply = function (effect) {
  79886. var sU = (1.0 / _this.luminancePostProcess.width);
  79887. var sV = (1.0 / _this.luminancePostProcess.height);
  79888. offsets[0] = -0.5 * sU;
  79889. offsets[1] = 0.5 * sV;
  79890. offsets[2] = 0.5 * sU;
  79891. offsets[3] = 0.5 * sV;
  79892. offsets[4] = -0.5 * sU;
  79893. offsets[5] = -0.5 * sV;
  79894. offsets[6] = 0.5 * sU;
  79895. offsets[7] = -0.5 * sV;
  79896. effect.setArray2("lumOffsets", offsets);
  79897. };
  79898. // Add to pipeline
  79899. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  79900. // Create down sample luminance
  79901. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  79902. var size = Math.pow(3, i);
  79903. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  79904. if (i === 0) {
  79905. defines += "#define FINAL_DOWN_SAMPLER";
  79906. }
  79907. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  79908. this.luminanceDownSamplePostProcesses.push(postProcess);
  79909. }
  79910. // Create callbacks and add effects
  79911. var lastLuminance = this.luminancePostProcess;
  79912. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  79913. var downSampleOffsets = new Array(18);
  79914. pp.onApply = function (effect) {
  79915. if (!lastLuminance) {
  79916. return;
  79917. }
  79918. var id = 0;
  79919. for (var x = -1; x < 2; x++) {
  79920. for (var y = -1; y < 2; y++) {
  79921. downSampleOffsets[id] = x / lastLuminance.width;
  79922. downSampleOffsets[id + 1] = y / lastLuminance.height;
  79923. id += 2;
  79924. }
  79925. }
  79926. effect.setArray2("dsOffsets", downSampleOffsets);
  79927. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  79928. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  79929. lastLuminance = _this.luminancePostProcess;
  79930. }
  79931. else {
  79932. lastLuminance = pp;
  79933. }
  79934. };
  79935. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  79936. pp.onAfterRender = function (effect) {
  79937. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  79938. 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);
  79939. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  79940. };
  79941. }
  79942. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  79943. });
  79944. };
  79945. // Create HDR post-process
  79946. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  79947. var _this = this;
  79948. 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);
  79949. var outputLiminance = 1;
  79950. var time = 0;
  79951. var lastTime = 0;
  79952. this.hdrPostProcess.onApply = function (effect) {
  79953. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  79954. time += scene.getEngine().getDeltaTime();
  79955. if (outputLiminance < 0) {
  79956. outputLiminance = _this._hdrCurrentLuminance;
  79957. }
  79958. else {
  79959. var dt = (lastTime - time) / 1000.0;
  79960. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  79961. outputLiminance += _this.hdrDecreaseRate * dt;
  79962. }
  79963. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  79964. outputLiminance -= _this.hdrIncreaseRate * dt;
  79965. }
  79966. else {
  79967. outputLiminance = _this._hdrCurrentLuminance;
  79968. }
  79969. }
  79970. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  79971. effect.setFloat("averageLuminance", outputLiminance);
  79972. lastTime = time;
  79973. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  79974. };
  79975. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  79976. };
  79977. // Create lens flare post-process
  79978. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  79979. var _this = this;
  79980. 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);
  79981. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  79982. this._createBlurPostProcesses(scene, ratio / 4, 2);
  79983. 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);
  79984. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  79985. var resolution = new BABYLON.Vector2(0, 0);
  79986. // Lens flare
  79987. this.lensFlarePostProcess.onApply = function (effect) {
  79988. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  79989. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  79990. effect.setFloat("strength", _this.lensFlareStrength);
  79991. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  79992. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  79993. // Shift
  79994. resolution.x = _this.lensFlarePostProcess.width;
  79995. resolution.y = _this.lensFlarePostProcess.height;
  79996. effect.setVector2("resolution", resolution);
  79997. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  79998. };
  79999. // Compose
  80000. 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);
  80001. 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);
  80002. this.lensFlareComposePostProcess.onApply = function (effect) {
  80003. if (!_this._scene.activeCamera) {
  80004. return;
  80005. }
  80006. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  80007. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  80008. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  80009. // Lens start rotation matrix
  80010. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  80011. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  80012. 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));
  80013. camRot *= 4.0;
  80014. 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);
  80015. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  80016. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  80017. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  80018. };
  80019. };
  80020. // Create depth-of-field post-process
  80021. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  80022. var _this = this;
  80023. 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);
  80024. this.depthOfFieldPostProcess.onApply = function (effect) {
  80025. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  80026. effect.setTexture("depthSampler", _this._getDepthTexture());
  80027. effect.setFloat("distance", _this.depthOfFieldDistance);
  80028. };
  80029. // Add to pipeline
  80030. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  80031. };
  80032. // Create motion blur post-process
  80033. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  80034. var _this = this;
  80035. 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);
  80036. var motionScale = 0;
  80037. var prevViewProjection = BABYLON.Matrix.Identity();
  80038. var invViewProjection = BABYLON.Matrix.Identity();
  80039. var viewProjection = BABYLON.Matrix.Identity();
  80040. var screenSize = BABYLON.Vector2.Zero();
  80041. this.motionBlurPostProcess.onApply = function (effect) {
  80042. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  80043. viewProjection.invertToRef(invViewProjection);
  80044. effect.setMatrix("inverseViewProjection", invViewProjection);
  80045. effect.setMatrix("prevViewProjection", prevViewProjection);
  80046. prevViewProjection = viewProjection;
  80047. screenSize.x = _this.motionBlurPostProcess.width;
  80048. screenSize.y = _this.motionBlurPostProcess.height;
  80049. effect.setVector2("screenSize", screenSize);
  80050. motionScale = scene.getEngine().getFps() / 60.0;
  80051. effect.setFloat("motionScale", motionScale);
  80052. effect.setFloat("motionStrength", _this.motionStrength);
  80053. effect.setTexture("depthSampler", _this._getDepthTexture());
  80054. };
  80055. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  80056. };
  80057. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  80058. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  80059. var renderer = this._scene.enableGeometryBufferRenderer();
  80060. return renderer.getGBuffer().textures[0];
  80061. }
  80062. return this._scene.enableDepthRenderer().getDepthMap();
  80063. };
  80064. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  80065. for (var i = 0; i < this._cameras.length; i++) {
  80066. var camera = this._cameras[i];
  80067. if (this.originalPostProcess) {
  80068. this.originalPostProcess.dispose(camera);
  80069. }
  80070. if (this.downSampleX4PostProcess) {
  80071. this.downSampleX4PostProcess.dispose(camera);
  80072. }
  80073. if (this.brightPassPostProcess) {
  80074. this.brightPassPostProcess.dispose(camera);
  80075. }
  80076. if (this.textureAdderPostProcess) {
  80077. this.textureAdderPostProcess.dispose(camera);
  80078. }
  80079. if (this.textureAdderFinalPostProcess) {
  80080. this.textureAdderFinalPostProcess.dispose(camera);
  80081. }
  80082. if (this.volumetricLightPostProcess) {
  80083. this.volumetricLightPostProcess.dispose(camera);
  80084. }
  80085. if (this.volumetricLightSmoothXPostProcess) {
  80086. this.volumetricLightSmoothXPostProcess.dispose(camera);
  80087. }
  80088. if (this.volumetricLightSmoothYPostProcess) {
  80089. this.volumetricLightSmoothYPostProcess.dispose(camera);
  80090. }
  80091. if (this.volumetricLightMergePostProces) {
  80092. this.volumetricLightMergePostProces.dispose(camera);
  80093. }
  80094. if (this.volumetricLightFinalPostProcess) {
  80095. this.volumetricLightFinalPostProcess.dispose(camera);
  80096. }
  80097. if (this.lensFlarePostProcess) {
  80098. this.lensFlarePostProcess.dispose(camera);
  80099. }
  80100. if (this.lensFlareComposePostProcess) {
  80101. this.lensFlareComposePostProcess.dispose(camera);
  80102. }
  80103. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  80104. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  80105. }
  80106. if (this.luminancePostProcess) {
  80107. this.luminancePostProcess.dispose(camera);
  80108. }
  80109. if (this.hdrPostProcess) {
  80110. this.hdrPostProcess.dispose(camera);
  80111. }
  80112. if (this.hdrFinalPostProcess) {
  80113. this.hdrFinalPostProcess.dispose(camera);
  80114. }
  80115. if (this.depthOfFieldPostProcess) {
  80116. this.depthOfFieldPostProcess.dispose(camera);
  80117. }
  80118. if (this.motionBlurPostProcess) {
  80119. this.motionBlurPostProcess.dispose(camera);
  80120. }
  80121. if (this.fxaaPostProcess) {
  80122. this.fxaaPostProcess.dispose(camera);
  80123. }
  80124. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  80125. this.blurHPostProcesses[j].dispose(camera);
  80126. }
  80127. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  80128. this.blurVPostProcesses[j].dispose(camera);
  80129. }
  80130. }
  80131. this.originalPostProcess = null;
  80132. this.downSampleX4PostProcess = null;
  80133. this.brightPassPostProcess = null;
  80134. this.textureAdderPostProcess = null;
  80135. this.textureAdderFinalPostProcess = null;
  80136. this.volumetricLightPostProcess = null;
  80137. this.volumetricLightSmoothXPostProcess = null;
  80138. this.volumetricLightSmoothYPostProcess = null;
  80139. this.volumetricLightMergePostProces = null;
  80140. this.volumetricLightFinalPostProcess = null;
  80141. this.lensFlarePostProcess = null;
  80142. this.lensFlareComposePostProcess = null;
  80143. this.luminancePostProcess = null;
  80144. this.hdrPostProcess = null;
  80145. this.hdrFinalPostProcess = null;
  80146. this.depthOfFieldPostProcess = null;
  80147. this.motionBlurPostProcess = null;
  80148. this.fxaaPostProcess = null;
  80149. this.luminanceDownSamplePostProcesses = [];
  80150. this.blurHPostProcesses = [];
  80151. this.blurVPostProcesses = [];
  80152. };
  80153. /**
  80154. * Dispose of the pipeline and stop all post processes
  80155. */
  80156. StandardRenderingPipeline.prototype.dispose = function () {
  80157. this._disposePostProcesses();
  80158. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  80159. _super.prototype.dispose.call(this);
  80160. };
  80161. /**
  80162. * Serialize the rendering pipeline (Used when exporting)
  80163. * @returns the serialized object
  80164. */
  80165. StandardRenderingPipeline.prototype.serialize = function () {
  80166. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  80167. if (this.sourceLight) {
  80168. serializationObject.sourceLightId = this.sourceLight.id;
  80169. }
  80170. serializationObject.customType = "StandardRenderingPipeline";
  80171. return serializationObject;
  80172. };
  80173. /**
  80174. * Parse the serialized pipeline
  80175. * @param source Source pipeline.
  80176. * @param scene The scene to load the pipeline to.
  80177. * @param rootUrl The URL of the serialized pipeline.
  80178. * @returns An instantiated pipeline from the serialized object.
  80179. */
  80180. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  80181. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  80182. if (source.sourceLightId) {
  80183. p.sourceLight = scene.getLightByID(source.sourceLightId);
  80184. }
  80185. return p;
  80186. };
  80187. // Luminance steps
  80188. StandardRenderingPipeline.LuminanceSteps = 6;
  80189. __decorate([
  80190. BABYLON.serialize()
  80191. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  80192. __decorate([
  80193. BABYLON.serialize()
  80194. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  80195. __decorate([
  80196. BABYLON.serialize()
  80197. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  80198. __decorate([
  80199. BABYLON.serialize()
  80200. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  80201. __decorate([
  80202. BABYLON.serializeAsTexture("lensTexture")
  80203. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  80204. __decorate([
  80205. BABYLON.serialize()
  80206. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  80207. __decorate([
  80208. BABYLON.serialize()
  80209. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  80210. __decorate([
  80211. BABYLON.serialize()
  80212. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  80213. __decorate([
  80214. BABYLON.serialize()
  80215. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  80216. __decorate([
  80217. BABYLON.serialize()
  80218. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  80219. __decorate([
  80220. BABYLON.serialize()
  80221. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  80222. __decorate([
  80223. BABYLON.serializeAsTexture("lensColorTexture")
  80224. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  80225. __decorate([
  80226. BABYLON.serialize()
  80227. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  80228. __decorate([
  80229. BABYLON.serialize()
  80230. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  80231. __decorate([
  80232. BABYLON.serialize()
  80233. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  80234. __decorate([
  80235. BABYLON.serialize()
  80236. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  80237. __decorate([
  80238. BABYLON.serializeAsTexture("lensStarTexture")
  80239. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  80240. __decorate([
  80241. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  80242. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  80243. __decorate([
  80244. BABYLON.serialize()
  80245. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  80246. __decorate([
  80247. BABYLON.serialize()
  80248. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  80249. __decorate([
  80250. BABYLON.serialize()
  80251. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  80252. __decorate([
  80253. BABYLON.serialize()
  80254. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  80255. __decorate([
  80256. BABYLON.serialize()
  80257. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  80258. __decorate([
  80259. BABYLON.serialize()
  80260. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  80261. __decorate([
  80262. BABYLON.serialize()
  80263. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  80264. __decorate([
  80265. BABYLON.serialize()
  80266. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  80267. __decorate([
  80268. BABYLON.serialize()
  80269. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  80270. __decorate([
  80271. BABYLON.serialize()
  80272. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  80273. __decorate([
  80274. BABYLON.serialize()
  80275. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  80276. __decorate([
  80277. BABYLON.serialize()
  80278. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  80279. __decorate([
  80280. BABYLON.serialize()
  80281. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  80282. __decorate([
  80283. BABYLON.serialize()
  80284. ], StandardRenderingPipeline.prototype, "samples", null);
  80285. return StandardRenderingPipeline;
  80286. }(BABYLON.PostProcessRenderPipeline));
  80287. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  80288. })(BABYLON || (BABYLON = {}));
  80289. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  80290. var BABYLON;
  80291. (function (BABYLON) {
  80292. var FxaaPostProcess = /** @class */ (function (_super) {
  80293. __extends(FxaaPostProcess, _super);
  80294. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  80295. if (camera === void 0) { camera = null; }
  80296. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80297. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  80298. var defines = _this._getDefines();
  80299. _this.updateEffect(defines);
  80300. _this.onApplyObservable.add(function (effect) {
  80301. var texelSize = _this.texelSize;
  80302. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  80303. });
  80304. return _this;
  80305. }
  80306. FxaaPostProcess.prototype._getDefines = function () {
  80307. var engine = this.getEngine();
  80308. if (!engine) {
  80309. return null;
  80310. }
  80311. var glInfo = engine.getGlInfo();
  80312. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  80313. return "#define MALI 1\n";
  80314. }
  80315. return null;
  80316. };
  80317. return FxaaPostProcess;
  80318. }(BABYLON.PostProcess));
  80319. BABYLON.FxaaPostProcess = FxaaPostProcess;
  80320. })(BABYLON || (BABYLON = {}));
  80321. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  80322. var BABYLON;
  80323. (function (BABYLON) {
  80324. /**
  80325. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  80326. */
  80327. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  80328. __extends(ChromaticAberrationPostProcess, _super);
  80329. /**
  80330. * Creates a new instance ChromaticAberrationPostProcess
  80331. * @param name The name of the effect.
  80332. * @param screenWidth The width of the screen to apply the effect on.
  80333. * @param screenHeight The height of the screen to apply the effect on.
  80334. * @param options The required width/height ratio to downsize to before computing the render pass.
  80335. * @param camera The camera to apply the render pass to.
  80336. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80337. * @param engine The engine which the post process will be applied. (default: current engine)
  80338. * @param reusable If the post process can be reused on the same frame. (default: false)
  80339. * @param textureType Type of textures used when performing the post process. (default: 0)
  80340. * @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)
  80341. */
  80342. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80343. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80344. if (blockCompilation === void 0) { blockCompilation = false; }
  80345. 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;
  80346. /**
  80347. * The amount of seperation of rgb channels (default: 30)
  80348. */
  80349. _this.aberrationAmount = 30;
  80350. /**
  80351. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  80352. */
  80353. _this.radialIntensity = 0;
  80354. /**
  80355. * 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))
  80356. */
  80357. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  80358. /**
  80359. * 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))
  80360. */
  80361. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  80362. _this.onApplyObservable.add(function (effect) {
  80363. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  80364. effect.setFloat('screen_width', screenWidth);
  80365. effect.setFloat('screen_height', screenHeight);
  80366. effect.setFloat('radialIntensity', _this.radialIntensity);
  80367. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  80368. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  80369. });
  80370. return _this;
  80371. }
  80372. return ChromaticAberrationPostProcess;
  80373. }(BABYLON.PostProcess));
  80374. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  80375. })(BABYLON || (BABYLON = {}));
  80376. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  80377. var BABYLON;
  80378. (function (BABYLON) {
  80379. /**
  80380. * The GrainPostProcess adds noise to the image at mid luminance levels
  80381. */
  80382. var GrainPostProcess = /** @class */ (function (_super) {
  80383. __extends(GrainPostProcess, _super);
  80384. /**
  80385. * Creates a new instance of @see GrainPostProcess
  80386. * @param name The name of the effect.
  80387. * @param options The required width/height ratio to downsize to before computing the render pass.
  80388. * @param camera The camera to apply the render pass to.
  80389. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80390. * @param engine The engine which the post process will be applied. (default: current engine)
  80391. * @param reusable If the post process can be reused on the same frame. (default: false)
  80392. * @param textureType Type of textures used when performing the post process. (default: 0)
  80393. * @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)
  80394. */
  80395. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80396. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80397. if (blockCompilation === void 0) { blockCompilation = false; }
  80398. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80399. /**
  80400. * The intensity of the grain added (default: 30)
  80401. */
  80402. _this.intensity = 30;
  80403. /**
  80404. * If the grain should be randomized on every frame
  80405. */
  80406. _this.animated = false;
  80407. _this.onApplyObservable.add(function (effect) {
  80408. effect.setFloat('intensity', _this.intensity);
  80409. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  80410. });
  80411. return _this;
  80412. }
  80413. return GrainPostProcess;
  80414. }(BABYLON.PostProcess));
  80415. BABYLON.GrainPostProcess = GrainPostProcess;
  80416. })(BABYLON || (BABYLON = {}));
  80417. //# sourceMappingURL=babylon.grainPostProcess.js.map
  80418. var BABYLON;
  80419. (function (BABYLON) {
  80420. /**
  80421. * The SharpenPostProcess applies a sharpen kernel to every pixel
  80422. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  80423. */
  80424. var SharpenPostProcess = /** @class */ (function (_super) {
  80425. __extends(SharpenPostProcess, _super);
  80426. /**
  80427. * Creates a new instance ConvolutionPostProcess
  80428. * @param name The name of the effect.
  80429. * @param options The required width/height ratio to downsize to before computing the render pass.
  80430. * @param camera The camera to apply the render pass to.
  80431. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80432. * @param engine The engine which the post process will be applied. (default: current engine)
  80433. * @param reusable If the post process can be reused on the same frame. (default: false)
  80434. * @param textureType Type of textures used when performing the post process. (default: 0)
  80435. * @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)
  80436. */
  80437. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80438. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80439. if (blockCompilation === void 0) { blockCompilation = false; }
  80440. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80441. /**
  80442. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  80443. */
  80444. _this.colorAmount = 1.0;
  80445. /**
  80446. * How much sharpness should be applied (default: 0.3)
  80447. */
  80448. _this.edgeAmount = 0.3;
  80449. _this.onApply = function (effect) {
  80450. effect.setFloat2("screenSize", _this.width, _this.height);
  80451. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  80452. };
  80453. return _this;
  80454. }
  80455. return SharpenPostProcess;
  80456. }(BABYLON.PostProcess));
  80457. BABYLON.SharpenPostProcess = SharpenPostProcess;
  80458. })(BABYLON || (BABYLON = {}));
  80459. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  80460. var BABYLON;
  80461. (function (BABYLON) {
  80462. /**
  80463. * The Blur Post Process which blurs an image based on a kernel and direction.
  80464. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  80465. */
  80466. var BlurPostProcess = /** @class */ (function (_super) {
  80467. __extends(BlurPostProcess, _super);
  80468. /**
  80469. * Creates a new instance BlurPostProcess
  80470. * @param name The name of the effect.
  80471. * @param direction The direction in which to blur the image.
  80472. * @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.
  80473. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  80474. * @param camera The camera to apply the render pass to.
  80475. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80476. * @param engine The engine which the post process will be applied. (default: current engine)
  80477. * @param reusable If the post process can be reused on the same frame. (default: false)
  80478. * @param textureType Type of textures used when performing the post process. (default: 0)
  80479. * @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)
  80480. */
  80481. function BlurPostProcess(name,
  80482. /** The direction in which to blur the image. */
  80483. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  80484. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80485. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80486. if (defines === void 0) { defines = ""; }
  80487. if (blockCompilation === void 0) { blockCompilation = false; }
  80488. 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;
  80489. _this.direction = direction;
  80490. _this.blockCompilation = blockCompilation;
  80491. _this._packedFloat = false;
  80492. _this._staticDefines = "";
  80493. _this._staticDefines = defines;
  80494. _this.onApplyObservable.add(function (effect) {
  80495. if (_this._outputTexture) {
  80496. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  80497. }
  80498. else {
  80499. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  80500. }
  80501. });
  80502. _this.kernel = kernel;
  80503. return _this;
  80504. }
  80505. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  80506. /**
  80507. * Gets the length in pixels of the blur sample region
  80508. */
  80509. get: function () {
  80510. return this._idealKernel;
  80511. },
  80512. /**
  80513. * Sets the length in pixels of the blur sample region
  80514. */
  80515. set: function (v) {
  80516. if (this._idealKernel === v) {
  80517. return;
  80518. }
  80519. v = Math.max(v, 1);
  80520. this._idealKernel = v;
  80521. this._kernel = this._nearestBestKernel(v);
  80522. if (!this.blockCompilation) {
  80523. this._updateParameters();
  80524. }
  80525. },
  80526. enumerable: true,
  80527. configurable: true
  80528. });
  80529. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  80530. /**
  80531. * Gets wether or not the blur is unpacking/repacking floats
  80532. */
  80533. get: function () {
  80534. return this._packedFloat;
  80535. },
  80536. /**
  80537. * Sets wether or not the blur needs to unpack/repack floats
  80538. */
  80539. set: function (v) {
  80540. if (this._packedFloat === v) {
  80541. return;
  80542. }
  80543. this._packedFloat = v;
  80544. if (!this.blockCompilation) {
  80545. this._updateParameters();
  80546. }
  80547. },
  80548. enumerable: true,
  80549. configurable: true
  80550. });
  80551. /**
  80552. * Updates the effect with the current post process compile time values and recompiles the shader.
  80553. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  80554. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  80555. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  80556. * @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
  80557. * @param onCompiled Called when the shader has been compiled.
  80558. * @param onError Called if there is an error when compiling a shader.
  80559. */
  80560. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  80561. if (defines === void 0) { defines = null; }
  80562. if (uniforms === void 0) { uniforms = null; }
  80563. if (samplers === void 0) { samplers = null; }
  80564. this._updateParameters(onCompiled, onError);
  80565. };
  80566. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  80567. // Generate sampling offsets and weights
  80568. var N = this._kernel;
  80569. var centerIndex = (N - 1) / 2;
  80570. // Generate Gaussian sampling weights over kernel
  80571. var offsets = [];
  80572. var weights = [];
  80573. var totalWeight = 0;
  80574. for (var i = 0; i < N; i++) {
  80575. var u = i / (N - 1);
  80576. var w = this._gaussianWeight(u * 2.0 - 1);
  80577. offsets[i] = (i - centerIndex);
  80578. weights[i] = w;
  80579. totalWeight += w;
  80580. }
  80581. // Normalize weights
  80582. for (var i = 0; i < weights.length; i++) {
  80583. weights[i] /= totalWeight;
  80584. }
  80585. // Optimize: combine samples to take advantage of hardware linear sampling
  80586. // Walk from left to center, combining pairs (symmetrically)
  80587. var linearSamplingWeights = [];
  80588. var linearSamplingOffsets = [];
  80589. var linearSamplingMap = [];
  80590. for (var i = 0; i <= centerIndex; i += 2) {
  80591. var j = Math.min(i + 1, Math.floor(centerIndex));
  80592. var singleCenterSample = i === j;
  80593. if (singleCenterSample) {
  80594. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  80595. }
  80596. else {
  80597. var sharedCell = j === centerIndex;
  80598. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  80599. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  80600. if (offsetLinear === 0) {
  80601. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  80602. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  80603. }
  80604. else {
  80605. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  80606. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  80607. }
  80608. }
  80609. }
  80610. for (var i = 0; i < linearSamplingMap.length; i++) {
  80611. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  80612. linearSamplingWeights[i] = linearSamplingMap[i].w;
  80613. }
  80614. // Replace with optimized
  80615. offsets = linearSamplingOffsets;
  80616. weights = linearSamplingWeights;
  80617. // Generate shaders
  80618. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  80619. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  80620. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  80621. var defines = "";
  80622. defines += this._staticDefines;
  80623. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  80624. if (this._staticDefines.indexOf("DOF") != -1) {
  80625. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  80626. varyingCount--;
  80627. }
  80628. for (var i = 0; i < varyingCount; i++) {
  80629. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  80630. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  80631. }
  80632. var depCount = 0;
  80633. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  80634. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  80635. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  80636. depCount++;
  80637. }
  80638. if (this.packedFloat) {
  80639. defines += "#define PACKEDFLOAT 1";
  80640. }
  80641. this.blockCompilation = false;
  80642. _super.prototype.updateEffect.call(this, defines, null, null, {
  80643. varyingCount: varyingCount,
  80644. depCount: depCount
  80645. }, onCompiled, onError);
  80646. };
  80647. /**
  80648. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  80649. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  80650. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  80651. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  80652. * The gaps between physical kernels are compensated for in the weighting of the samples
  80653. * @param idealKernel Ideal blur kernel.
  80654. * @return Nearest best kernel.
  80655. */
  80656. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  80657. var v = Math.round(idealKernel);
  80658. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  80659. var k = _a[_i];
  80660. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  80661. return Math.max(k, 3);
  80662. }
  80663. }
  80664. return Math.max(v, 3);
  80665. };
  80666. /**
  80667. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  80668. * @param x The point on the Gaussian distribution to sample.
  80669. * @return the value of the Gaussian function at x.
  80670. */
  80671. BlurPostProcess.prototype._gaussianWeight = function (x) {
  80672. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  80673. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  80674. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  80675. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  80676. // truncated at around 1.3% of peak strength.
  80677. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  80678. var sigma = (1 / 3);
  80679. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  80680. var exponent = -((x * x) / (2.0 * sigma * sigma));
  80681. var weight = (1.0 / denominator) * Math.exp(exponent);
  80682. return weight;
  80683. };
  80684. /**
  80685. * Generates a string that can be used as a floating point number in GLSL.
  80686. * @param x Value to print.
  80687. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  80688. * @return GLSL float string.
  80689. */
  80690. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  80691. if (decimalFigures === void 0) { decimalFigures = 8; }
  80692. return x.toFixed(decimalFigures).replace(/0+$/, '');
  80693. };
  80694. return BlurPostProcess;
  80695. }(BABYLON.PostProcess));
  80696. BABYLON.BlurPostProcess = BlurPostProcess;
  80697. })(BABYLON || (BABYLON = {}));
  80698. //# sourceMappingURL=babylon.blurPostProcess.js.map
  80699. var BABYLON;
  80700. (function (BABYLON) {
  80701. /**
  80702. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  80703. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  80704. * based on samples that have a large difference in distance than the center pixel.
  80705. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  80706. */
  80707. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  80708. __extends(DepthOfFieldBlurPostProcess, _super);
  80709. /**
  80710. * Creates a new instance CircleOfConfusionPostProcess
  80711. * @param name The name of the effect.
  80712. * @param scene The scene the effect belongs to.
  80713. * @param direction The direction the blur should be applied.
  80714. * @param kernel The size of the kernel used to blur.
  80715. * @param options The required width/height ratio to downsize to before computing the render pass.
  80716. * @param camera The camera to apply the render pass to.
  80717. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  80718. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  80719. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80720. * @param engine The engine which the post process will be applied. (default: current engine)
  80721. * @param reusable If the post process can be reused on the same frame. (default: false)
  80722. * @param textureType Type of textures used when performing the post process. (default: 0)
  80723. * @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)
  80724. */
  80725. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  80726. if (imageToBlur === void 0) { imageToBlur = null; }
  80727. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80728. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80729. if (blockCompilation === void 0) { blockCompilation = false; }
  80730. 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;
  80731. _this.direction = direction;
  80732. _this.onApplyObservable.add(function (effect) {
  80733. if (imageToBlur != null) {
  80734. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  80735. }
  80736. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  80737. if (scene.activeCamera) {
  80738. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  80739. }
  80740. });
  80741. return _this;
  80742. }
  80743. return DepthOfFieldBlurPostProcess;
  80744. }(BABYLON.BlurPostProcess));
  80745. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  80746. })(BABYLON || (BABYLON = {}));
  80747. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  80748. var BABYLON;
  80749. (function (BABYLON) {
  80750. /**
  80751. * Options to be set when merging outputs from the default pipeline.
  80752. */
  80753. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  80754. function DepthOfFieldMergePostProcessOptions() {
  80755. }
  80756. return DepthOfFieldMergePostProcessOptions;
  80757. }());
  80758. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  80759. /**
  80760. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  80761. */
  80762. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  80763. __extends(DepthOfFieldMergePostProcess, _super);
  80764. /**
  80765. * Creates a new instance of DepthOfFieldMergePostProcess
  80766. * @param name The name of the effect.
  80767. * @param originalFromInput Post process which's input will be used for the merge.
  80768. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  80769. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  80770. * @param options The required width/height ratio to downsize to before computing the render pass.
  80771. * @param camera The camera to apply the render pass to.
  80772. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80773. * @param engine The engine which the post process will be applied. (default: current engine)
  80774. * @param reusable If the post process can be reused on the same frame. (default: false)
  80775. * @param textureType Type of textures used when performing the post process. (default: 0)
  80776. * @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)
  80777. */
  80778. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80779. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80780. if (blockCompilation === void 0) { blockCompilation = false; }
  80781. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  80782. _this.blurSteps = blurSteps;
  80783. _this.onApplyObservable.add(function (effect) {
  80784. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  80785. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  80786. blurSteps.forEach(function (step, index) {
  80787. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  80788. });
  80789. });
  80790. if (!blockCompilation) {
  80791. _this.updateEffect();
  80792. }
  80793. return _this;
  80794. }
  80795. /**
  80796. * Updates the effect with the current post process compile time values and recompiles the shader.
  80797. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  80798. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  80799. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  80800. * @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
  80801. * @param onCompiled Called when the shader has been compiled.
  80802. * @param onError Called if there is an error when compiling a shader.
  80803. */
  80804. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  80805. if (defines === void 0) { defines = null; }
  80806. if (uniforms === void 0) { uniforms = null; }
  80807. if (samplers === void 0) { samplers = null; }
  80808. if (!defines) {
  80809. defines = "";
  80810. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  80811. }
  80812. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  80813. };
  80814. return DepthOfFieldMergePostProcess;
  80815. }(BABYLON.PostProcess));
  80816. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  80817. })(BABYLON || (BABYLON = {}));
  80818. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  80819. var BABYLON;
  80820. (function (BABYLON) {
  80821. /**
  80822. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  80823. */
  80824. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  80825. __extends(CircleOfConfusionPostProcess, _super);
  80826. /**
  80827. * Creates a new instance CircleOfConfusionPostProcess
  80828. * @param name The name of the effect.
  80829. * @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.
  80830. * @param options The required width/height ratio to downsize to before computing the render pass.
  80831. * @param camera The camera to apply the render pass to.
  80832. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80833. * @param engine The engine which the post process will be applied. (default: current engine)
  80834. * @param reusable If the post process can be reused on the same frame. (default: false)
  80835. * @param textureType Type of textures used when performing the post process. (default: 0)
  80836. * @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)
  80837. */
  80838. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80839. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80840. if (blockCompilation === void 0) { blockCompilation = false; }
  80841. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80842. /**
  80843. * 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.
  80844. */
  80845. _this.lensSize = 50;
  80846. /**
  80847. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  80848. */
  80849. _this.fStop = 1.4;
  80850. /**
  80851. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  80852. */
  80853. _this.focusDistance = 2000;
  80854. /**
  80855. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  80856. */
  80857. _this.focalLength = 50;
  80858. _this._depthTexture = null;
  80859. _this._depthTexture = depthTexture;
  80860. _this.onApplyObservable.add(function (effect) {
  80861. if (!_this._depthTexture) {
  80862. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  80863. return;
  80864. }
  80865. effect.setTexture("depthSampler", _this._depthTexture);
  80866. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  80867. var aperture = _this.lensSize / _this.fStop;
  80868. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  80869. effect.setFloat('focusDistance', _this.focusDistance);
  80870. effect.setFloat('cocPrecalculation', cocPrecalculation);
  80871. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  80872. });
  80873. return _this;
  80874. }
  80875. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  80876. /**
  80877. * 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.
  80878. */
  80879. set: function (value) {
  80880. this._depthTexture = value;
  80881. },
  80882. enumerable: true,
  80883. configurable: true
  80884. });
  80885. return CircleOfConfusionPostProcess;
  80886. }(BABYLON.PostProcess));
  80887. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  80888. })(BABYLON || (BABYLON = {}));
  80889. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  80890. var BABYLON;
  80891. (function (BABYLON) {
  80892. /**
  80893. * Specifies the level of max blur that should be applied when using the depth of field effect
  80894. */
  80895. var DepthOfFieldEffectBlurLevel;
  80896. (function (DepthOfFieldEffectBlurLevel) {
  80897. /**
  80898. * Subtle blur
  80899. */
  80900. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  80901. /**
  80902. * Medium blur
  80903. */
  80904. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  80905. /**
  80906. * Large blur
  80907. */
  80908. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  80909. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  80910. ;
  80911. /**
  80912. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  80913. */
  80914. var DepthOfFieldEffect = /** @class */ (function (_super) {
  80915. __extends(DepthOfFieldEffect, _super);
  80916. /**
  80917. * Creates a new instance DepthOfFieldEffect
  80918. * @param scene The scene the effect belongs to.
  80919. * @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.
  80920. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  80921. * @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)
  80922. */
  80923. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  80924. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  80925. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  80926. if (blockCompilation === void 0) { blockCompilation = false; }
  80927. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  80928. return _this._effects;
  80929. }, true) || this;
  80930. /**
  80931. * @hidden Internal post processes in depth of field effect
  80932. */
  80933. _this._effects = [];
  80934. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  80935. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80936. // 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)
  80937. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  80938. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  80939. _this._depthOfFieldBlurY = [];
  80940. _this._depthOfFieldBlurX = [];
  80941. var blurCount = 1;
  80942. var kernelSize = 15;
  80943. switch (blurLevel) {
  80944. case DepthOfFieldEffectBlurLevel.High: {
  80945. blurCount = 3;
  80946. kernelSize = 51;
  80947. break;
  80948. }
  80949. case DepthOfFieldEffectBlurLevel.Medium: {
  80950. blurCount = 2;
  80951. kernelSize = 31;
  80952. break;
  80953. }
  80954. default: {
  80955. kernelSize = 15;
  80956. blurCount = 1;
  80957. break;
  80958. }
  80959. }
  80960. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  80961. var ratio = 1.0;
  80962. for (var i = 0; i < blurCount; i++) {
  80963. 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);
  80964. blurY.autoClear = false;
  80965. ratio = 0.75 / Math.pow(2, i);
  80966. 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);
  80967. blurX.autoClear = false;
  80968. _this._depthOfFieldBlurY.push(blurY);
  80969. _this._depthOfFieldBlurX.push(blurX);
  80970. }
  80971. // Set all post processes on the effect.
  80972. _this._effects = [_this._circleOfConfusion];
  80973. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  80974. _this._effects.push(_this._depthOfFieldBlurY[i]);
  80975. _this._effects.push(_this._depthOfFieldBlurX[i]);
  80976. }
  80977. // Merge blurred images with original image based on circleOfConfusion
  80978. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80979. _this._dofMerge.autoClear = false;
  80980. _this._effects.push(_this._dofMerge);
  80981. return _this;
  80982. }
  80983. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  80984. get: function () {
  80985. return this._circleOfConfusion.focalLength;
  80986. },
  80987. /**
  80988. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  80989. */
  80990. set: function (value) {
  80991. this._circleOfConfusion.focalLength = value;
  80992. },
  80993. enumerable: true,
  80994. configurable: true
  80995. });
  80996. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  80997. get: function () {
  80998. return this._circleOfConfusion.fStop;
  80999. },
  81000. /**
  81001. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  81002. */
  81003. set: function (value) {
  81004. this._circleOfConfusion.fStop = value;
  81005. },
  81006. enumerable: true,
  81007. configurable: true
  81008. });
  81009. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  81010. get: function () {
  81011. return this._circleOfConfusion.focusDistance;
  81012. },
  81013. /**
  81014. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  81015. */
  81016. set: function (value) {
  81017. this._circleOfConfusion.focusDistance = value;
  81018. },
  81019. enumerable: true,
  81020. configurable: true
  81021. });
  81022. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  81023. get: function () {
  81024. return this._circleOfConfusion.lensSize;
  81025. },
  81026. /**
  81027. * 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.
  81028. */
  81029. set: function (value) {
  81030. this._circleOfConfusion.lensSize = value;
  81031. },
  81032. enumerable: true,
  81033. configurable: true
  81034. });
  81035. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  81036. /**
  81037. * 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.
  81038. */
  81039. set: function (value) {
  81040. this._circleOfConfusion.depthTexture = value;
  81041. },
  81042. enumerable: true,
  81043. configurable: true
  81044. });
  81045. /**
  81046. * Disposes each of the internal effects for a given camera.
  81047. * @param camera The camera to dispose the effect on.
  81048. */
  81049. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  81050. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81051. this._effects[effectIndex].dispose(camera);
  81052. }
  81053. };
  81054. /**
  81055. * @hidden Internal
  81056. */
  81057. DepthOfFieldEffect.prototype._updateEffects = function () {
  81058. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81059. this._effects[effectIndex].updateEffect();
  81060. }
  81061. };
  81062. /**
  81063. * Internal
  81064. * @returns if all the contained post processes are ready.
  81065. * @hidden
  81066. */
  81067. DepthOfFieldEffect.prototype._isReady = function () {
  81068. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81069. if (!this._effects[effectIndex].isReady()) {
  81070. return false;
  81071. }
  81072. }
  81073. return true;
  81074. };
  81075. return DepthOfFieldEffect;
  81076. }(BABYLON.PostProcessRenderEffect));
  81077. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  81078. })(BABYLON || (BABYLON = {}));
  81079. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  81080. var BABYLON;
  81081. (function (BABYLON) {
  81082. /**
  81083. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  81084. */
  81085. var BloomMergePostProcess = /** @class */ (function (_super) {
  81086. __extends(BloomMergePostProcess, _super);
  81087. /**
  81088. * Creates a new instance of @see BloomMergePostProcess
  81089. * @param name The name of the effect.
  81090. * @param originalFromInput Post process which's input will be used for the merge.
  81091. * @param blurred Blurred highlights post process which's output will be used.
  81092. * @param weight Weight of the bloom to be added to the original input.
  81093. * @param options The required width/height ratio to downsize to before computing the render pass.
  81094. * @param camera The camera to apply the render pass to.
  81095. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  81096. * @param engine The engine which the post process will be applied. (default: current engine)
  81097. * @param reusable If the post process can be reused on the same frame. (default: false)
  81098. * @param textureType Type of textures used when performing the post process. (default: 0)
  81099. * @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)
  81100. */
  81101. function BloomMergePostProcess(name, originalFromInput, blurred,
  81102. /** Weight of the bloom to be added to the original input. */
  81103. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  81104. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81105. if (blockCompilation === void 0) { blockCompilation = false; }
  81106. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  81107. _this.weight = weight;
  81108. _this.onApplyObservable.add(function (effect) {
  81109. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  81110. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  81111. effect.setFloat("bloomWeight", _this.weight);
  81112. });
  81113. if (!blockCompilation) {
  81114. _this.updateEffect();
  81115. }
  81116. return _this;
  81117. }
  81118. return BloomMergePostProcess;
  81119. }(BABYLON.PostProcess));
  81120. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  81121. })(BABYLON || (BABYLON = {}));
  81122. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  81123. var BABYLON;
  81124. (function (BABYLON) {
  81125. /**
  81126. * 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.
  81127. */
  81128. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  81129. __extends(ExtractHighlightsPostProcess, _super);
  81130. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  81131. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81132. if (blockCompilation === void 0) { blockCompilation = false; }
  81133. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  81134. /**
  81135. * The luminance threshold, pixels below this value will be set to black.
  81136. */
  81137. _this.threshold = 0.9;
  81138. /** @hidden */
  81139. _this._exposure = 1;
  81140. /**
  81141. * Post process which has the input texture to be used when performing highlight extraction
  81142. * @hidden
  81143. */
  81144. _this._inputPostProcess = null;
  81145. _this.onApplyObservable.add(function (effect) {
  81146. if (_this._inputPostProcess) {
  81147. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  81148. }
  81149. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  81150. effect.setFloat('exposure', _this._exposure);
  81151. });
  81152. return _this;
  81153. }
  81154. return ExtractHighlightsPostProcess;
  81155. }(BABYLON.PostProcess));
  81156. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  81157. })(BABYLON || (BABYLON = {}));
  81158. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  81159. var BABYLON;
  81160. (function (BABYLON) {
  81161. /**
  81162. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  81163. */
  81164. var BloomEffect = /** @class */ (function (_super) {
  81165. __extends(BloomEffect, _super);
  81166. /**
  81167. * Creates a new instance of @see BloomEffect
  81168. * @param scene The scene the effect belongs to.
  81169. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  81170. * @param bloomKernel The size of the kernel to be used when applying the blur.
  81171. * @param bloomWeight The the strength of bloom.
  81172. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  81173. * @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)
  81174. */
  81175. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  81176. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  81177. if (blockCompilation === void 0) { blockCompilation = false; }
  81178. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  81179. return _this._effects;
  81180. }, true) || this;
  81181. _this.bloomScale = bloomScale;
  81182. /**
  81183. * @hidden Internal
  81184. */
  81185. _this._effects = [];
  81186. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  81187. _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);
  81188. _this._blurX.alwaysForcePOT = true;
  81189. _this._blurX.autoClear = false;
  81190. _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);
  81191. _this._blurY.alwaysForcePOT = true;
  81192. _this._blurY.autoClear = false;
  81193. _this.kernel = bloomKernel;
  81194. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  81195. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  81196. _this._merge.autoClear = false;
  81197. _this._effects.push(_this._merge);
  81198. return _this;
  81199. }
  81200. Object.defineProperty(BloomEffect.prototype, "threshold", {
  81201. /**
  81202. * The luminance threshold to find bright areas of the image to bloom.
  81203. */
  81204. get: function () {
  81205. return this._downscale.threshold;
  81206. },
  81207. set: function (value) {
  81208. this._downscale.threshold = value;
  81209. },
  81210. enumerable: true,
  81211. configurable: true
  81212. });
  81213. Object.defineProperty(BloomEffect.prototype, "weight", {
  81214. /**
  81215. * The strength of the bloom.
  81216. */
  81217. get: function () {
  81218. return this._merge.weight;
  81219. },
  81220. set: function (value) {
  81221. this._merge.weight = value;
  81222. },
  81223. enumerable: true,
  81224. configurable: true
  81225. });
  81226. Object.defineProperty(BloomEffect.prototype, "kernel", {
  81227. /**
  81228. * Specifies the size of the bloom blur kernel, relative to the final output size
  81229. */
  81230. get: function () {
  81231. return this._blurX.kernel / this.bloomScale;
  81232. },
  81233. set: function (value) {
  81234. this._blurX.kernel = value * this.bloomScale;
  81235. this._blurY.kernel = value * this.bloomScale;
  81236. },
  81237. enumerable: true,
  81238. configurable: true
  81239. });
  81240. /**
  81241. * Disposes each of the internal effects for a given camera.
  81242. * @param camera The camera to dispose the effect on.
  81243. */
  81244. BloomEffect.prototype.disposeEffects = function (camera) {
  81245. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81246. this._effects[effectIndex].dispose(camera);
  81247. }
  81248. };
  81249. /**
  81250. * @hidden Internal
  81251. */
  81252. BloomEffect.prototype._updateEffects = function () {
  81253. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81254. this._effects[effectIndex].updateEffect();
  81255. }
  81256. };
  81257. /**
  81258. * Internal
  81259. * @returns if all the contained post processes are ready.
  81260. * @hidden
  81261. */
  81262. BloomEffect.prototype._isReady = function () {
  81263. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  81264. if (!this._effects[effectIndex].isReady()) {
  81265. return false;
  81266. }
  81267. }
  81268. return true;
  81269. };
  81270. return BloomEffect;
  81271. }(BABYLON.PostProcessRenderEffect));
  81272. BABYLON.BloomEffect = BloomEffect;
  81273. })(BABYLON || (BABYLON = {}));
  81274. //# sourceMappingURL=babylon.bloomEffect.js.map
  81275. var BABYLON;
  81276. (function (BABYLON) {
  81277. /**
  81278. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  81279. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  81280. */
  81281. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  81282. __extends(DefaultRenderingPipeline, _super);
  81283. /**
  81284. * @constructor
  81285. * @param {string} name - The rendering pipeline name (default: "")
  81286. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  81287. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  81288. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  81289. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  81290. */
  81291. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  81292. if (name === void 0) { name = ""; }
  81293. if (hdr === void 0) { hdr = true; }
  81294. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  81295. if (automaticBuild === void 0) { automaticBuild = true; }
  81296. var _this = _super.call(this, scene.getEngine(), name) || this;
  81297. _this._camerasToBeAttached = [];
  81298. /**
  81299. * ID of the sharpen post process,
  81300. */
  81301. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  81302. /**
  81303. * ID of the image processing post process;
  81304. */
  81305. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  81306. /**
  81307. * ID of the Fast Approximate Anti-Aliasing post process;
  81308. */
  81309. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  81310. /**
  81311. * ID of the chromatic aberration post process,
  81312. */
  81313. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  81314. /**
  81315. * ID of the grain post process
  81316. */
  81317. _this.GrainPostProcessId = "GrainPostProcessEffect";
  81318. /**
  81319. * Glow post process which adds a glow to emmisive areas of the image
  81320. */
  81321. _this._glowLayer = null;
  81322. /**
  81323. * Animations which can be used to tweak settings over a period of time
  81324. */
  81325. _this.animations = [];
  81326. _this._imageProcessingConfigurationObserver = null;
  81327. // Values
  81328. _this._sharpenEnabled = false;
  81329. _this._bloomEnabled = false;
  81330. _this._depthOfFieldEnabled = false;
  81331. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  81332. _this._fxaaEnabled = false;
  81333. _this._imageProcessingEnabled = true;
  81334. _this._bloomScale = 0.5;
  81335. _this._chromaticAberrationEnabled = false;
  81336. _this._grainEnabled = false;
  81337. _this._buildAllowed = true;
  81338. _this._resizeObserver = null;
  81339. _this._hardwareScaleLevel = 1.0;
  81340. _this._bloomKernel = 64;
  81341. /**
  81342. * Specifies the weight of the bloom in the final rendering
  81343. */
  81344. _this._bloomWeight = 0.15;
  81345. /**
  81346. * Specifies the luma threshold for the area that will be blurred by the bloom
  81347. */
  81348. _this._bloomThreshold = 0.9;
  81349. _this._samples = 1;
  81350. _this._hasCleared = false;
  81351. _this._prevPostProcess = null;
  81352. _this._prevPrevPostProcess = null;
  81353. _this._depthOfFieldSceneObserver = null;
  81354. _this._cameras = cameras || scene.cameras;
  81355. _this._cameras = _this._cameras.slice();
  81356. _this._camerasToBeAttached = _this._cameras.slice();
  81357. _this._buildAllowed = automaticBuild;
  81358. // Initialize
  81359. _this._scene = scene;
  81360. var caps = _this._scene.getEngine().getCaps();
  81361. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  81362. // Misc
  81363. if (_this._hdr) {
  81364. if (caps.textureHalfFloatRender) {
  81365. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81366. }
  81367. else if (caps.textureFloatRender) {
  81368. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81369. }
  81370. }
  81371. else {
  81372. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81373. }
  81374. // Attach
  81375. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81376. var engine = _this._scene.getEngine();
  81377. // Create post processes before hand so they can be modified before enabled.
  81378. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  81379. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81380. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  81381. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  81382. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  81383. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81384. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  81385. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81386. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  81387. _this._resizeObserver = engine.onResizeObservable.add(function () {
  81388. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  81389. _this.bloomKernel = _this.bloomKernel;
  81390. });
  81391. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  81392. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  81393. });
  81394. _this._buildPipeline();
  81395. return _this;
  81396. }
  81397. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  81398. get: function () {
  81399. return this._sharpenEnabled;
  81400. },
  81401. /**
  81402. * Enable or disable the sharpen process from the pipeline
  81403. */
  81404. set: function (enabled) {
  81405. if (this._sharpenEnabled === enabled) {
  81406. return;
  81407. }
  81408. this._sharpenEnabled = enabled;
  81409. this._buildPipeline();
  81410. },
  81411. enumerable: true,
  81412. configurable: true
  81413. });
  81414. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  81415. /**
  81416. * Specifies the size of the bloom blur kernel, relative to the final output size
  81417. */
  81418. get: function () {
  81419. return this._bloomKernel;
  81420. },
  81421. set: function (value) {
  81422. this._bloomKernel = value;
  81423. this.bloom.kernel = value / this._hardwareScaleLevel;
  81424. },
  81425. enumerable: true,
  81426. configurable: true
  81427. });
  81428. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  81429. get: function () {
  81430. return this._bloomWeight;
  81431. },
  81432. /**
  81433. * The strength of the bloom.
  81434. */
  81435. set: function (value) {
  81436. if (this._bloomWeight === value) {
  81437. return;
  81438. }
  81439. this.bloom.weight = value;
  81440. this._bloomWeight = value;
  81441. },
  81442. enumerable: true,
  81443. configurable: true
  81444. });
  81445. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  81446. get: function () {
  81447. return this._bloomThreshold;
  81448. },
  81449. /**
  81450. * The strength of the bloom.
  81451. */
  81452. set: function (value) {
  81453. if (this._bloomThreshold === value) {
  81454. return;
  81455. }
  81456. this.bloom.threshold = value;
  81457. this._bloomThreshold = value;
  81458. },
  81459. enumerable: true,
  81460. configurable: true
  81461. });
  81462. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  81463. get: function () {
  81464. return this._bloomScale;
  81465. },
  81466. /**
  81467. * The scale of the bloom, lower value will provide better performance.
  81468. */
  81469. set: function (value) {
  81470. if (this._bloomScale === value) {
  81471. return;
  81472. }
  81473. this._bloomScale = value;
  81474. // recreate bloom and dispose old as this setting is not dynamic
  81475. this._rebuildBloom();
  81476. this._buildPipeline();
  81477. },
  81478. enumerable: true,
  81479. configurable: true
  81480. });
  81481. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  81482. get: function () {
  81483. return this._bloomEnabled;
  81484. },
  81485. /**
  81486. * Enable or disable the bloom from the pipeline
  81487. */
  81488. set: function (enabled) {
  81489. if (this._bloomEnabled === enabled) {
  81490. return;
  81491. }
  81492. this._bloomEnabled = enabled;
  81493. this._buildPipeline();
  81494. },
  81495. enumerable: true,
  81496. configurable: true
  81497. });
  81498. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  81499. // recreate bloom and dispose old as this setting is not dynamic
  81500. var oldBloom = this.bloom;
  81501. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  81502. this.bloom.threshold = oldBloom.threshold;
  81503. for (var i = 0; i < this._cameras.length; i++) {
  81504. oldBloom.disposeEffects(this._cameras[i]);
  81505. }
  81506. };
  81507. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  81508. /**
  81509. * If the depth of field is enabled.
  81510. */
  81511. get: function () {
  81512. return this._depthOfFieldEnabled;
  81513. },
  81514. set: function (enabled) {
  81515. if (this._depthOfFieldEnabled === enabled) {
  81516. return;
  81517. }
  81518. this._depthOfFieldEnabled = enabled;
  81519. this._buildPipeline();
  81520. },
  81521. enumerable: true,
  81522. configurable: true
  81523. });
  81524. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  81525. /**
  81526. * Blur level of the depth of field effect. (Higher blur will effect performance)
  81527. */
  81528. get: function () {
  81529. return this._depthOfFieldBlurLevel;
  81530. },
  81531. set: function (value) {
  81532. if (this._depthOfFieldBlurLevel === value) {
  81533. return;
  81534. }
  81535. this._depthOfFieldBlurLevel = value;
  81536. // recreate dof and dispose old as this setting is not dynamic
  81537. var oldDof = this.depthOfField;
  81538. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  81539. this.depthOfField.focalLength = oldDof.focalLength;
  81540. this.depthOfField.focusDistance = oldDof.focusDistance;
  81541. this.depthOfField.fStop = oldDof.fStop;
  81542. this.depthOfField.lensSize = oldDof.lensSize;
  81543. for (var i = 0; i < this._cameras.length; i++) {
  81544. oldDof.disposeEffects(this._cameras[i]);
  81545. }
  81546. this._buildPipeline();
  81547. },
  81548. enumerable: true,
  81549. configurable: true
  81550. });
  81551. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  81552. get: function () {
  81553. return this._fxaaEnabled;
  81554. },
  81555. /**
  81556. * If the anti aliasing is enabled.
  81557. */
  81558. set: function (enabled) {
  81559. if (this._fxaaEnabled === enabled) {
  81560. return;
  81561. }
  81562. this._fxaaEnabled = enabled;
  81563. this._buildPipeline();
  81564. },
  81565. enumerable: true,
  81566. configurable: true
  81567. });
  81568. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  81569. get: function () {
  81570. return this._samples;
  81571. },
  81572. /**
  81573. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  81574. */
  81575. set: function (sampleCount) {
  81576. if (this._samples === sampleCount) {
  81577. return;
  81578. }
  81579. this._samples = sampleCount;
  81580. this._buildPipeline();
  81581. },
  81582. enumerable: true,
  81583. configurable: true
  81584. });
  81585. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  81586. get: function () {
  81587. return this._imageProcessingEnabled;
  81588. },
  81589. /**
  81590. * If image processing is enabled.
  81591. */
  81592. set: function (enabled) {
  81593. if (this._imageProcessingEnabled === enabled) {
  81594. return;
  81595. }
  81596. this._imageProcessingEnabled = enabled;
  81597. this._buildPipeline();
  81598. },
  81599. enumerable: true,
  81600. configurable: true
  81601. });
  81602. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  81603. get: function () {
  81604. return this._glowLayer == null;
  81605. },
  81606. /**
  81607. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  81608. */
  81609. set: function (enabled) {
  81610. if (enabled && !this._glowLayer) {
  81611. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  81612. }
  81613. else if (!enabled && this._glowLayer) {
  81614. this._glowLayer.dispose();
  81615. this._glowLayer = null;
  81616. }
  81617. },
  81618. enumerable: true,
  81619. configurable: true
  81620. });
  81621. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  81622. get: function () {
  81623. return this._chromaticAberrationEnabled;
  81624. },
  81625. /**
  81626. * Enable or disable the chromaticAberration process from the pipeline
  81627. */
  81628. set: function (enabled) {
  81629. if (this._chromaticAberrationEnabled === enabled) {
  81630. return;
  81631. }
  81632. this._chromaticAberrationEnabled = enabled;
  81633. this._buildPipeline();
  81634. },
  81635. enumerable: true,
  81636. configurable: true
  81637. });
  81638. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  81639. get: function () {
  81640. return this._grainEnabled;
  81641. },
  81642. /**
  81643. * Enable or disable the grain process from the pipeline
  81644. */
  81645. set: function (enabled) {
  81646. if (this._grainEnabled === enabled) {
  81647. return;
  81648. }
  81649. this._grainEnabled = enabled;
  81650. this._buildPipeline();
  81651. },
  81652. enumerable: true,
  81653. configurable: true
  81654. });
  81655. /**
  81656. * Force the compilation of the entire pipeline.
  81657. */
  81658. DefaultRenderingPipeline.prototype.prepare = function () {
  81659. var previousState = this._buildAllowed;
  81660. this._buildAllowed = true;
  81661. this._buildPipeline();
  81662. this._buildAllowed = previousState;
  81663. };
  81664. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  81665. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  81666. if (this._hasCleared) {
  81667. postProcess.autoClear = false;
  81668. }
  81669. else {
  81670. postProcess.autoClear = true;
  81671. this._scene.autoClear = false;
  81672. this._hasCleared = true;
  81673. }
  81674. if (!skipTextureSharing) {
  81675. if (this._prevPrevPostProcess) {
  81676. postProcess.shareOutputWith(this._prevPrevPostProcess);
  81677. }
  81678. else {
  81679. postProcess.useOwnOutput();
  81680. }
  81681. if (this._prevPostProcess) {
  81682. this._prevPrevPostProcess = this._prevPostProcess;
  81683. }
  81684. this._prevPostProcess = postProcess;
  81685. }
  81686. };
  81687. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  81688. var _this = this;
  81689. if (!this._buildAllowed) {
  81690. return;
  81691. }
  81692. this._scene.autoClear = true;
  81693. var engine = this._scene.getEngine();
  81694. this._disposePostProcesses();
  81695. if (this._cameras !== null) {
  81696. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  81697. // get back cameras to be used to reattach pipeline
  81698. this._cameras = this._camerasToBeAttached.slice();
  81699. }
  81700. this._reset();
  81701. this._prevPostProcess = null;
  81702. this._prevPrevPostProcess = null;
  81703. this._hasCleared = false;
  81704. if (this.depthOfFieldEnabled) {
  81705. // Multi camera suport
  81706. if (this._cameras.length > 1) {
  81707. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  81708. var camera = _a[_i];
  81709. var depthRenderer = this._scene.enableDepthRenderer(camera);
  81710. depthRenderer.useOnlyInActiveCamera = true;
  81711. }
  81712. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  81713. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  81714. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  81715. }
  81716. });
  81717. }
  81718. else {
  81719. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  81720. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  81721. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  81722. }
  81723. if (!this.depthOfField._isReady()) {
  81724. this.depthOfField._updateEffects();
  81725. }
  81726. this.addEffect(this.depthOfField);
  81727. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  81728. }
  81729. else {
  81730. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  81731. }
  81732. if (this.bloomEnabled) {
  81733. if (!this.bloom._isReady()) {
  81734. this.bloom._updateEffects();
  81735. }
  81736. this.addEffect(this.bloom);
  81737. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  81738. }
  81739. if (this._imageProcessingEnabled) {
  81740. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  81741. if (this._hdr) {
  81742. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  81743. this._setAutoClearAndTextureSharing(this.imageProcessing);
  81744. }
  81745. else {
  81746. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  81747. }
  81748. }
  81749. if (this.sharpenEnabled) {
  81750. if (!this.sharpen.isReady()) {
  81751. this.sharpen.updateEffect();
  81752. }
  81753. this.addEffect(this._sharpenEffect);
  81754. this._setAutoClearAndTextureSharing(this.sharpen);
  81755. }
  81756. if (this.grainEnabled) {
  81757. if (!this.grain.isReady()) {
  81758. this.grain.updateEffect();
  81759. }
  81760. this.addEffect(this._grainEffect);
  81761. this._setAutoClearAndTextureSharing(this.grain);
  81762. }
  81763. if (this.chromaticAberrationEnabled) {
  81764. if (!this.chromaticAberration.isReady()) {
  81765. this.chromaticAberration.updateEffect();
  81766. }
  81767. this.addEffect(this._chromaticAberrationEffect);
  81768. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  81769. }
  81770. if (this.fxaaEnabled) {
  81771. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  81772. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  81773. this._setAutoClearAndTextureSharing(this.fxaa, true);
  81774. }
  81775. if (this._cameras !== null) {
  81776. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  81777. }
  81778. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  81779. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  81780. }
  81781. };
  81782. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  81783. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  81784. for (var i = 0; i < this._cameras.length; i++) {
  81785. var camera = this._cameras[i];
  81786. if (this.imageProcessing) {
  81787. this.imageProcessing.dispose(camera);
  81788. }
  81789. if (this.fxaa) {
  81790. this.fxaa.dispose(camera);
  81791. }
  81792. // These are created in the constructor and should not be disposed on every pipeline change
  81793. if (disposeNonRecreated) {
  81794. if (this.sharpen) {
  81795. this.sharpen.dispose(camera);
  81796. }
  81797. if (this.depthOfField) {
  81798. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  81799. this.depthOfField.disposeEffects(camera);
  81800. }
  81801. if (this.bloom) {
  81802. this.bloom.disposeEffects(camera);
  81803. }
  81804. if (this.chromaticAberration) {
  81805. this.chromaticAberration.dispose(camera);
  81806. }
  81807. if (this.grain) {
  81808. this.grain.dispose(camera);
  81809. }
  81810. if (this._glowLayer) {
  81811. this._glowLayer.dispose();
  81812. }
  81813. }
  81814. }
  81815. this.imageProcessing = null;
  81816. this.fxaa = null;
  81817. if (disposeNonRecreated) {
  81818. this.sharpen = null;
  81819. this._sharpenEffect = null;
  81820. this.depthOfField = null;
  81821. this.bloom = null;
  81822. this.chromaticAberration = null;
  81823. this._chromaticAberrationEffect = null;
  81824. this.grain = null;
  81825. this._grainEffect = null;
  81826. this._glowLayer = null;
  81827. }
  81828. };
  81829. /**
  81830. * Adds a camera to the pipeline
  81831. * @param camera the camera to be added
  81832. */
  81833. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  81834. this._camerasToBeAttached.push(camera);
  81835. this._buildPipeline();
  81836. };
  81837. /**
  81838. * Removes a camera from the pipeline
  81839. * @param camera the camera to remove
  81840. */
  81841. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  81842. var index = this._camerasToBeAttached.indexOf(camera);
  81843. this._camerasToBeAttached.splice(index, 1);
  81844. this._buildPipeline();
  81845. };
  81846. /**
  81847. * Dispose of the pipeline and stop all post processes
  81848. */
  81849. DefaultRenderingPipeline.prototype.dispose = function () {
  81850. this._disposePostProcesses(true);
  81851. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  81852. this._scene.autoClear = true;
  81853. if (this._resizeObserver) {
  81854. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  81855. this._resizeObserver = null;
  81856. }
  81857. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  81858. _super.prototype.dispose.call(this);
  81859. };
  81860. /**
  81861. * Serialize the rendering pipeline (Used when exporting)
  81862. * @returns the serialized object
  81863. */
  81864. DefaultRenderingPipeline.prototype.serialize = function () {
  81865. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81866. serializationObject.customType = "DefaultRenderingPipeline";
  81867. return serializationObject;
  81868. };
  81869. /**
  81870. * Parse the serialized pipeline
  81871. * @param source Source pipeline.
  81872. * @param scene The scene to load the pipeline to.
  81873. * @param rootUrl The URL of the serialized pipeline.
  81874. * @returns An instantiated pipeline from the serialized object.
  81875. */
  81876. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  81877. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  81878. };
  81879. __decorate([
  81880. BABYLON.serialize()
  81881. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  81882. __decorate([
  81883. BABYLON.serialize()
  81884. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  81885. __decorate([
  81886. BABYLON.serialize()
  81887. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  81888. __decorate([
  81889. BABYLON.serialize()
  81890. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  81891. __decorate([
  81892. BABYLON.serialize()
  81893. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  81894. __decorate([
  81895. BABYLON.serialize()
  81896. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  81897. __decorate([
  81898. BABYLON.serialize()
  81899. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  81900. __decorate([
  81901. BABYLON.serialize()
  81902. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  81903. __decorate([
  81904. BABYLON.serialize()
  81905. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  81906. __decorate([
  81907. BABYLON.serialize()
  81908. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  81909. __decorate([
  81910. BABYLON.serialize()
  81911. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  81912. __decorate([
  81913. BABYLON.serialize()
  81914. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  81915. __decorate([
  81916. BABYLON.serialize()
  81917. ], DefaultRenderingPipeline.prototype, "samples", null);
  81918. __decorate([
  81919. BABYLON.serialize()
  81920. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  81921. __decorate([
  81922. BABYLON.serialize()
  81923. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  81924. __decorate([
  81925. BABYLON.serialize()
  81926. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  81927. __decorate([
  81928. BABYLON.serialize()
  81929. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  81930. return DefaultRenderingPipeline;
  81931. }(BABYLON.PostProcessRenderPipeline));
  81932. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  81933. })(BABYLON || (BABYLON = {}));
  81934. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  81935. var BABYLON;
  81936. (function (BABYLON) {
  81937. /**
  81938. * @hidden
  81939. */
  81940. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  81941. __extends(ImageProcessingConfigurationDefines, _super);
  81942. function ImageProcessingConfigurationDefines() {
  81943. var _this = _super.call(this) || this;
  81944. _this.IMAGEPROCESSING = false;
  81945. _this.VIGNETTE = false;
  81946. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  81947. _this.VIGNETTEBLENDMODEOPAQUE = false;
  81948. _this.TONEMAPPING = false;
  81949. _this.TONEMAPPING_ACES = false;
  81950. _this.CONTRAST = false;
  81951. _this.COLORCURVES = false;
  81952. _this.COLORGRADING = false;
  81953. _this.COLORGRADING3D = false;
  81954. _this.SAMPLER3DGREENDEPTH = false;
  81955. _this.SAMPLER3DBGRMAP = false;
  81956. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  81957. _this.EXPOSURE = false;
  81958. _this.rebuild();
  81959. return _this;
  81960. }
  81961. return ImageProcessingConfigurationDefines;
  81962. }(BABYLON.MaterialDefines));
  81963. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  81964. /**
  81965. * This groups together the common properties used for image processing either in direct forward pass
  81966. * or through post processing effect depending on the use of the image processing pipeline in your scene
  81967. * or not.
  81968. */
  81969. var ImageProcessingConfiguration = /** @class */ (function () {
  81970. function ImageProcessingConfiguration() {
  81971. /**
  81972. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  81973. */
  81974. this.colorCurves = new BABYLON.ColorCurves();
  81975. this._colorCurvesEnabled = false;
  81976. this._colorGradingEnabled = false;
  81977. this._colorGradingWithGreenDepth = true;
  81978. this._colorGradingBGR = true;
  81979. /** @hidden */
  81980. this._exposure = 1.0;
  81981. this._toneMappingEnabled = false;
  81982. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  81983. this._contrast = 1.0;
  81984. /**
  81985. * Vignette stretch size.
  81986. */
  81987. this.vignetteStretch = 0;
  81988. /**
  81989. * Vignette centre X Offset.
  81990. */
  81991. this.vignetteCentreX = 0;
  81992. /**
  81993. * Vignette centre Y Offset.
  81994. */
  81995. this.vignetteCentreY = 0;
  81996. /**
  81997. * Vignette weight or intensity of the vignette effect.
  81998. */
  81999. this.vignetteWeight = 1.5;
  82000. /**
  82001. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  82002. * if vignetteEnabled is set to true.
  82003. */
  82004. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  82005. /**
  82006. * Camera field of view used by the Vignette effect.
  82007. */
  82008. this.vignetteCameraFov = 0.5;
  82009. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  82010. this._vignetteEnabled = false;
  82011. this._applyByPostProcess = false;
  82012. this._isEnabled = true;
  82013. /**
  82014. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  82015. */
  82016. this.onUpdateParameters = new BABYLON.Observable();
  82017. }
  82018. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  82019. /**
  82020. * Gets wether the color curves effect is enabled.
  82021. */
  82022. get: function () {
  82023. return this._colorCurvesEnabled;
  82024. },
  82025. /**
  82026. * Sets wether the color curves effect is enabled.
  82027. */
  82028. set: function (value) {
  82029. if (this._colorCurvesEnabled === value) {
  82030. return;
  82031. }
  82032. this._colorCurvesEnabled = value;
  82033. this._updateParameters();
  82034. },
  82035. enumerable: true,
  82036. configurable: true
  82037. });
  82038. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  82039. /**
  82040. * Gets wether the color grading effect is enabled.
  82041. */
  82042. get: function () {
  82043. return this._colorGradingEnabled;
  82044. },
  82045. /**
  82046. * Sets wether the color grading effect is enabled.
  82047. */
  82048. set: function (value) {
  82049. if (this._colorGradingEnabled === value) {
  82050. return;
  82051. }
  82052. this._colorGradingEnabled = value;
  82053. this._updateParameters();
  82054. },
  82055. enumerable: true,
  82056. configurable: true
  82057. });
  82058. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  82059. /**
  82060. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  82061. */
  82062. get: function () {
  82063. return this._colorGradingWithGreenDepth;
  82064. },
  82065. /**
  82066. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  82067. */
  82068. set: function (value) {
  82069. if (this._colorGradingWithGreenDepth === value) {
  82070. return;
  82071. }
  82072. this._colorGradingWithGreenDepth = value;
  82073. this._updateParameters();
  82074. },
  82075. enumerable: true,
  82076. configurable: true
  82077. });
  82078. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  82079. /**
  82080. * Gets wether the color grading texture contains BGR values.
  82081. */
  82082. get: function () {
  82083. return this._colorGradingBGR;
  82084. },
  82085. /**
  82086. * Sets wether the color grading texture contains BGR values.
  82087. */
  82088. set: function (value) {
  82089. if (this._colorGradingBGR === value) {
  82090. return;
  82091. }
  82092. this._colorGradingBGR = value;
  82093. this._updateParameters();
  82094. },
  82095. enumerable: true,
  82096. configurable: true
  82097. });
  82098. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  82099. /**
  82100. * Gets the Exposure used in the effect.
  82101. */
  82102. get: function () {
  82103. return this._exposure;
  82104. },
  82105. /**
  82106. * Sets the Exposure used in the effect.
  82107. */
  82108. set: function (value) {
  82109. if (this._exposure === value) {
  82110. return;
  82111. }
  82112. this._exposure = value;
  82113. this._updateParameters();
  82114. },
  82115. enumerable: true,
  82116. configurable: true
  82117. });
  82118. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  82119. /**
  82120. * Gets wether the tone mapping effect is enabled.
  82121. */
  82122. get: function () {
  82123. return this._toneMappingEnabled;
  82124. },
  82125. /**
  82126. * Sets wether the tone mapping effect is enabled.
  82127. */
  82128. set: function (value) {
  82129. if (this._toneMappingEnabled === value) {
  82130. return;
  82131. }
  82132. this._toneMappingEnabled = value;
  82133. this._updateParameters();
  82134. },
  82135. enumerable: true,
  82136. configurable: true
  82137. });
  82138. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  82139. /**
  82140. * Gets the type of tone mapping effect.
  82141. */
  82142. get: function () {
  82143. return this._toneMappingType;
  82144. },
  82145. /**
  82146. * Sets the type of tone mapping effect used in BabylonJS.
  82147. */
  82148. set: function (value) {
  82149. if (this._toneMappingType === value) {
  82150. return;
  82151. }
  82152. this._toneMappingType = value;
  82153. this._updateParameters();
  82154. },
  82155. enumerable: true,
  82156. configurable: true
  82157. });
  82158. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  82159. /**
  82160. * Gets the contrast used in the effect.
  82161. */
  82162. get: function () {
  82163. return this._contrast;
  82164. },
  82165. /**
  82166. * Sets the contrast used in the effect.
  82167. */
  82168. set: function (value) {
  82169. if (this._contrast === value) {
  82170. return;
  82171. }
  82172. this._contrast = value;
  82173. this._updateParameters();
  82174. },
  82175. enumerable: true,
  82176. configurable: true
  82177. });
  82178. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  82179. /**
  82180. * Gets the vignette blend mode allowing different kind of effect.
  82181. */
  82182. get: function () {
  82183. return this._vignetteBlendMode;
  82184. },
  82185. /**
  82186. * Sets the vignette blend mode allowing different kind of effect.
  82187. */
  82188. set: function (value) {
  82189. if (this._vignetteBlendMode === value) {
  82190. return;
  82191. }
  82192. this._vignetteBlendMode = value;
  82193. this._updateParameters();
  82194. },
  82195. enumerable: true,
  82196. configurable: true
  82197. });
  82198. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  82199. /**
  82200. * Gets wether the vignette effect is enabled.
  82201. */
  82202. get: function () {
  82203. return this._vignetteEnabled;
  82204. },
  82205. /**
  82206. * Sets wether the vignette effect is enabled.
  82207. */
  82208. set: function (value) {
  82209. if (this._vignetteEnabled === value) {
  82210. return;
  82211. }
  82212. this._vignetteEnabled = value;
  82213. this._updateParameters();
  82214. },
  82215. enumerable: true,
  82216. configurable: true
  82217. });
  82218. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  82219. /**
  82220. * Gets wether the image processing is applied through a post process or not.
  82221. */
  82222. get: function () {
  82223. return this._applyByPostProcess;
  82224. },
  82225. /**
  82226. * Sets wether the image processing is applied through a post process or not.
  82227. */
  82228. set: function (value) {
  82229. if (this._applyByPostProcess === value) {
  82230. return;
  82231. }
  82232. this._applyByPostProcess = value;
  82233. this._updateParameters();
  82234. },
  82235. enumerable: true,
  82236. configurable: true
  82237. });
  82238. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  82239. /**
  82240. * Gets wether the image processing is enabled or not.
  82241. */
  82242. get: function () {
  82243. return this._isEnabled;
  82244. },
  82245. /**
  82246. * Sets wether the image processing is enabled or not.
  82247. */
  82248. set: function (value) {
  82249. if (this._isEnabled === value) {
  82250. return;
  82251. }
  82252. this._isEnabled = value;
  82253. this._updateParameters();
  82254. },
  82255. enumerable: true,
  82256. configurable: true
  82257. });
  82258. /**
  82259. * Method called each time the image processing information changes requires to recompile the effect.
  82260. */
  82261. ImageProcessingConfiguration.prototype._updateParameters = function () {
  82262. this.onUpdateParameters.notifyObservers(this);
  82263. };
  82264. ImageProcessingConfiguration.prototype.getClassName = function () {
  82265. return "ImageProcessingConfiguration";
  82266. };
  82267. /**
  82268. * Prepare the list of uniforms associated with the Image Processing effects.
  82269. * @param uniformsList The list of uniforms used in the effect
  82270. * @param defines the list of defines currently in use
  82271. */
  82272. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  82273. if (defines.EXPOSURE) {
  82274. uniforms.push("exposureLinear");
  82275. }
  82276. if (defines.CONTRAST) {
  82277. uniforms.push("contrast");
  82278. }
  82279. if (defines.COLORGRADING) {
  82280. uniforms.push("colorTransformSettings");
  82281. }
  82282. if (defines.VIGNETTE) {
  82283. uniforms.push("vInverseScreenSize");
  82284. uniforms.push("vignetteSettings1");
  82285. uniforms.push("vignetteSettings2");
  82286. }
  82287. if (defines.COLORCURVES) {
  82288. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  82289. }
  82290. };
  82291. /**
  82292. * Prepare the list of samplers associated with the Image Processing effects.
  82293. * @param uniformsList The list of uniforms used in the effect
  82294. * @param defines the list of defines currently in use
  82295. */
  82296. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  82297. if (defines.COLORGRADING) {
  82298. samplersList.push("txColorTransform");
  82299. }
  82300. };
  82301. /**
  82302. * Prepare the list of defines associated to the shader.
  82303. * @param defines the list of defines to complete
  82304. */
  82305. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  82306. if (forPostProcess === void 0) { forPostProcess = false; }
  82307. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  82308. defines.VIGNETTE = false;
  82309. defines.TONEMAPPING = false;
  82310. defines.TONEMAPPING_ACES = false;
  82311. defines.CONTRAST = false;
  82312. defines.EXPOSURE = false;
  82313. defines.COLORCURVES = false;
  82314. defines.COLORGRADING = false;
  82315. defines.COLORGRADING3D = false;
  82316. defines.IMAGEPROCESSING = false;
  82317. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  82318. return;
  82319. }
  82320. defines.VIGNETTE = this.vignetteEnabled;
  82321. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  82322. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  82323. defines.TONEMAPPING = this.toneMappingEnabled;
  82324. switch (this._toneMappingType) {
  82325. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  82326. defines.TONEMAPPING_ACES = true;
  82327. break;
  82328. }
  82329. defines.CONTRAST = (this.contrast !== 1.0);
  82330. defines.EXPOSURE = (this.exposure !== 1.0);
  82331. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  82332. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  82333. if (defines.COLORGRADING) {
  82334. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  82335. }
  82336. else {
  82337. defines.COLORGRADING3D = false;
  82338. }
  82339. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  82340. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  82341. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  82342. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  82343. };
  82344. /**
  82345. * Returns true if all the image processing information are ready.
  82346. */
  82347. ImageProcessingConfiguration.prototype.isReady = function () {
  82348. // Color Grading texure can not be none blocking.
  82349. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  82350. };
  82351. /**
  82352. * Binds the image processing to the shader.
  82353. * @param effect The effect to bind to
  82354. */
  82355. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  82356. if (aspectRatio === void 0) { aspectRatio = 1; }
  82357. // Color Curves
  82358. if (this._colorCurvesEnabled && this.colorCurves) {
  82359. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  82360. }
  82361. // Vignette
  82362. if (this._vignetteEnabled) {
  82363. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  82364. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  82365. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  82366. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  82367. var vignetteScaleX = vignetteScaleY * aspectRatio;
  82368. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  82369. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  82370. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  82371. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  82372. var vignettePower = -2.0 * this.vignetteWeight;
  82373. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  82374. }
  82375. // Exposure
  82376. effect.setFloat("exposureLinear", this.exposure);
  82377. // Contrast
  82378. effect.setFloat("contrast", this.contrast);
  82379. // Color transform settings
  82380. if (this.colorGradingTexture) {
  82381. effect.setTexture("txColorTransform", this.colorGradingTexture);
  82382. var textureSize = this.colorGradingTexture.getSize().height;
  82383. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  82384. 0.5 / textureSize, // textureOffset
  82385. textureSize, // textureSize
  82386. this.colorGradingTexture.level // weight
  82387. );
  82388. }
  82389. };
  82390. /**
  82391. * Clones the current image processing instance.
  82392. * @return The cloned image processing
  82393. */
  82394. ImageProcessingConfiguration.prototype.clone = function () {
  82395. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  82396. };
  82397. /**
  82398. * Serializes the current image processing instance to a json representation.
  82399. * @return a JSON representation
  82400. */
  82401. ImageProcessingConfiguration.prototype.serialize = function () {
  82402. return BABYLON.SerializationHelper.Serialize(this);
  82403. };
  82404. /**
  82405. * Parses the image processing from a json representation.
  82406. * @param source the JSON source to parse
  82407. * @return The parsed image processing
  82408. */
  82409. ImageProcessingConfiguration.Parse = function (source) {
  82410. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  82411. };
  82412. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  82413. /**
  82414. * Used to apply the vignette as a mix with the pixel color.
  82415. */
  82416. get: function () {
  82417. return this._VIGNETTEMODE_MULTIPLY;
  82418. },
  82419. enumerable: true,
  82420. configurable: true
  82421. });
  82422. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  82423. /**
  82424. * Used to apply the vignette as a replacement of the pixel color.
  82425. */
  82426. get: function () {
  82427. return this._VIGNETTEMODE_OPAQUE;
  82428. },
  82429. enumerable: true,
  82430. configurable: true
  82431. });
  82432. /**
  82433. * Default tone mapping applied in BabylonJS.
  82434. */
  82435. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  82436. /**
  82437. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  82438. * to other engines rendering to increase portability.
  82439. */
  82440. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  82441. // Static constants associated to the image processing.
  82442. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  82443. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  82444. __decorate([
  82445. BABYLON.serializeAsColorCurves()
  82446. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  82447. __decorate([
  82448. BABYLON.serialize()
  82449. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  82450. __decorate([
  82451. BABYLON.serializeAsTexture()
  82452. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  82453. __decorate([
  82454. BABYLON.serialize()
  82455. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  82456. __decorate([
  82457. BABYLON.serialize()
  82458. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  82459. __decorate([
  82460. BABYLON.serialize()
  82461. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  82462. __decorate([
  82463. BABYLON.serialize()
  82464. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  82465. __decorate([
  82466. BABYLON.serialize()
  82467. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  82468. __decorate([
  82469. BABYLON.serialize()
  82470. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  82471. __decorate([
  82472. BABYLON.serialize()
  82473. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  82474. __decorate([
  82475. BABYLON.serialize()
  82476. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  82477. __decorate([
  82478. BABYLON.serialize()
  82479. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  82480. __decorate([
  82481. BABYLON.serialize()
  82482. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  82483. __decorate([
  82484. BABYLON.serialize()
  82485. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  82486. __decorate([
  82487. BABYLON.serializeAsColor4()
  82488. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  82489. __decorate([
  82490. BABYLON.serialize()
  82491. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  82492. __decorate([
  82493. BABYLON.serialize()
  82494. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  82495. __decorate([
  82496. BABYLON.serialize()
  82497. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  82498. __decorate([
  82499. BABYLON.serialize()
  82500. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  82501. __decorate([
  82502. BABYLON.serialize()
  82503. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  82504. return ImageProcessingConfiguration;
  82505. }());
  82506. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  82507. })(BABYLON || (BABYLON = {}));
  82508. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  82509. var BABYLON;
  82510. (function (BABYLON) {
  82511. /**
  82512. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  82513. * It can help converting any input color in a desired output one. This can then be used to create effects
  82514. * from sepia, black and white to sixties or futuristic rendering...
  82515. *
  82516. * The only supported format is currently 3dl.
  82517. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  82518. */
  82519. var ColorGradingTexture = /** @class */ (function (_super) {
  82520. __extends(ColorGradingTexture, _super);
  82521. /**
  82522. * Instantiates a ColorGradingTexture from the following parameters.
  82523. *
  82524. * @param url The location of the color gradind data (currently only supporting 3dl)
  82525. * @param scene The scene the texture will be used in
  82526. */
  82527. function ColorGradingTexture(url, scene) {
  82528. var _this = _super.call(this, scene) || this;
  82529. if (!url) {
  82530. return _this;
  82531. }
  82532. _this._engine = scene.getEngine();
  82533. _this._textureMatrix = BABYLON.Matrix.Identity();
  82534. _this.name = url;
  82535. _this.url = url;
  82536. _this.hasAlpha = false;
  82537. _this.isCube = false;
  82538. _this.is3D = _this._engine.webGLVersion > 1;
  82539. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82540. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82541. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82542. _this.anisotropicFilteringLevel = 1;
  82543. _this._texture = _this._getFromCache(url, true);
  82544. if (!_this._texture) {
  82545. if (!scene.useDelayedTextureLoading) {
  82546. _this.loadTexture();
  82547. }
  82548. else {
  82549. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82550. }
  82551. }
  82552. return _this;
  82553. }
  82554. /**
  82555. * Returns the texture matrix used in most of the material.
  82556. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  82557. */
  82558. ColorGradingTexture.prototype.getTextureMatrix = function () {
  82559. return this._textureMatrix;
  82560. };
  82561. /**
  82562. * Occurs when the file being loaded is a .3dl LUT file.
  82563. */
  82564. ColorGradingTexture.prototype.load3dlTexture = function () {
  82565. var engine = this._engine;
  82566. var texture;
  82567. if (engine.webGLVersion === 1) {
  82568. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82569. }
  82570. else {
  82571. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82572. }
  82573. this._texture = texture;
  82574. var callback = function (text) {
  82575. if (typeof text !== "string") {
  82576. return;
  82577. }
  82578. var data = null;
  82579. var tempData = null;
  82580. var line;
  82581. var lines = text.split('\n');
  82582. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  82583. var maxColor = 0;
  82584. for (var i = 0; i < lines.length; i++) {
  82585. line = lines[i];
  82586. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  82587. continue;
  82588. if (line.indexOf('#') === 0)
  82589. continue;
  82590. var words = line.split(" ");
  82591. if (size === 0) {
  82592. // Number of space + one
  82593. size = words.length;
  82594. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  82595. tempData = new Float32Array(size * size * size * 4);
  82596. continue;
  82597. }
  82598. if (size != 0) {
  82599. var r = Math.max(parseInt(words[0]), 0);
  82600. var g = Math.max(parseInt(words[1]), 0);
  82601. var b = Math.max(parseInt(words[2]), 0);
  82602. maxColor = Math.max(r, maxColor);
  82603. maxColor = Math.max(g, maxColor);
  82604. maxColor = Math.max(b, maxColor);
  82605. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  82606. if (tempData) {
  82607. tempData[pixelStorageIndex + 0] = r;
  82608. tempData[pixelStorageIndex + 1] = g;
  82609. tempData[pixelStorageIndex + 2] = b;
  82610. }
  82611. pixelIndexSlice++;
  82612. if (pixelIndexSlice % size == 0) {
  82613. pixelIndexH++;
  82614. pixelIndexSlice = 0;
  82615. if (pixelIndexH % size == 0) {
  82616. pixelIndexW++;
  82617. pixelIndexH = 0;
  82618. }
  82619. }
  82620. }
  82621. }
  82622. if (tempData && data) {
  82623. for (var i = 0; i < tempData.length; i++) {
  82624. if (i > 0 && (i + 1) % 4 === 0) {
  82625. data[i] = 255;
  82626. }
  82627. else {
  82628. var value = tempData[i];
  82629. data[i] = (value / maxColor * 255);
  82630. }
  82631. }
  82632. }
  82633. if (texture.is3D) {
  82634. texture.updateSize(size, size, size);
  82635. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  82636. }
  82637. else {
  82638. texture.updateSize(size * size, size);
  82639. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  82640. }
  82641. };
  82642. var scene = this.getScene();
  82643. if (scene) {
  82644. scene._loadFile(this.url, callback);
  82645. }
  82646. else {
  82647. this._engine._loadFile(this.url, callback);
  82648. }
  82649. return this._texture;
  82650. };
  82651. /**
  82652. * Starts the loading process of the texture.
  82653. */
  82654. ColorGradingTexture.prototype.loadTexture = function () {
  82655. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  82656. this.load3dlTexture();
  82657. }
  82658. };
  82659. /**
  82660. * Clones the color gradind texture.
  82661. */
  82662. ColorGradingTexture.prototype.clone = function () {
  82663. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  82664. // Base texture
  82665. newTexture.level = this.level;
  82666. return newTexture;
  82667. };
  82668. /**
  82669. * Called during delayed load for textures.
  82670. */
  82671. ColorGradingTexture.prototype.delayLoad = function () {
  82672. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  82673. return;
  82674. }
  82675. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  82676. this._texture = this._getFromCache(this.url, true);
  82677. if (!this._texture) {
  82678. this.loadTexture();
  82679. }
  82680. };
  82681. /**
  82682. * Parses a color grading texture serialized by Babylon.
  82683. * @param parsedTexture The texture information being parsedTexture
  82684. * @param scene The scene to load the texture in
  82685. * @param rootUrl The root url of the data assets to load
  82686. * @return A color gradind texture
  82687. */
  82688. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  82689. var texture = null;
  82690. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  82691. texture = new ColorGradingTexture(parsedTexture.name, scene);
  82692. texture.name = parsedTexture.name;
  82693. texture.level = parsedTexture.level;
  82694. }
  82695. return texture;
  82696. };
  82697. /**
  82698. * Serializes the LUT texture to json format.
  82699. */
  82700. ColorGradingTexture.prototype.serialize = function () {
  82701. if (!this.name) {
  82702. return null;
  82703. }
  82704. var serializationObject = {};
  82705. serializationObject.name = this.name;
  82706. serializationObject.level = this.level;
  82707. serializationObject.customType = "BABYLON.ColorGradingTexture";
  82708. return serializationObject;
  82709. };
  82710. /**
  82711. * Empty line regex stored for GC.
  82712. */
  82713. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  82714. return ColorGradingTexture;
  82715. }(BABYLON.BaseTexture));
  82716. BABYLON.ColorGradingTexture = ColorGradingTexture;
  82717. })(BABYLON || (BABYLON = {}));
  82718. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  82719. var BABYLON;
  82720. (function (BABYLON) {
  82721. /**
  82722. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  82723. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  82724. * 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;
  82725. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  82726. */
  82727. var ColorCurves = /** @class */ (function () {
  82728. function ColorCurves() {
  82729. this._dirty = true;
  82730. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  82731. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  82732. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  82733. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  82734. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  82735. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  82736. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  82737. this._globalHue = 30;
  82738. this._globalDensity = 0;
  82739. this._globalSaturation = 0;
  82740. this._globalExposure = 0;
  82741. this._highlightsHue = 30;
  82742. this._highlightsDensity = 0;
  82743. this._highlightsSaturation = 0;
  82744. this._highlightsExposure = 0;
  82745. this._midtonesHue = 30;
  82746. this._midtonesDensity = 0;
  82747. this._midtonesSaturation = 0;
  82748. this._midtonesExposure = 0;
  82749. this._shadowsHue = 30;
  82750. this._shadowsDensity = 0;
  82751. this._shadowsSaturation = 0;
  82752. this._shadowsExposure = 0;
  82753. }
  82754. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  82755. /**
  82756. * Gets the global Hue value.
  82757. * 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).
  82758. */
  82759. get: function () {
  82760. return this._globalHue;
  82761. },
  82762. /**
  82763. * Sets the global Hue value.
  82764. * 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).
  82765. */
  82766. set: function (value) {
  82767. this._globalHue = value;
  82768. this._dirty = true;
  82769. },
  82770. enumerable: true,
  82771. configurable: true
  82772. });
  82773. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  82774. /**
  82775. * Gets the global Density value.
  82776. * 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.
  82777. * Values less than zero provide a filter of opposite hue.
  82778. */
  82779. get: function () {
  82780. return this._globalDensity;
  82781. },
  82782. /**
  82783. * Sets the global Density value.
  82784. * 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.
  82785. * Values less than zero provide a filter of opposite hue.
  82786. */
  82787. set: function (value) {
  82788. this._globalDensity = value;
  82789. this._dirty = true;
  82790. },
  82791. enumerable: true,
  82792. configurable: true
  82793. });
  82794. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  82795. /**
  82796. * Gets the global Saturation value.
  82797. * 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.
  82798. */
  82799. get: function () {
  82800. return this._globalSaturation;
  82801. },
  82802. /**
  82803. * Sets the global Saturation value.
  82804. * 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.
  82805. */
  82806. set: function (value) {
  82807. this._globalSaturation = value;
  82808. this._dirty = true;
  82809. },
  82810. enumerable: true,
  82811. configurable: true
  82812. });
  82813. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  82814. /**
  82815. * Gets the global Exposure value.
  82816. * 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.
  82817. */
  82818. get: function () {
  82819. return this._globalExposure;
  82820. },
  82821. /**
  82822. * Sets the global Exposure value.
  82823. * 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.
  82824. */
  82825. set: function (value) {
  82826. this._globalExposure = value;
  82827. this._dirty = true;
  82828. },
  82829. enumerable: true,
  82830. configurable: true
  82831. });
  82832. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  82833. /**
  82834. * Gets the highlights Hue value.
  82835. * 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).
  82836. */
  82837. get: function () {
  82838. return this._highlightsHue;
  82839. },
  82840. /**
  82841. * Sets the highlights Hue value.
  82842. * 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).
  82843. */
  82844. set: function (value) {
  82845. this._highlightsHue = value;
  82846. this._dirty = true;
  82847. },
  82848. enumerable: true,
  82849. configurable: true
  82850. });
  82851. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  82852. /**
  82853. * Gets the highlights Density value.
  82854. * 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.
  82855. * Values less than zero provide a filter of opposite hue.
  82856. */
  82857. get: function () {
  82858. return this._highlightsDensity;
  82859. },
  82860. /**
  82861. * Sets the highlights Density value.
  82862. * 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.
  82863. * Values less than zero provide a filter of opposite hue.
  82864. */
  82865. set: function (value) {
  82866. this._highlightsDensity = value;
  82867. this._dirty = true;
  82868. },
  82869. enumerable: true,
  82870. configurable: true
  82871. });
  82872. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  82873. /**
  82874. * Gets the highlights Saturation value.
  82875. * 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.
  82876. */
  82877. get: function () {
  82878. return this._highlightsSaturation;
  82879. },
  82880. /**
  82881. * Sets the highlights Saturation value.
  82882. * 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.
  82883. */
  82884. set: function (value) {
  82885. this._highlightsSaturation = value;
  82886. this._dirty = true;
  82887. },
  82888. enumerable: true,
  82889. configurable: true
  82890. });
  82891. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  82892. /**
  82893. * Gets the highlights Exposure value.
  82894. * 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.
  82895. */
  82896. get: function () {
  82897. return this._highlightsExposure;
  82898. },
  82899. /**
  82900. * Sets the highlights Exposure value.
  82901. * 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.
  82902. */
  82903. set: function (value) {
  82904. this._highlightsExposure = value;
  82905. this._dirty = true;
  82906. },
  82907. enumerable: true,
  82908. configurable: true
  82909. });
  82910. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  82911. /**
  82912. * Gets the midtones Hue value.
  82913. * 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).
  82914. */
  82915. get: function () {
  82916. return this._midtonesHue;
  82917. },
  82918. /**
  82919. * Sets the midtones Hue value.
  82920. * 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).
  82921. */
  82922. set: function (value) {
  82923. this._midtonesHue = value;
  82924. this._dirty = true;
  82925. },
  82926. enumerable: true,
  82927. configurable: true
  82928. });
  82929. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  82930. /**
  82931. * Gets the midtones Density value.
  82932. * 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.
  82933. * Values less than zero provide a filter of opposite hue.
  82934. */
  82935. get: function () {
  82936. return this._midtonesDensity;
  82937. },
  82938. /**
  82939. * Sets the midtones Density value.
  82940. * 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.
  82941. * Values less than zero provide a filter of opposite hue.
  82942. */
  82943. set: function (value) {
  82944. this._midtonesDensity = value;
  82945. this._dirty = true;
  82946. },
  82947. enumerable: true,
  82948. configurable: true
  82949. });
  82950. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  82951. /**
  82952. * Gets the midtones Saturation value.
  82953. * 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.
  82954. */
  82955. get: function () {
  82956. return this._midtonesSaturation;
  82957. },
  82958. /**
  82959. * Sets the midtones Saturation value.
  82960. * 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.
  82961. */
  82962. set: function (value) {
  82963. this._midtonesSaturation = value;
  82964. this._dirty = true;
  82965. },
  82966. enumerable: true,
  82967. configurable: true
  82968. });
  82969. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  82970. /**
  82971. * Gets the midtones Exposure value.
  82972. * 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.
  82973. */
  82974. get: function () {
  82975. return this._midtonesExposure;
  82976. },
  82977. /**
  82978. * Sets the midtones Exposure value.
  82979. * 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.
  82980. */
  82981. set: function (value) {
  82982. this._midtonesExposure = value;
  82983. this._dirty = true;
  82984. },
  82985. enumerable: true,
  82986. configurable: true
  82987. });
  82988. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  82989. /**
  82990. * Gets the shadows Hue value.
  82991. * 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).
  82992. */
  82993. get: function () {
  82994. return this._shadowsHue;
  82995. },
  82996. /**
  82997. * Sets the shadows Hue value.
  82998. * 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).
  82999. */
  83000. set: function (value) {
  83001. this._shadowsHue = value;
  83002. this._dirty = true;
  83003. },
  83004. enumerable: true,
  83005. configurable: true
  83006. });
  83007. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  83008. /**
  83009. * Gets the shadows Density value.
  83010. * 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.
  83011. * Values less than zero provide a filter of opposite hue.
  83012. */
  83013. get: function () {
  83014. return this._shadowsDensity;
  83015. },
  83016. /**
  83017. * Sets the shadows Density value.
  83018. * 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.
  83019. * Values less than zero provide a filter of opposite hue.
  83020. */
  83021. set: function (value) {
  83022. this._shadowsDensity = value;
  83023. this._dirty = true;
  83024. },
  83025. enumerable: true,
  83026. configurable: true
  83027. });
  83028. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  83029. /**
  83030. * Gets the shadows Saturation value.
  83031. * 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.
  83032. */
  83033. get: function () {
  83034. return this._shadowsSaturation;
  83035. },
  83036. /**
  83037. * Sets the shadows Saturation value.
  83038. * 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.
  83039. */
  83040. set: function (value) {
  83041. this._shadowsSaturation = value;
  83042. this._dirty = true;
  83043. },
  83044. enumerable: true,
  83045. configurable: true
  83046. });
  83047. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  83048. /**
  83049. * Gets the shadows Exposure value.
  83050. * 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.
  83051. */
  83052. get: function () {
  83053. return this._shadowsExposure;
  83054. },
  83055. /**
  83056. * Sets the shadows Exposure value.
  83057. * 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.
  83058. */
  83059. set: function (value) {
  83060. this._shadowsExposure = value;
  83061. this._dirty = true;
  83062. },
  83063. enumerable: true,
  83064. configurable: true
  83065. });
  83066. ColorCurves.prototype.getClassName = function () {
  83067. return "ColorCurves";
  83068. };
  83069. /**
  83070. * Binds the color curves to the shader.
  83071. * @param colorCurves The color curve to bind
  83072. * @param effect The effect to bind to
  83073. */
  83074. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  83075. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  83076. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  83077. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  83078. if (colorCurves._dirty) {
  83079. colorCurves._dirty = false;
  83080. // Fill in global info.
  83081. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  83082. // Compute highlights info.
  83083. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  83084. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  83085. // Compute midtones info.
  83086. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  83087. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  83088. // Compute shadows info.
  83089. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  83090. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  83091. // Compute deltas (neutral is midtones).
  83092. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  83093. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  83094. }
  83095. if (effect) {
  83096. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  83097. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  83098. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  83099. }
  83100. };
  83101. /**
  83102. * Prepare the list of uniforms associated with the ColorCurves effects.
  83103. * @param uniformsList The list of uniforms used in the effect
  83104. */
  83105. ColorCurves.PrepareUniforms = function (uniformsList) {
  83106. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  83107. };
  83108. /**
  83109. * Returns color grading data based on a hue, density, saturation and exposure value.
  83110. * @param filterHue The hue of the color filter.
  83111. * @param filterDensity The density of the color filter.
  83112. * @param saturation The saturation.
  83113. * @param exposure The exposure.
  83114. * @param result The result data container.
  83115. */
  83116. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  83117. if (hue == null) {
  83118. return;
  83119. }
  83120. hue = ColorCurves.clamp(hue, 0, 360);
  83121. density = ColorCurves.clamp(density, -100, 100);
  83122. saturation = ColorCurves.clamp(saturation, -100, 100);
  83123. exposure = ColorCurves.clamp(exposure, -100, 100);
  83124. // Remap the slider/config filter density with non-linear mapping and also scale by half
  83125. // so that the maximum filter density is only 50% control. This provides fine control
  83126. // for small values and reasonable range.
  83127. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  83128. density *= 0.5;
  83129. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  83130. if (density < 0) {
  83131. density *= -1;
  83132. hue = (hue + 180) % 360;
  83133. }
  83134. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  83135. result.scaleToRef(2, result);
  83136. result.a = 1 + 0.01 * saturation;
  83137. };
  83138. /**
  83139. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  83140. * @param value The input slider value in range [-100,100].
  83141. * @returns Adjusted value.
  83142. */
  83143. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  83144. value /= 100;
  83145. var x = Math.abs(value);
  83146. x = Math.pow(x, 2);
  83147. if (value < 0) {
  83148. x *= -1;
  83149. }
  83150. x *= 100;
  83151. return x;
  83152. };
  83153. /**
  83154. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  83155. * @param hue The hue (H) input.
  83156. * @param saturation The saturation (S) input.
  83157. * @param brightness The brightness (B) input.
  83158. * @result An RGBA color represented as Vector4.
  83159. */
  83160. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  83161. var h = ColorCurves.clamp(hue, 0, 360);
  83162. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  83163. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  83164. if (s === 0) {
  83165. result.r = v;
  83166. result.g = v;
  83167. result.b = v;
  83168. }
  83169. else {
  83170. // sector 0 to 5
  83171. h /= 60;
  83172. var i = Math.floor(h);
  83173. // fractional part of h
  83174. var f = h - i;
  83175. var p = v * (1 - s);
  83176. var q = v * (1 - s * f);
  83177. var t = v * (1 - s * (1 - f));
  83178. switch (i) {
  83179. case 0:
  83180. result.r = v;
  83181. result.g = t;
  83182. result.b = p;
  83183. break;
  83184. case 1:
  83185. result.r = q;
  83186. result.g = v;
  83187. result.b = p;
  83188. break;
  83189. case 2:
  83190. result.r = p;
  83191. result.g = v;
  83192. result.b = t;
  83193. break;
  83194. case 3:
  83195. result.r = p;
  83196. result.g = q;
  83197. result.b = v;
  83198. break;
  83199. case 4:
  83200. result.r = t;
  83201. result.g = p;
  83202. result.b = v;
  83203. break;
  83204. default: // case 5:
  83205. result.r = v;
  83206. result.g = p;
  83207. result.b = q;
  83208. break;
  83209. }
  83210. }
  83211. result.a = 1;
  83212. };
  83213. /**
  83214. * Returns a value clamped between min and max
  83215. * @param value The value to clamp
  83216. * @param min The minimum of value
  83217. * @param max The maximum of value
  83218. * @returns The clamped value.
  83219. */
  83220. ColorCurves.clamp = function (value, min, max) {
  83221. return Math.min(Math.max(value, min), max);
  83222. };
  83223. /**
  83224. * Clones the current color curve instance.
  83225. * @return The cloned curves
  83226. */
  83227. ColorCurves.prototype.clone = function () {
  83228. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  83229. };
  83230. /**
  83231. * Serializes the current color curve instance to a json representation.
  83232. * @return a JSON representation
  83233. */
  83234. ColorCurves.prototype.serialize = function () {
  83235. return BABYLON.SerializationHelper.Serialize(this);
  83236. };
  83237. /**
  83238. * Parses the color curve from a json representation.
  83239. * @param source the JSON source to parse
  83240. * @return The parsed curves
  83241. */
  83242. ColorCurves.Parse = function (source) {
  83243. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  83244. };
  83245. __decorate([
  83246. BABYLON.serialize()
  83247. ], ColorCurves.prototype, "_globalHue", void 0);
  83248. __decorate([
  83249. BABYLON.serialize()
  83250. ], ColorCurves.prototype, "_globalDensity", void 0);
  83251. __decorate([
  83252. BABYLON.serialize()
  83253. ], ColorCurves.prototype, "_globalSaturation", void 0);
  83254. __decorate([
  83255. BABYLON.serialize()
  83256. ], ColorCurves.prototype, "_globalExposure", void 0);
  83257. __decorate([
  83258. BABYLON.serialize()
  83259. ], ColorCurves.prototype, "_highlightsHue", void 0);
  83260. __decorate([
  83261. BABYLON.serialize()
  83262. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  83263. __decorate([
  83264. BABYLON.serialize()
  83265. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  83266. __decorate([
  83267. BABYLON.serialize()
  83268. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  83269. __decorate([
  83270. BABYLON.serialize()
  83271. ], ColorCurves.prototype, "_midtonesHue", void 0);
  83272. __decorate([
  83273. BABYLON.serialize()
  83274. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  83275. __decorate([
  83276. BABYLON.serialize()
  83277. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  83278. __decorate([
  83279. BABYLON.serialize()
  83280. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  83281. return ColorCurves;
  83282. }());
  83283. BABYLON.ColorCurves = ColorCurves;
  83284. })(BABYLON || (BABYLON = {}));
  83285. //# sourceMappingURL=babylon.colorCurves.js.map
  83286. var BABYLON;
  83287. (function (BABYLON) {
  83288. var RefractionPostProcess = /** @class */ (function (_super) {
  83289. __extends(RefractionPostProcess, _super);
  83290. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  83291. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  83292. _this.color = color;
  83293. _this.depth = depth;
  83294. _this.colorLevel = colorLevel;
  83295. _this._ownRefractionTexture = true;
  83296. _this.onActivateObservable.add(function (cam) {
  83297. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  83298. });
  83299. _this.onApplyObservable.add(function (effect) {
  83300. effect.setColor3("baseColor", _this.color);
  83301. effect.setFloat("depth", _this.depth);
  83302. effect.setFloat("colorLevel", _this.colorLevel);
  83303. effect.setTexture("refractionSampler", _this._refTexture);
  83304. });
  83305. return _this;
  83306. }
  83307. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  83308. /**
  83309. * Gets or sets the refraction texture
  83310. * Please note that you are responsible for disposing the texture if you set it manually
  83311. */
  83312. get: function () {
  83313. return this._refTexture;
  83314. },
  83315. set: function (value) {
  83316. if (this._refTexture && this._ownRefractionTexture) {
  83317. this._refTexture.dispose();
  83318. }
  83319. this._refTexture = value;
  83320. this._ownRefractionTexture = false;
  83321. },
  83322. enumerable: true,
  83323. configurable: true
  83324. });
  83325. // Methods
  83326. RefractionPostProcess.prototype.dispose = function (camera) {
  83327. if (this._refTexture && this._ownRefractionTexture) {
  83328. this._refTexture.dispose();
  83329. this._refTexture = null;
  83330. }
  83331. _super.prototype.dispose.call(this, camera);
  83332. };
  83333. return RefractionPostProcess;
  83334. }(BABYLON.PostProcess));
  83335. BABYLON.RefractionPostProcess = RefractionPostProcess;
  83336. })(BABYLON || (BABYLON = {}));
  83337. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  83338. var BABYLON;
  83339. (function (BABYLON) {
  83340. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  83341. __extends(BlackAndWhitePostProcess, _super);
  83342. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  83343. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  83344. _this.degree = 1;
  83345. _this.onApplyObservable.add(function (effect) {
  83346. effect.setFloat("degree", _this.degree);
  83347. });
  83348. return _this;
  83349. }
  83350. return BlackAndWhitePostProcess;
  83351. }(BABYLON.PostProcess));
  83352. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  83353. })(BABYLON || (BABYLON = {}));
  83354. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  83355. var BABYLON;
  83356. (function (BABYLON) {
  83357. /**
  83358. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  83359. * input texture to perform effects such as edge detection or sharpening
  83360. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  83361. */
  83362. var ConvolutionPostProcess = /** @class */ (function (_super) {
  83363. __extends(ConvolutionPostProcess, _super);
  83364. /**
  83365. * Creates a new instance ConvolutionPostProcess
  83366. * @param name The name of the effect.
  83367. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  83368. * @param options The required width/height ratio to downsize to before computing the render pass.
  83369. * @param camera The camera to apply the render pass to.
  83370. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83371. * @param engine The engine which the post process will be applied. (default: current engine)
  83372. * @param reusable If the post process can be reused on the same frame. (default: false)
  83373. * @param textureType Type of textures used when performing the post process. (default: 0)
  83374. */
  83375. function ConvolutionPostProcess(name,
  83376. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  83377. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  83378. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83379. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  83380. _this.kernel = kernel;
  83381. _this.onApply = function (effect) {
  83382. effect.setFloat2("screenSize", _this.width, _this.height);
  83383. effect.setArray("kernel", _this.kernel);
  83384. };
  83385. return _this;
  83386. }
  83387. // Statics
  83388. /**
  83389. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83390. */
  83391. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  83392. /**
  83393. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83394. */
  83395. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  83396. /**
  83397. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83398. */
  83399. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  83400. /**
  83401. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83402. */
  83403. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  83404. /**
  83405. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83406. */
  83407. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  83408. /**
  83409. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83410. */
  83411. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  83412. return ConvolutionPostProcess;
  83413. }(BABYLON.PostProcess));
  83414. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  83415. })(BABYLON || (BABYLON = {}));
  83416. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  83417. var BABYLON;
  83418. (function (BABYLON) {
  83419. var FilterPostProcess = /** @class */ (function (_super) {
  83420. __extends(FilterPostProcess, _super);
  83421. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  83422. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  83423. _this.kernelMatrix = kernelMatrix;
  83424. _this.onApply = function (effect) {
  83425. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  83426. };
  83427. return _this;
  83428. }
  83429. return FilterPostProcess;
  83430. }(BABYLON.PostProcess));
  83431. BABYLON.FilterPostProcess = FilterPostProcess;
  83432. })(BABYLON || (BABYLON = {}));
  83433. //# sourceMappingURL=babylon.filterPostProcess.js.map
  83434. var BABYLON;
  83435. (function (BABYLON) {
  83436. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  83437. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  83438. __extends(VolumetricLightScatteringPostProcess, _super);
  83439. /**
  83440. * @constructor
  83441. * @param {string} name - The post-process name
  83442. * @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)
  83443. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  83444. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  83445. * @param {number} samples - The post-process quality, default 100
  83446. * @param {number} samplingMode - The post-process filtering mode
  83447. * @param {BABYLON.Engine} engine - The babylon engine
  83448. * @param {boolean} reusable - If the post-process is reusable
  83449. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  83450. */
  83451. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  83452. if (samples === void 0) { samples = 100; }
  83453. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83454. 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;
  83455. _this._screenCoordinates = BABYLON.Vector2.Zero();
  83456. /**
  83457. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  83458. */
  83459. _this.customMeshPosition = BABYLON.Vector3.Zero();
  83460. /**
  83461. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  83462. */
  83463. _this.useCustomMeshPosition = false;
  83464. /**
  83465. * If the post-process should inverse the light scattering direction
  83466. */
  83467. _this.invert = true;
  83468. /**
  83469. * Array containing the excluded meshes not rendered in the internal pass
  83470. */
  83471. _this.excludedMeshes = new Array();
  83472. /**
  83473. * Controls the overall intensity of the post-process
  83474. */
  83475. _this.exposure = 0.3;
  83476. /**
  83477. * Dissipates each sample's contribution in range [0, 1]
  83478. */
  83479. _this.decay = 0.96815;
  83480. /**
  83481. * Controls the overall intensity of each sample
  83482. */
  83483. _this.weight = 0.58767;
  83484. /**
  83485. * Controls the density of each sample
  83486. */
  83487. _this.density = 0.926;
  83488. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  83489. engine = scene.getEngine();
  83490. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  83491. // Configure mesh
  83492. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  83493. // Configure
  83494. _this._createPass(scene, ratio.passRatio || ratio);
  83495. _this.onActivate = function (camera) {
  83496. if (!_this.isSupported) {
  83497. _this.dispose(camera);
  83498. }
  83499. _this.onActivate = null;
  83500. };
  83501. _this.onApplyObservable.add(function (effect) {
  83502. _this._updateMeshScreenCoordinates(scene);
  83503. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  83504. effect.setFloat("exposure", _this.exposure);
  83505. effect.setFloat("decay", _this.decay);
  83506. effect.setFloat("weight", _this.weight);
  83507. effect.setFloat("density", _this.density);
  83508. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  83509. });
  83510. return _this;
  83511. }
  83512. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  83513. get: function () {
  83514. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  83515. return false;
  83516. },
  83517. set: function (useDiffuseColor) {
  83518. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  83519. },
  83520. enumerable: true,
  83521. configurable: true
  83522. });
  83523. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  83524. return "VolumetricLightScatteringPostProcess";
  83525. };
  83526. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  83527. var mesh = subMesh.getMesh();
  83528. // Render this.mesh as default
  83529. if (mesh === this.mesh && mesh.material) {
  83530. return mesh.material.isReady(mesh);
  83531. }
  83532. var defines = [];
  83533. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83534. var material = subMesh.getMaterial();
  83535. // Alpha test
  83536. if (material) {
  83537. if (material.needAlphaTesting()) {
  83538. defines.push("#define ALPHATEST");
  83539. }
  83540. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83541. attribs.push(BABYLON.VertexBuffer.UVKind);
  83542. defines.push("#define UV1");
  83543. }
  83544. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83545. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83546. defines.push("#define UV2");
  83547. }
  83548. }
  83549. // Bones
  83550. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83551. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83552. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83553. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83554. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  83555. }
  83556. else {
  83557. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83558. }
  83559. // Instances
  83560. if (useInstances) {
  83561. defines.push("#define INSTANCES");
  83562. attribs.push("world0");
  83563. attribs.push("world1");
  83564. attribs.push("world2");
  83565. attribs.push("world3");
  83566. }
  83567. // Get correct effect
  83568. var join = defines.join("\n");
  83569. if (this._cachedDefines !== join) {
  83570. this._cachedDefines = join;
  83571. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  83572. }
  83573. return this._volumetricLightScatteringPass.isReady();
  83574. };
  83575. /**
  83576. * Sets the new light position for light scattering effect
  83577. * @param {BABYLON.Vector3} The new custom light position
  83578. */
  83579. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  83580. this.customMeshPosition = position;
  83581. };
  83582. /**
  83583. * Returns the light position for light scattering effect
  83584. * @return {BABYLON.Vector3} The custom light position
  83585. */
  83586. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  83587. return this.customMeshPosition;
  83588. };
  83589. /**
  83590. * Disposes the internal assets and detaches the post-process from the camera
  83591. */
  83592. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  83593. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  83594. if (rttIndex !== -1) {
  83595. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  83596. }
  83597. this._volumetricLightScatteringRTT.dispose();
  83598. _super.prototype.dispose.call(this, camera);
  83599. };
  83600. /**
  83601. * Returns the render target texture used by the post-process
  83602. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  83603. */
  83604. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  83605. return this._volumetricLightScatteringRTT;
  83606. };
  83607. // Private methods
  83608. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  83609. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  83610. return true;
  83611. }
  83612. return false;
  83613. };
  83614. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  83615. var _this = this;
  83616. var engine = scene.getEngine();
  83617. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  83618. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83619. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83620. this._volumetricLightScatteringRTT.renderList = null;
  83621. this._volumetricLightScatteringRTT.renderParticles = false;
  83622. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  83623. var camera = this.getCamera();
  83624. if (camera) {
  83625. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  83626. }
  83627. else {
  83628. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  83629. }
  83630. // Custom render function for submeshes
  83631. var renderSubMesh = function (subMesh) {
  83632. var mesh = subMesh.getRenderingMesh();
  83633. if (_this._meshExcluded(mesh)) {
  83634. return;
  83635. }
  83636. var material = subMesh.getMaterial();
  83637. if (!material) {
  83638. return;
  83639. }
  83640. var scene = mesh.getScene();
  83641. var engine = scene.getEngine();
  83642. // Culling
  83643. engine.setState(material.backFaceCulling);
  83644. // Managing instances
  83645. var batch = mesh._getInstancesRenderList(subMesh._id);
  83646. if (batch.mustReturn) {
  83647. return;
  83648. }
  83649. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83650. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  83651. var effect = _this._volumetricLightScatteringPass;
  83652. if (mesh === _this.mesh) {
  83653. if (subMesh.effect) {
  83654. effect = subMesh.effect;
  83655. }
  83656. else {
  83657. effect = material.getEffect();
  83658. }
  83659. }
  83660. engine.enableEffect(effect);
  83661. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  83662. if (mesh === _this.mesh) {
  83663. material.bind(mesh.getWorldMatrix(), mesh);
  83664. }
  83665. else {
  83666. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  83667. // Alpha test
  83668. if (material && material.needAlphaTesting()) {
  83669. var alphaTexture = material.getAlphaTestTexture();
  83670. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  83671. if (alphaTexture) {
  83672. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83673. }
  83674. }
  83675. // Bones
  83676. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83677. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83678. }
  83679. }
  83680. // Draw
  83681. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  83682. }
  83683. };
  83684. // Render target texture callbacks
  83685. var savedSceneClearColor;
  83686. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  83687. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  83688. savedSceneClearColor = scene.clearColor;
  83689. scene.clearColor = sceneClearColor;
  83690. });
  83691. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  83692. scene.clearColor = savedSceneClearColor;
  83693. });
  83694. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83695. var engine = scene.getEngine();
  83696. var index;
  83697. if (depthOnlySubMeshes.length) {
  83698. engine.setColorWrite(false);
  83699. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83700. renderSubMesh(depthOnlySubMeshes.data[index]);
  83701. }
  83702. engine.setColorWrite(true);
  83703. }
  83704. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83705. renderSubMesh(opaqueSubMeshes.data[index]);
  83706. }
  83707. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83708. renderSubMesh(alphaTestSubMeshes.data[index]);
  83709. }
  83710. if (transparentSubMeshes.length) {
  83711. // Sort sub meshes
  83712. for (index = 0; index < transparentSubMeshes.length; index++) {
  83713. var submesh = transparentSubMeshes.data[index];
  83714. var boundingInfo = submesh.getBoundingInfo();
  83715. if (boundingInfo && scene.activeCamera) {
  83716. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  83717. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  83718. }
  83719. }
  83720. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  83721. sortedArray.sort(function (a, b) {
  83722. // Alpha index first
  83723. if (a._alphaIndex > b._alphaIndex) {
  83724. return 1;
  83725. }
  83726. if (a._alphaIndex < b._alphaIndex) {
  83727. return -1;
  83728. }
  83729. // Then distance to camera
  83730. if (a._distanceToCamera < b._distanceToCamera) {
  83731. return 1;
  83732. }
  83733. if (a._distanceToCamera > b._distanceToCamera) {
  83734. return -1;
  83735. }
  83736. return 0;
  83737. });
  83738. // Render sub meshes
  83739. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  83740. for (index = 0; index < sortedArray.length; index++) {
  83741. renderSubMesh(sortedArray[index]);
  83742. }
  83743. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  83744. }
  83745. };
  83746. };
  83747. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  83748. var transform = scene.getTransformMatrix();
  83749. var meshPosition;
  83750. if (this.useCustomMeshPosition) {
  83751. meshPosition = this.customMeshPosition;
  83752. }
  83753. else if (this.attachedNode) {
  83754. meshPosition = this.attachedNode.position;
  83755. }
  83756. else {
  83757. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  83758. }
  83759. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  83760. this._screenCoordinates.x = pos.x / this._viewPort.width;
  83761. this._screenCoordinates.y = pos.y / this._viewPort.height;
  83762. if (this.invert)
  83763. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  83764. };
  83765. // Static methods
  83766. /**
  83767. * Creates a default mesh for the Volumeric Light Scattering post-process
  83768. * @param {string} The mesh name
  83769. * @param {BABYLON.Scene} The scene where to create the mesh
  83770. * @return {BABYLON.Mesh} the default mesh
  83771. */
  83772. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  83773. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  83774. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  83775. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  83776. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  83777. mesh.material = material;
  83778. return mesh;
  83779. };
  83780. __decorate([
  83781. BABYLON.serializeAsVector3()
  83782. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  83783. __decorate([
  83784. BABYLON.serialize()
  83785. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  83786. __decorate([
  83787. BABYLON.serialize()
  83788. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  83789. __decorate([
  83790. BABYLON.serializeAsMeshReference()
  83791. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  83792. __decorate([
  83793. BABYLON.serialize()
  83794. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  83795. __decorate([
  83796. BABYLON.serialize()
  83797. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  83798. __decorate([
  83799. BABYLON.serialize()
  83800. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  83801. __decorate([
  83802. BABYLON.serialize()
  83803. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  83804. __decorate([
  83805. BABYLON.serialize()
  83806. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  83807. return VolumetricLightScatteringPostProcess;
  83808. }(BABYLON.PostProcess));
  83809. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  83810. })(BABYLON || (BABYLON = {}));
  83811. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  83812. //
  83813. // This post-process allows the modification of rendered colors by using
  83814. // a 'look-up table' (LUT). This effect is also called Color Grading.
  83815. //
  83816. // The object needs to be provided an url to a texture containing the color
  83817. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  83818. // Use an image editing software to tweak the LUT to match your needs.
  83819. //
  83820. // For an example of a color LUT, see here:
  83821. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  83822. // For explanations on color grading, see here:
  83823. // http://udn.epicgames.com/Three/ColorGrading.html
  83824. //
  83825. var BABYLON;
  83826. (function (BABYLON) {
  83827. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  83828. __extends(ColorCorrectionPostProcess, _super);
  83829. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  83830. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  83831. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  83832. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  83833. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83834. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83835. _this.onApply = function (effect) {
  83836. effect.setTexture("colorTable", _this._colorTableTexture);
  83837. };
  83838. return _this;
  83839. }
  83840. return ColorCorrectionPostProcess;
  83841. }(BABYLON.PostProcess));
  83842. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  83843. })(BABYLON || (BABYLON = {}));
  83844. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  83845. var BABYLON;
  83846. (function (BABYLON) {
  83847. /** Defines operator used for tonemapping */
  83848. var TonemappingOperator;
  83849. (function (TonemappingOperator) {
  83850. /** Hable */
  83851. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  83852. /** Reinhard */
  83853. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  83854. /** HejiDawson */
  83855. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  83856. /** Photographic */
  83857. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  83858. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  83859. ;
  83860. /**
  83861. * Defines a post process to apply tone mapping
  83862. */
  83863. var TonemapPostProcess = /** @class */ (function (_super) {
  83864. __extends(TonemapPostProcess, _super);
  83865. /**
  83866. * Creates a new TonemapPostProcess
  83867. * @param name defines the name of the postprocess
  83868. * @param _operator defines the operator to use
  83869. * @param exposureAdjustment defines the required exposure adjustement
  83870. * @param camera defines the camera to use (can be null)
  83871. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  83872. * @param engine defines the hosting engine (can be ignore if camera is set)
  83873. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  83874. */
  83875. function TonemapPostProcess(name, _operator,
  83876. /** Defines the required exposure adjustement */
  83877. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  83878. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83879. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83880. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  83881. _this._operator = _operator;
  83882. _this.exposureAdjustment = exposureAdjustment;
  83883. var defines = "#define ";
  83884. if (_this._operator === TonemappingOperator.Hable)
  83885. defines += "HABLE_TONEMAPPING";
  83886. else if (_this._operator === TonemappingOperator.Reinhard)
  83887. defines += "REINHARD_TONEMAPPING";
  83888. else if (_this._operator === TonemappingOperator.HejiDawson)
  83889. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  83890. else if (_this._operator === TonemappingOperator.Photographic)
  83891. defines += "PHOTOGRAPHIC_TONEMAPPING";
  83892. //sadly a second call to create the effect.
  83893. _this.updateEffect(defines);
  83894. _this.onApply = function (effect) {
  83895. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  83896. };
  83897. return _this;
  83898. }
  83899. return TonemapPostProcess;
  83900. }(BABYLON.PostProcess));
  83901. BABYLON.TonemapPostProcess = TonemapPostProcess;
  83902. })(BABYLON || (BABYLON = {}));
  83903. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  83904. var BABYLON;
  83905. (function (BABYLON) {
  83906. var DisplayPassPostProcess = /** @class */ (function (_super) {
  83907. __extends(DisplayPassPostProcess, _super);
  83908. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  83909. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  83910. }
  83911. return DisplayPassPostProcess;
  83912. }(BABYLON.PostProcess));
  83913. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  83914. })(BABYLON || (BABYLON = {}));
  83915. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  83916. var BABYLON;
  83917. (function (BABYLON) {
  83918. var HighlightsPostProcess = /** @class */ (function (_super) {
  83919. __extends(HighlightsPostProcess, _super);
  83920. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  83921. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83922. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  83923. }
  83924. return HighlightsPostProcess;
  83925. }(BABYLON.PostProcess));
  83926. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  83927. })(BABYLON || (BABYLON = {}));
  83928. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  83929. var BABYLON;
  83930. (function (BABYLON) {
  83931. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  83932. __extends(ImageProcessingPostProcess, _super);
  83933. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  83934. if (camera === void 0) { camera = null; }
  83935. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83936. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  83937. _this._fromLinearSpace = true;
  83938. /**
  83939. * Defines cache preventing GC.
  83940. */
  83941. _this._defines = {
  83942. IMAGEPROCESSING: false,
  83943. VIGNETTE: false,
  83944. VIGNETTEBLENDMODEMULTIPLY: false,
  83945. VIGNETTEBLENDMODEOPAQUE: false,
  83946. TONEMAPPING: false,
  83947. TONEMAPPING_ACES: false,
  83948. CONTRAST: false,
  83949. COLORCURVES: false,
  83950. COLORGRADING: false,
  83951. COLORGRADING3D: false,
  83952. FROMLINEARSPACE: false,
  83953. SAMPLER3DGREENDEPTH: false,
  83954. SAMPLER3DBGRMAP: false,
  83955. IMAGEPROCESSINGPOSTPROCESS: false,
  83956. EXPOSURE: false,
  83957. };
  83958. // Setup the configuration as forced by the constructor. This would then not force the
  83959. // scene materials output in linear space and let untouched the default forward pass.
  83960. if (imageProcessingConfiguration) {
  83961. imageProcessingConfiguration.applyByPostProcess = true;
  83962. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  83963. // This will cause the shader to be compiled
  83964. _this.fromLinearSpace = false;
  83965. }
  83966. // Setup the default processing configuration to the scene.
  83967. else {
  83968. _this._attachImageProcessingConfiguration(null, true);
  83969. _this.imageProcessingConfiguration.applyByPostProcess = true;
  83970. }
  83971. _this.onApply = function (effect) {
  83972. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  83973. };
  83974. return _this;
  83975. }
  83976. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  83977. /**
  83978. * Gets the image processing configuration used either in this material.
  83979. */
  83980. get: function () {
  83981. return this._imageProcessingConfiguration;
  83982. },
  83983. /**
  83984. * Sets the Default image processing configuration used either in the this material.
  83985. *
  83986. * If sets to null, the scene one is in use.
  83987. */
  83988. set: function (value) {
  83989. this._attachImageProcessingConfiguration(value);
  83990. },
  83991. enumerable: true,
  83992. configurable: true
  83993. });
  83994. /**
  83995. * Attaches a new image processing configuration to the PBR Material.
  83996. * @param configuration
  83997. */
  83998. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  83999. var _this = this;
  84000. if (doNotBuild === void 0) { doNotBuild = false; }
  84001. if (configuration === this._imageProcessingConfiguration) {
  84002. return;
  84003. }
  84004. // Detaches observer.
  84005. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  84006. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  84007. }
  84008. // Pick the scene configuration if needed.
  84009. if (!configuration) {
  84010. var scene = null;
  84011. var engine = this.getEngine();
  84012. var camera = this.getCamera();
  84013. if (camera) {
  84014. scene = camera.getScene();
  84015. }
  84016. else if (engine && engine.scenes) {
  84017. var scenes = engine.scenes;
  84018. scene = scenes[scenes.length - 1];
  84019. }
  84020. else {
  84021. scene = BABYLON.Engine.LastCreatedScene;
  84022. }
  84023. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  84024. }
  84025. else {
  84026. this._imageProcessingConfiguration = configuration;
  84027. }
  84028. // Attaches observer.
  84029. if (this._imageProcessingConfiguration) {
  84030. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  84031. _this._updateParameters();
  84032. });
  84033. }
  84034. // Ensure the effect will be rebuilt.
  84035. if (!doNotBuild) {
  84036. this._updateParameters();
  84037. }
  84038. };
  84039. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  84040. /**
  84041. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  84042. */
  84043. get: function () {
  84044. return this.imageProcessingConfiguration.colorCurves;
  84045. },
  84046. /**
  84047. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  84048. */
  84049. set: function (value) {
  84050. this.imageProcessingConfiguration.colorCurves = value;
  84051. },
  84052. enumerable: true,
  84053. configurable: true
  84054. });
  84055. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  84056. /**
  84057. * Gets wether the color curves effect is enabled.
  84058. */
  84059. get: function () {
  84060. return this.imageProcessingConfiguration.colorCurvesEnabled;
  84061. },
  84062. /**
  84063. * Sets wether the color curves effect is enabled.
  84064. */
  84065. set: function (value) {
  84066. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  84067. },
  84068. enumerable: true,
  84069. configurable: true
  84070. });
  84071. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  84072. /**
  84073. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  84074. */
  84075. get: function () {
  84076. return this.imageProcessingConfiguration.colorGradingTexture;
  84077. },
  84078. /**
  84079. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  84080. */
  84081. set: function (value) {
  84082. this.imageProcessingConfiguration.colorGradingTexture = value;
  84083. },
  84084. enumerable: true,
  84085. configurable: true
  84086. });
  84087. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  84088. /**
  84089. * Gets wether the color grading effect is enabled.
  84090. */
  84091. get: function () {
  84092. return this.imageProcessingConfiguration.colorGradingEnabled;
  84093. },
  84094. /**
  84095. * Gets wether the color grading effect is enabled.
  84096. */
  84097. set: function (value) {
  84098. this.imageProcessingConfiguration.colorGradingEnabled = value;
  84099. },
  84100. enumerable: true,
  84101. configurable: true
  84102. });
  84103. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  84104. /**
  84105. * Gets exposure used in the effect.
  84106. */
  84107. get: function () {
  84108. return this.imageProcessingConfiguration.exposure;
  84109. },
  84110. /**
  84111. * Sets exposure used in the effect.
  84112. */
  84113. set: function (value) {
  84114. this.imageProcessingConfiguration.exposure = value;
  84115. },
  84116. enumerable: true,
  84117. configurable: true
  84118. });
  84119. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  84120. /**
  84121. * Gets wether tonemapping is enabled or not.
  84122. */
  84123. get: function () {
  84124. return this._imageProcessingConfiguration.toneMappingEnabled;
  84125. },
  84126. /**
  84127. * Sets wether tonemapping is enabled or not
  84128. */
  84129. set: function (value) {
  84130. this._imageProcessingConfiguration.toneMappingEnabled = value;
  84131. },
  84132. enumerable: true,
  84133. configurable: true
  84134. });
  84135. ;
  84136. ;
  84137. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  84138. /**
  84139. * Gets contrast used in the effect.
  84140. */
  84141. get: function () {
  84142. return this.imageProcessingConfiguration.contrast;
  84143. },
  84144. /**
  84145. * Sets contrast used in the effect.
  84146. */
  84147. set: function (value) {
  84148. this.imageProcessingConfiguration.contrast = value;
  84149. },
  84150. enumerable: true,
  84151. configurable: true
  84152. });
  84153. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  84154. /**
  84155. * Gets Vignette stretch size.
  84156. */
  84157. get: function () {
  84158. return this.imageProcessingConfiguration.vignetteStretch;
  84159. },
  84160. /**
  84161. * Sets Vignette stretch size.
  84162. */
  84163. set: function (value) {
  84164. this.imageProcessingConfiguration.vignetteStretch = value;
  84165. },
  84166. enumerable: true,
  84167. configurable: true
  84168. });
  84169. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  84170. /**
  84171. * Gets Vignette centre X Offset.
  84172. */
  84173. get: function () {
  84174. return this.imageProcessingConfiguration.vignetteCentreX;
  84175. },
  84176. /**
  84177. * Sets Vignette centre X Offset.
  84178. */
  84179. set: function (value) {
  84180. this.imageProcessingConfiguration.vignetteCentreX = value;
  84181. },
  84182. enumerable: true,
  84183. configurable: true
  84184. });
  84185. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  84186. /**
  84187. * Gets Vignette centre Y Offset.
  84188. */
  84189. get: function () {
  84190. return this.imageProcessingConfiguration.vignetteCentreY;
  84191. },
  84192. /**
  84193. * Sets Vignette centre Y Offset.
  84194. */
  84195. set: function (value) {
  84196. this.imageProcessingConfiguration.vignetteCentreY = value;
  84197. },
  84198. enumerable: true,
  84199. configurable: true
  84200. });
  84201. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  84202. /**
  84203. * Gets Vignette weight or intensity of the vignette effect.
  84204. */
  84205. get: function () {
  84206. return this.imageProcessingConfiguration.vignetteWeight;
  84207. },
  84208. /**
  84209. * Sets Vignette weight or intensity of the vignette effect.
  84210. */
  84211. set: function (value) {
  84212. this.imageProcessingConfiguration.vignetteWeight = value;
  84213. },
  84214. enumerable: true,
  84215. configurable: true
  84216. });
  84217. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  84218. /**
  84219. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  84220. * if vignetteEnabled is set to true.
  84221. */
  84222. get: function () {
  84223. return this.imageProcessingConfiguration.vignetteColor;
  84224. },
  84225. /**
  84226. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  84227. * if vignetteEnabled is set to true.
  84228. */
  84229. set: function (value) {
  84230. this.imageProcessingConfiguration.vignetteColor = value;
  84231. },
  84232. enumerable: true,
  84233. configurable: true
  84234. });
  84235. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  84236. /**
  84237. * Gets Camera field of view used by the Vignette effect.
  84238. */
  84239. get: function () {
  84240. return this.imageProcessingConfiguration.vignetteCameraFov;
  84241. },
  84242. /**
  84243. * Sets Camera field of view used by the Vignette effect.
  84244. */
  84245. set: function (value) {
  84246. this.imageProcessingConfiguration.vignetteCameraFov = value;
  84247. },
  84248. enumerable: true,
  84249. configurable: true
  84250. });
  84251. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  84252. /**
  84253. * Gets the vignette blend mode allowing different kind of effect.
  84254. */
  84255. get: function () {
  84256. return this.imageProcessingConfiguration.vignetteBlendMode;
  84257. },
  84258. /**
  84259. * Sets the vignette blend mode allowing different kind of effect.
  84260. */
  84261. set: function (value) {
  84262. this.imageProcessingConfiguration.vignetteBlendMode = value;
  84263. },
  84264. enumerable: true,
  84265. configurable: true
  84266. });
  84267. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  84268. /**
  84269. * Gets wether the vignette effect is enabled.
  84270. */
  84271. get: function () {
  84272. return this.imageProcessingConfiguration.vignetteEnabled;
  84273. },
  84274. /**
  84275. * Sets wether the vignette effect is enabled.
  84276. */
  84277. set: function (value) {
  84278. this.imageProcessingConfiguration.vignetteEnabled = value;
  84279. },
  84280. enumerable: true,
  84281. configurable: true
  84282. });
  84283. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  84284. /**
  84285. * Gets wether the input of the processing is in Gamma or Linear Space.
  84286. */
  84287. get: function () {
  84288. return this._fromLinearSpace;
  84289. },
  84290. /**
  84291. * Sets wether the input of the processing is in Gamma or Linear Space.
  84292. */
  84293. set: function (value) {
  84294. if (this._fromLinearSpace === value) {
  84295. return;
  84296. }
  84297. this._fromLinearSpace = value;
  84298. this._updateParameters();
  84299. },
  84300. enumerable: true,
  84301. configurable: true
  84302. });
  84303. ImageProcessingPostProcess.prototype.getClassName = function () {
  84304. return "ImageProcessingPostProcess";
  84305. };
  84306. ImageProcessingPostProcess.prototype._updateParameters = function () {
  84307. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  84308. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  84309. var defines = "";
  84310. for (var define in this._defines) {
  84311. if (this._defines[define]) {
  84312. defines += "#define " + define + ";\r\n";
  84313. }
  84314. }
  84315. var samplers = ["textureSampler"];
  84316. var uniforms = ["scale"];
  84317. if (BABYLON.ImageProcessingConfiguration) {
  84318. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  84319. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  84320. }
  84321. this.updateEffect(defines, uniforms, samplers);
  84322. };
  84323. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  84324. _super.prototype.dispose.call(this, camera);
  84325. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  84326. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  84327. }
  84328. if (this._imageProcessingConfiguration) {
  84329. this.imageProcessingConfiguration.applyByPostProcess = false;
  84330. }
  84331. };
  84332. __decorate([
  84333. BABYLON.serialize()
  84334. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  84335. return ImageProcessingPostProcess;
  84336. }(BABYLON.PostProcess));
  84337. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  84338. })(BABYLON || (BABYLON = {}));
  84339. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  84340. var BABYLON;
  84341. (function (BABYLON) {
  84342. /**
  84343. * Class used to store bone information
  84344. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  84345. */
  84346. var Bone = /** @class */ (function (_super) {
  84347. __extends(Bone, _super);
  84348. /**
  84349. * Create a new bone
  84350. * @param name defines the bone name
  84351. * @param skeleton defines the parent skeleton
  84352. * @param parentBone defines the parent (can be null if the bone is the root)
  84353. * @param localMatrix defines the local matrix
  84354. * @param restPose defines the rest pose matrix
  84355. * @param baseMatrix defines the base matrix
  84356. * @param index defines index of the bone in the hiearchy
  84357. */
  84358. function Bone(
  84359. /**
  84360. * defines the bone name
  84361. */
  84362. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  84363. if (parentBone === void 0) { parentBone = null; }
  84364. if (localMatrix === void 0) { localMatrix = null; }
  84365. if (restPose === void 0) { restPose = null; }
  84366. if (baseMatrix === void 0) { baseMatrix = null; }
  84367. if (index === void 0) { index = null; }
  84368. var _this = _super.call(this, name, skeleton.getScene()) || this;
  84369. _this.name = name;
  84370. /**
  84371. * Gets the list of child bones
  84372. */
  84373. _this.children = new Array();
  84374. /** Gets the animations associated with this bone */
  84375. _this.animations = new Array();
  84376. /**
  84377. * @hidden Internal only
  84378. * Set this value to map this bone to a different index in the transform matrices
  84379. * Set this value to -1 to exclude the bone from the transform matrices
  84380. */
  84381. _this._index = null;
  84382. _this._absoluteTransform = new BABYLON.Matrix();
  84383. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  84384. _this._scalingDeterminant = 1;
  84385. _this._worldTransform = new BABYLON.Matrix();
  84386. _this._needToDecompose = true;
  84387. _this._needToCompose = false;
  84388. _this._skeleton = skeleton;
  84389. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  84390. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  84391. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  84392. _this._index = index;
  84393. skeleton.bones.push(_this);
  84394. _this.setParent(parentBone, false);
  84395. if (baseMatrix || localMatrix) {
  84396. _this._updateDifferenceMatrix();
  84397. }
  84398. return _this;
  84399. }
  84400. Object.defineProperty(Bone.prototype, "_matrix", {
  84401. /** @hidden */
  84402. get: function () {
  84403. this._compose();
  84404. return this._localMatrix;
  84405. },
  84406. /** @hidden */
  84407. set: function (value) {
  84408. this._localMatrix.copyFrom(value);
  84409. this._needToDecompose = true;
  84410. },
  84411. enumerable: true,
  84412. configurable: true
  84413. });
  84414. // Members
  84415. /**
  84416. * Gets the parent skeleton
  84417. * @returns a skeleton
  84418. */
  84419. Bone.prototype.getSkeleton = function () {
  84420. return this._skeleton;
  84421. };
  84422. /**
  84423. * Gets parent bone
  84424. * @returns a bone or null if the bone is the root of the bone hierarchy
  84425. */
  84426. Bone.prototype.getParent = function () {
  84427. return this._parent;
  84428. };
  84429. /**
  84430. * Sets the parent bone
  84431. * @param parent defines the parent (can be null if the bone is the root)
  84432. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  84433. */
  84434. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  84435. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  84436. if (this._parent === parent) {
  84437. return;
  84438. }
  84439. if (this._parent) {
  84440. var index = this._parent.children.indexOf(this);
  84441. if (index !== -1) {
  84442. this._parent.children.splice(index, 1);
  84443. }
  84444. }
  84445. this._parent = parent;
  84446. if (this._parent) {
  84447. this._parent.children.push(this);
  84448. }
  84449. if (updateDifferenceMatrix) {
  84450. this._updateDifferenceMatrix();
  84451. }
  84452. this.markAsDirty();
  84453. };
  84454. /**
  84455. * Gets the local matrix
  84456. * @returns a matrix
  84457. */
  84458. Bone.prototype.getLocalMatrix = function () {
  84459. this._compose();
  84460. return this._localMatrix;
  84461. };
  84462. /**
  84463. * Gets the base matrix (initial matrix which remains unchanged)
  84464. * @returns a matrix
  84465. */
  84466. Bone.prototype.getBaseMatrix = function () {
  84467. return this._baseMatrix;
  84468. };
  84469. /**
  84470. * Gets the rest pose matrix
  84471. * @returns a matrix
  84472. */
  84473. Bone.prototype.getRestPose = function () {
  84474. return this._restPose;
  84475. };
  84476. /**
  84477. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  84478. */
  84479. Bone.prototype.getWorldMatrix = function () {
  84480. return this._worldTransform;
  84481. };
  84482. /**
  84483. * Sets the local matrix to rest pose matrix
  84484. */
  84485. Bone.prototype.returnToRest = function () {
  84486. this.updateMatrix(this._restPose.clone());
  84487. };
  84488. /**
  84489. * Gets the inverse of the absolute transform matrix.
  84490. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  84491. * @returns a matrix
  84492. */
  84493. Bone.prototype.getInvertedAbsoluteTransform = function () {
  84494. return this._invertedAbsoluteTransform;
  84495. };
  84496. /**
  84497. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  84498. * @returns a matrix
  84499. */
  84500. Bone.prototype.getAbsoluteTransform = function () {
  84501. return this._absoluteTransform;
  84502. };
  84503. Object.defineProperty(Bone.prototype, "position", {
  84504. // Properties (matches AbstractMesh properties)
  84505. /** Gets or sets current position (in local space) */
  84506. get: function () {
  84507. this._decompose();
  84508. return this._localPosition;
  84509. },
  84510. set: function (newPosition) {
  84511. this._decompose();
  84512. this._localPosition.copyFrom(newPosition);
  84513. this._markAsDirtyAndCompose();
  84514. },
  84515. enumerable: true,
  84516. configurable: true
  84517. });
  84518. Object.defineProperty(Bone.prototype, "rotation", {
  84519. /** Gets or sets current rotation (in local space) */
  84520. get: function () {
  84521. return this.getRotation();
  84522. },
  84523. set: function (newRotation) {
  84524. this.setRotation(newRotation);
  84525. },
  84526. enumerable: true,
  84527. configurable: true
  84528. });
  84529. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  84530. /** Gets or sets current rotation quaternion (in local space) */
  84531. get: function () {
  84532. this._decompose();
  84533. return this._localRotation;
  84534. },
  84535. set: function (newRotation) {
  84536. this.setRotationQuaternion(newRotation);
  84537. },
  84538. enumerable: true,
  84539. configurable: true
  84540. });
  84541. Object.defineProperty(Bone.prototype, "scaling", {
  84542. /** Gets or sets current scaling (in local space) */
  84543. get: function () {
  84544. return this.getScale();
  84545. },
  84546. set: function (newScaling) {
  84547. this.setScale(newScaling);
  84548. },
  84549. enumerable: true,
  84550. configurable: true
  84551. });
  84552. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  84553. /**
  84554. * Gets the animation properties override
  84555. */
  84556. get: function () {
  84557. return this._skeleton.animationPropertiesOverride;
  84558. },
  84559. enumerable: true,
  84560. configurable: true
  84561. });
  84562. // Methods
  84563. Bone.prototype._decompose = function () {
  84564. if (!this._needToDecompose) {
  84565. return;
  84566. }
  84567. this._needToDecompose = false;
  84568. if (!this._localScaling) {
  84569. this._localScaling = BABYLON.Vector3.Zero();
  84570. this._localRotation = BABYLON.Quaternion.Zero();
  84571. this._localPosition = BABYLON.Vector3.Zero();
  84572. }
  84573. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  84574. };
  84575. Bone.prototype._compose = function () {
  84576. if (!this._needToCompose) {
  84577. return;
  84578. }
  84579. this._needToCompose = false;
  84580. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  84581. };
  84582. /**
  84583. * Update the base and local matrices
  84584. * @param matrix defines the new base or local matrix
  84585. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  84586. * @param updateLocalMatrix defines if the local matrix should be updated
  84587. */
  84588. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  84589. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  84590. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  84591. this._baseMatrix.copyFrom(matrix);
  84592. if (updateDifferenceMatrix) {
  84593. this._updateDifferenceMatrix();
  84594. }
  84595. if (updateLocalMatrix) {
  84596. this._localMatrix.copyFrom(matrix);
  84597. this._markAsDirtyAndDecompose();
  84598. }
  84599. else {
  84600. this.markAsDirty();
  84601. }
  84602. };
  84603. /** @hidden */
  84604. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  84605. if (updateChildren === void 0) { updateChildren = true; }
  84606. if (!rootMatrix) {
  84607. rootMatrix = this._baseMatrix;
  84608. }
  84609. if (this._parent) {
  84610. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  84611. }
  84612. else {
  84613. this._absoluteTransform.copyFrom(rootMatrix);
  84614. }
  84615. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  84616. if (updateChildren) {
  84617. for (var index = 0; index < this.children.length; index++) {
  84618. this.children[index]._updateDifferenceMatrix();
  84619. }
  84620. }
  84621. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  84622. };
  84623. /**
  84624. * Flag the bone as dirty (Forcing it to update everything)
  84625. */
  84626. Bone.prototype.markAsDirty = function () {
  84627. this._currentRenderId++;
  84628. this._childRenderId++;
  84629. this._skeleton._markAsDirty();
  84630. };
  84631. Bone.prototype._markAsDirtyAndCompose = function () {
  84632. this.markAsDirty();
  84633. this._needToCompose = true;
  84634. };
  84635. Bone.prototype._markAsDirtyAndDecompose = function () {
  84636. this.markAsDirty();
  84637. this._needToDecompose = true;
  84638. };
  84639. /**
  84640. * Copy an animation range from another bone
  84641. * @param source defines the source bone
  84642. * @param rangeName defines the range name to copy
  84643. * @param frameOffset defines the frame offset
  84644. * @param rescaleAsRequired defines if rescaling must be applied if required
  84645. * @param skelDimensionsRatio defines the scaling ratio
  84646. * @returns true if operation was successful
  84647. */
  84648. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  84649. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  84650. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  84651. // all animation may be coming from a library skeleton, so may need to create animation
  84652. if (this.animations.length === 0) {
  84653. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  84654. this.animations[0].setKeys([]);
  84655. }
  84656. // get animation info / verify there is such a range from the source bone
  84657. var sourceRange = source.animations[0].getRange(rangeName);
  84658. if (!sourceRange) {
  84659. return false;
  84660. }
  84661. var from = sourceRange.from;
  84662. var to = sourceRange.to;
  84663. var sourceKeys = source.animations[0].getKeys();
  84664. // rescaling prep
  84665. var sourceBoneLength = source.length;
  84666. var sourceParent = source.getParent();
  84667. var parent = this.getParent();
  84668. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  84669. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  84670. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  84671. var destKeys = this.animations[0].getKeys();
  84672. // loop vars declaration
  84673. var orig;
  84674. var origTranslation;
  84675. var mat;
  84676. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  84677. orig = sourceKeys[key];
  84678. if (orig.frame >= from && orig.frame <= to) {
  84679. if (rescaleAsRequired) {
  84680. mat = orig.value.clone();
  84681. // scale based on parent ratio, when bone has parent
  84682. if (parentScalingReqd) {
  84683. origTranslation = mat.getTranslation();
  84684. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  84685. // scale based on skeleton dimension ratio when root bone, and value is passed
  84686. }
  84687. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  84688. origTranslation = mat.getTranslation();
  84689. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  84690. // use original when root bone, and no data for skelDimensionsRatio
  84691. }
  84692. else {
  84693. mat = orig.value;
  84694. }
  84695. }
  84696. else {
  84697. mat = orig.value;
  84698. }
  84699. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  84700. }
  84701. }
  84702. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  84703. return true;
  84704. };
  84705. /**
  84706. * Translate the bone in local or world space
  84707. * @param vec The amount to translate the bone
  84708. * @param space The space that the translation is in
  84709. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84710. */
  84711. Bone.prototype.translate = function (vec, space, mesh) {
  84712. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84713. var lm = this.getLocalMatrix();
  84714. if (space == BABYLON.Space.LOCAL) {
  84715. lm.m[12] += vec.x;
  84716. lm.m[13] += vec.y;
  84717. lm.m[14] += vec.z;
  84718. }
  84719. else {
  84720. var wm = null;
  84721. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84722. if (mesh) {
  84723. wm = mesh.getWorldMatrix();
  84724. }
  84725. this._skeleton.computeAbsoluteTransforms();
  84726. var tmat = Bone._tmpMats[0];
  84727. var tvec = Bone._tmpVecs[0];
  84728. if (this._parent) {
  84729. if (mesh && wm) {
  84730. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84731. tmat.multiplyToRef(wm, tmat);
  84732. }
  84733. else {
  84734. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84735. }
  84736. }
  84737. tmat.m[12] = 0;
  84738. tmat.m[13] = 0;
  84739. tmat.m[14] = 0;
  84740. tmat.invert();
  84741. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  84742. lm.m[12] += tvec.x;
  84743. lm.m[13] += tvec.y;
  84744. lm.m[14] += tvec.z;
  84745. }
  84746. this._markAsDirtyAndDecompose();
  84747. };
  84748. /**
  84749. * Set the postion of the bone in local or world space
  84750. * @param position The position to set the bone
  84751. * @param space The space that the position is in
  84752. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84753. */
  84754. Bone.prototype.setPosition = function (position, space, mesh) {
  84755. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84756. var lm = this.getLocalMatrix();
  84757. if (space == BABYLON.Space.LOCAL) {
  84758. lm.m[12] = position.x;
  84759. lm.m[13] = position.y;
  84760. lm.m[14] = position.z;
  84761. }
  84762. else {
  84763. var wm = null;
  84764. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84765. if (mesh) {
  84766. wm = mesh.getWorldMatrix();
  84767. }
  84768. this._skeleton.computeAbsoluteTransforms();
  84769. var tmat = Bone._tmpMats[0];
  84770. var vec = Bone._tmpVecs[0];
  84771. if (this._parent) {
  84772. if (mesh && wm) {
  84773. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84774. tmat.multiplyToRef(wm, tmat);
  84775. }
  84776. else {
  84777. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84778. }
  84779. }
  84780. tmat.invert();
  84781. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  84782. lm.m[12] = vec.x;
  84783. lm.m[13] = vec.y;
  84784. lm.m[14] = vec.z;
  84785. }
  84786. this._markAsDirtyAndDecompose();
  84787. };
  84788. /**
  84789. * Set the absolute position of the bone (world space)
  84790. * @param position The position to set the bone
  84791. * @param mesh The mesh that this bone is attached to
  84792. */
  84793. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  84794. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  84795. };
  84796. /**
  84797. * Scale the bone on the x, y and z axes (in local space)
  84798. * @param x The amount to scale the bone on the x axis
  84799. * @param y The amount to scale the bone on the y axis
  84800. * @param z The amount to scale the bone on the z axis
  84801. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  84802. */
  84803. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  84804. if (scaleChildren === void 0) { scaleChildren = false; }
  84805. var locMat = this.getLocalMatrix();
  84806. // Apply new scaling on top of current local matrix
  84807. var scaleMat = Bone._tmpMats[0];
  84808. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  84809. scaleMat.multiplyToRef(locMat, locMat);
  84810. // Invert scaling matrix and apply the inverse to all children
  84811. scaleMat.invert();
  84812. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  84813. var child = _a[_i];
  84814. var cm = child.getLocalMatrix();
  84815. cm.multiplyToRef(scaleMat, cm);
  84816. cm.m[12] *= x;
  84817. cm.m[13] *= y;
  84818. cm.m[14] *= z;
  84819. child._markAsDirtyAndDecompose();
  84820. }
  84821. this._markAsDirtyAndDecompose();
  84822. if (scaleChildren) {
  84823. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  84824. var child = _c[_b];
  84825. child.scale(x, y, z, scaleChildren);
  84826. }
  84827. }
  84828. };
  84829. /**
  84830. * Set the bone scaling in local space
  84831. * @param scale defines the scaling vector
  84832. */
  84833. Bone.prototype.setScale = function (scale) {
  84834. this._decompose();
  84835. this._localScaling.copyFrom(scale);
  84836. this._markAsDirtyAndCompose();
  84837. };
  84838. /**
  84839. * Gets the current scaling in local space
  84840. * @returns the current scaling vector
  84841. */
  84842. Bone.prototype.getScale = function () {
  84843. this._decompose();
  84844. return this._localScaling;
  84845. };
  84846. /**
  84847. * Gets the current scaling in local space and stores it in a target vector
  84848. * @param result defines the target vector
  84849. */
  84850. Bone.prototype.getScaleToRef = function (result) {
  84851. this._decompose();
  84852. result.copyFrom(this._localScaling);
  84853. };
  84854. /**
  84855. * Set the yaw, pitch, and roll of the bone in local or world space
  84856. * @param yaw The rotation of the bone on the y axis
  84857. * @param pitch The rotation of the bone on the x axis
  84858. * @param roll The rotation of the bone on the z axis
  84859. * @param space The space that the axes of rotation are in
  84860. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84861. */
  84862. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  84863. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84864. if (space === BABYLON.Space.LOCAL) {
  84865. var quat = Bone._tmpQuat;
  84866. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  84867. this.setRotationQuaternion(quat, space, mesh);
  84868. return;
  84869. }
  84870. var rotMatInv = Bone._tmpMats[0];
  84871. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84872. return;
  84873. }
  84874. var rotMat = Bone._tmpMats[1];
  84875. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  84876. rotMatInv.multiplyToRef(rotMat, rotMat);
  84877. this._rotateWithMatrix(rotMat, space, mesh);
  84878. };
  84879. /**
  84880. * Add a rotation to the bone on an axis in local or world space
  84881. * @param axis The axis to rotate the bone on
  84882. * @param amount The amount to rotate the bone
  84883. * @param space The space that the axis is in
  84884. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84885. */
  84886. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  84887. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84888. var rmat = Bone._tmpMats[0];
  84889. rmat.m[12] = 0;
  84890. rmat.m[13] = 0;
  84891. rmat.m[14] = 0;
  84892. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  84893. this._rotateWithMatrix(rmat, space, mesh);
  84894. };
  84895. /**
  84896. * Set the rotation of the bone to a particular axis angle in local or world space
  84897. * @param axis The axis to rotate the bone on
  84898. * @param angle The angle that the bone should be rotated to
  84899. * @param space The space that the axis is in
  84900. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84901. */
  84902. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  84903. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84904. if (space === BABYLON.Space.LOCAL) {
  84905. var quat = Bone._tmpQuat;
  84906. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  84907. this.setRotationQuaternion(quat, space, mesh);
  84908. return;
  84909. }
  84910. var rotMatInv = Bone._tmpMats[0];
  84911. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84912. return;
  84913. }
  84914. var rotMat = Bone._tmpMats[1];
  84915. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  84916. rotMatInv.multiplyToRef(rotMat, rotMat);
  84917. this._rotateWithMatrix(rotMat, space, mesh);
  84918. };
  84919. /**
  84920. * Set the euler rotation of the bone in local of world space
  84921. * @param rotation The euler rotation that the bone should be set to
  84922. * @param space The space that the rotation is in
  84923. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84924. */
  84925. Bone.prototype.setRotation = function (rotation, space, mesh) {
  84926. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84927. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  84928. };
  84929. /**
  84930. * Set the quaternion rotation of the bone in local of world space
  84931. * @param quat The quaternion rotation that the bone should be set to
  84932. * @param space The space that the rotation is in
  84933. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84934. */
  84935. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  84936. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84937. if (space === BABYLON.Space.LOCAL) {
  84938. this._decompose();
  84939. this._localRotation.copyFrom(quat);
  84940. this._markAsDirtyAndCompose();
  84941. return;
  84942. }
  84943. var rotMatInv = Bone._tmpMats[0];
  84944. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84945. return;
  84946. }
  84947. var rotMat = Bone._tmpMats[1];
  84948. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  84949. rotMatInv.multiplyToRef(rotMat, rotMat);
  84950. this._rotateWithMatrix(rotMat, space, mesh);
  84951. };
  84952. /**
  84953. * Set the rotation matrix of the bone in local of world space
  84954. * @param rotMat The rotation matrix that the bone should be set to
  84955. * @param space The space that the rotation is in
  84956. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84957. */
  84958. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  84959. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84960. if (space === BABYLON.Space.LOCAL) {
  84961. var quat = Bone._tmpQuat;
  84962. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  84963. this.setRotationQuaternion(quat, space, mesh);
  84964. return;
  84965. }
  84966. var rotMatInv = Bone._tmpMats[0];
  84967. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84968. return;
  84969. }
  84970. var rotMat2 = Bone._tmpMats[1];
  84971. rotMat2.copyFrom(rotMat);
  84972. rotMatInv.multiplyToRef(rotMat, rotMat2);
  84973. this._rotateWithMatrix(rotMat2, space, mesh);
  84974. };
  84975. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  84976. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84977. var lmat = this.getLocalMatrix();
  84978. var lx = lmat.m[12];
  84979. var ly = lmat.m[13];
  84980. var lz = lmat.m[14];
  84981. var parent = this.getParent();
  84982. var parentScale = Bone._tmpMats[3];
  84983. var parentScaleInv = Bone._tmpMats[4];
  84984. if (parent && space == BABYLON.Space.WORLD) {
  84985. if (mesh) {
  84986. parentScale.copyFrom(mesh.getWorldMatrix());
  84987. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  84988. }
  84989. else {
  84990. parentScale.copyFrom(parent.getAbsoluteTransform());
  84991. }
  84992. parentScaleInv.copyFrom(parentScale);
  84993. parentScaleInv.invert();
  84994. lmat.multiplyToRef(parentScale, lmat);
  84995. lmat.multiplyToRef(rmat, lmat);
  84996. lmat.multiplyToRef(parentScaleInv, lmat);
  84997. }
  84998. else {
  84999. if (space == BABYLON.Space.WORLD && mesh) {
  85000. parentScale.copyFrom(mesh.getWorldMatrix());
  85001. parentScaleInv.copyFrom(parentScale);
  85002. parentScaleInv.invert();
  85003. lmat.multiplyToRef(parentScale, lmat);
  85004. lmat.multiplyToRef(rmat, lmat);
  85005. lmat.multiplyToRef(parentScaleInv, lmat);
  85006. }
  85007. else {
  85008. lmat.multiplyToRef(rmat, lmat);
  85009. }
  85010. }
  85011. lmat.m[12] = lx;
  85012. lmat.m[13] = ly;
  85013. lmat.m[14] = lz;
  85014. this.computeAbsoluteTransforms();
  85015. this._markAsDirtyAndDecompose();
  85016. };
  85017. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  85018. var scaleMatrix = Bone._tmpMats[2];
  85019. rotMatInv.copyFrom(this.getAbsoluteTransform());
  85020. if (mesh) {
  85021. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  85022. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  85023. }
  85024. rotMatInv.invert();
  85025. if (isNaN(rotMatInv.m[0])) {
  85026. // Matrix failed to invert.
  85027. // This can happen if scale is zero for example.
  85028. return false;
  85029. }
  85030. scaleMatrix.m[0] *= this._scalingDeterminant;
  85031. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  85032. return true;
  85033. };
  85034. /**
  85035. * Get the position of the bone in local or world space
  85036. * @param space The space that the returned position is in
  85037. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85038. * @returns The position of the bone
  85039. */
  85040. Bone.prototype.getPosition = function (space, mesh) {
  85041. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85042. if (mesh === void 0) { mesh = null; }
  85043. var pos = BABYLON.Vector3.Zero();
  85044. this.getPositionToRef(space, mesh, pos);
  85045. return pos;
  85046. };
  85047. /**
  85048. * Copy the position of the bone to a vector3 in local or world space
  85049. * @param space The space that the returned position is in
  85050. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85051. * @param result The vector3 to copy the position to
  85052. */
  85053. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  85054. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85055. if (space == BABYLON.Space.LOCAL) {
  85056. var lm = this.getLocalMatrix();
  85057. result.x = lm.m[12];
  85058. result.y = lm.m[13];
  85059. result.z = lm.m[14];
  85060. }
  85061. else {
  85062. var wm = null;
  85063. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85064. if (mesh) {
  85065. wm = mesh.getWorldMatrix();
  85066. }
  85067. this._skeleton.computeAbsoluteTransforms();
  85068. var tmat = Bone._tmpMats[0];
  85069. if (mesh && wm) {
  85070. tmat.copyFrom(this.getAbsoluteTransform());
  85071. tmat.multiplyToRef(wm, tmat);
  85072. }
  85073. else {
  85074. tmat = this.getAbsoluteTransform();
  85075. }
  85076. result.x = tmat.m[12];
  85077. result.y = tmat.m[13];
  85078. result.z = tmat.m[14];
  85079. }
  85080. };
  85081. /**
  85082. * Get the absolute position of the bone (world space)
  85083. * @param mesh The mesh that this bone is attached to
  85084. * @returns The absolute position of the bone
  85085. */
  85086. Bone.prototype.getAbsolutePosition = function (mesh) {
  85087. if (mesh === void 0) { mesh = null; }
  85088. var pos = BABYLON.Vector3.Zero();
  85089. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  85090. return pos;
  85091. };
  85092. /**
  85093. * Copy the absolute position of the bone (world space) to the result param
  85094. * @param mesh The mesh that this bone is attached to
  85095. * @param result The vector3 to copy the absolute position to
  85096. */
  85097. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  85098. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  85099. };
  85100. /**
  85101. * Compute the absolute transforms of this bone and its children
  85102. */
  85103. Bone.prototype.computeAbsoluteTransforms = function () {
  85104. this._compose();
  85105. if (this._parent) {
  85106. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  85107. }
  85108. else {
  85109. this._absoluteTransform.copyFrom(this._localMatrix);
  85110. var poseMatrix = this._skeleton.getPoseMatrix();
  85111. if (poseMatrix) {
  85112. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  85113. }
  85114. }
  85115. var children = this.children;
  85116. var len = children.length;
  85117. for (var i = 0; i < len; i++) {
  85118. children[i].computeAbsoluteTransforms();
  85119. }
  85120. };
  85121. /**
  85122. * Get the world direction from an axis that is in the local space of the bone
  85123. * @param localAxis The local direction that is used to compute the world direction
  85124. * @param mesh The mesh that this bone is attached to
  85125. * @returns The world direction
  85126. */
  85127. Bone.prototype.getDirection = function (localAxis, mesh) {
  85128. if (mesh === void 0) { mesh = null; }
  85129. var result = BABYLON.Vector3.Zero();
  85130. this.getDirectionToRef(localAxis, mesh, result);
  85131. return result;
  85132. };
  85133. /**
  85134. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  85135. * @param localAxis The local direction that is used to compute the world direction
  85136. * @param mesh The mesh that this bone is attached to
  85137. * @param result The vector3 that the world direction will be copied to
  85138. */
  85139. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  85140. if (mesh === void 0) { mesh = null; }
  85141. var wm = null;
  85142. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85143. if (mesh) {
  85144. wm = mesh.getWorldMatrix();
  85145. }
  85146. this._skeleton.computeAbsoluteTransforms();
  85147. var mat = Bone._tmpMats[0];
  85148. mat.copyFrom(this.getAbsoluteTransform());
  85149. if (mesh && wm) {
  85150. mat.multiplyToRef(wm, mat);
  85151. }
  85152. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  85153. result.normalize();
  85154. };
  85155. /**
  85156. * Get the euler rotation of the bone in local or world space
  85157. * @param space The space that the rotation should be in
  85158. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85159. * @returns The euler rotation
  85160. */
  85161. Bone.prototype.getRotation = function (space, mesh) {
  85162. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85163. if (mesh === void 0) { mesh = null; }
  85164. var result = BABYLON.Vector3.Zero();
  85165. this.getRotationToRef(space, mesh, result);
  85166. return result;
  85167. };
  85168. /**
  85169. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  85170. * @param space The space that the rotation should be in
  85171. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85172. * @param result The vector3 that the rotation should be copied to
  85173. */
  85174. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  85175. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85176. if (mesh === void 0) { mesh = null; }
  85177. var quat = Bone._tmpQuat;
  85178. this.getRotationQuaternionToRef(space, mesh, quat);
  85179. quat.toEulerAnglesToRef(result);
  85180. };
  85181. /**
  85182. * Get the quaternion rotation of the bone in either local or world space
  85183. * @param space The space that the rotation should be in
  85184. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85185. * @returns The quaternion rotation
  85186. */
  85187. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  85188. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85189. if (mesh === void 0) { mesh = null; }
  85190. var result = BABYLON.Quaternion.Identity();
  85191. this.getRotationQuaternionToRef(space, mesh, result);
  85192. return result;
  85193. };
  85194. /**
  85195. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  85196. * @param space The space that the rotation should be in
  85197. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85198. * @param result The quaternion that the rotation should be copied to
  85199. */
  85200. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  85201. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85202. if (mesh === void 0) { mesh = null; }
  85203. if (space == BABYLON.Space.LOCAL) {
  85204. this._decompose();
  85205. result.copyFrom(this._localRotation);
  85206. }
  85207. else {
  85208. var mat = Bone._tmpMats[0];
  85209. var amat = this.getAbsoluteTransform();
  85210. if (mesh) {
  85211. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  85212. }
  85213. else {
  85214. mat.copyFrom(amat);
  85215. }
  85216. mat.m[0] *= this._scalingDeterminant;
  85217. mat.m[1] *= this._scalingDeterminant;
  85218. mat.m[2] *= this._scalingDeterminant;
  85219. mat.decompose(undefined, result, undefined);
  85220. }
  85221. };
  85222. /**
  85223. * Get the rotation matrix of the bone in local or world space
  85224. * @param space The space that the rotation should be in
  85225. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85226. * @returns The rotation matrix
  85227. */
  85228. Bone.prototype.getRotationMatrix = function (space, mesh) {
  85229. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85230. var result = BABYLON.Matrix.Identity();
  85231. this.getRotationMatrixToRef(space, mesh, result);
  85232. return result;
  85233. };
  85234. /**
  85235. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  85236. * @param space The space that the rotation should be in
  85237. * @param mesh The mesh that this bone is attached to. This is only used in world space
  85238. * @param result The quaternion that the rotation should be copied to
  85239. */
  85240. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  85241. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  85242. if (space == BABYLON.Space.LOCAL) {
  85243. this.getLocalMatrix().getRotationMatrixToRef(result);
  85244. }
  85245. else {
  85246. var mat = Bone._tmpMats[0];
  85247. var amat = this.getAbsoluteTransform();
  85248. if (mesh) {
  85249. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  85250. }
  85251. else {
  85252. mat.copyFrom(amat);
  85253. }
  85254. mat.m[0] *= this._scalingDeterminant;
  85255. mat.m[1] *= this._scalingDeterminant;
  85256. mat.m[2] *= this._scalingDeterminant;
  85257. mat.getRotationMatrixToRef(result);
  85258. }
  85259. };
  85260. /**
  85261. * Get the world position of a point that is in the local space of the bone
  85262. * @param position The local position
  85263. * @param mesh The mesh that this bone is attached to
  85264. * @returns The world position
  85265. */
  85266. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  85267. if (mesh === void 0) { mesh = null; }
  85268. var result = BABYLON.Vector3.Zero();
  85269. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  85270. return result;
  85271. };
  85272. /**
  85273. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  85274. * @param position The local position
  85275. * @param mesh The mesh that this bone is attached to
  85276. * @param result The vector3 that the world position should be copied to
  85277. */
  85278. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  85279. if (mesh === void 0) { mesh = null; }
  85280. var wm = null;
  85281. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85282. if (mesh) {
  85283. wm = mesh.getWorldMatrix();
  85284. }
  85285. this._skeleton.computeAbsoluteTransforms();
  85286. var tmat = Bone._tmpMats[0];
  85287. if (mesh && wm) {
  85288. tmat.copyFrom(this.getAbsoluteTransform());
  85289. tmat.multiplyToRef(wm, tmat);
  85290. }
  85291. else {
  85292. tmat = this.getAbsoluteTransform();
  85293. }
  85294. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  85295. };
  85296. /**
  85297. * Get the local position of a point that is in world space
  85298. * @param position The world position
  85299. * @param mesh The mesh that this bone is attached to
  85300. * @returns The local position
  85301. */
  85302. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  85303. if (mesh === void 0) { mesh = null; }
  85304. var result = BABYLON.Vector3.Zero();
  85305. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  85306. return result;
  85307. };
  85308. /**
  85309. * Get the local position of a point that is in world space and copy it to the result param
  85310. * @param position The world position
  85311. * @param mesh The mesh that this bone is attached to
  85312. * @param result The vector3 that the local position should be copied to
  85313. */
  85314. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  85315. if (mesh === void 0) { mesh = null; }
  85316. var wm = null;
  85317. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85318. if (mesh) {
  85319. wm = mesh.getWorldMatrix();
  85320. }
  85321. this._skeleton.computeAbsoluteTransforms();
  85322. var tmat = Bone._tmpMats[0];
  85323. tmat.copyFrom(this.getAbsoluteTransform());
  85324. if (mesh && wm) {
  85325. tmat.multiplyToRef(wm, tmat);
  85326. }
  85327. tmat.invert();
  85328. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  85329. };
  85330. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85331. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  85332. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  85333. return Bone;
  85334. }(BABYLON.Node));
  85335. BABYLON.Bone = Bone;
  85336. })(BABYLON || (BABYLON = {}));
  85337. //# sourceMappingURL=babylon.bone.js.map
  85338. var BABYLON;
  85339. (function (BABYLON) {
  85340. /**
  85341. * Class used to apply inverse kinematics to bones
  85342. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  85343. */
  85344. var BoneIKController = /** @class */ (function () {
  85345. /**
  85346. * Creates a new BoneIKController
  85347. * @param mesh defines the mesh to control
  85348. * @param bone defines the bone to control
  85349. * @param options defines options to set up the controller
  85350. */
  85351. function BoneIKController(mesh, bone, options) {
  85352. /**
  85353. * Gets or sets the target position
  85354. */
  85355. this.targetPosition = BABYLON.Vector3.Zero();
  85356. /**
  85357. * Gets or sets the pole target position
  85358. */
  85359. this.poleTargetPosition = BABYLON.Vector3.Zero();
  85360. /**
  85361. * Gets or sets the pole target local offset
  85362. */
  85363. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  85364. /**
  85365. * Gets or sets the pole angle
  85366. */
  85367. this.poleAngle = 0;
  85368. /**
  85369. * 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)
  85370. */
  85371. this.slerpAmount = 1;
  85372. this._bone1Quat = BABYLON.Quaternion.Identity();
  85373. this._bone1Mat = BABYLON.Matrix.Identity();
  85374. this._bone2Ang = Math.PI;
  85375. this._maxAngle = Math.PI;
  85376. this._rightHandedSystem = false;
  85377. this._bendAxis = BABYLON.Vector3.Right();
  85378. this._slerping = false;
  85379. this._adjustRoll = 0;
  85380. this._bone2 = bone;
  85381. this._bone1 = bone.getParent();
  85382. if (!this._bone1) {
  85383. return;
  85384. }
  85385. this.mesh = mesh;
  85386. var bonePos = bone.getPosition();
  85387. if (bone.getAbsoluteTransform().determinant() > 0) {
  85388. this._rightHandedSystem = true;
  85389. this._bendAxis.x = 0;
  85390. this._bendAxis.y = 0;
  85391. this._bendAxis.z = -1;
  85392. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  85393. this._adjustRoll = Math.PI * .5;
  85394. this._bendAxis.z = 1;
  85395. }
  85396. }
  85397. if (this._bone1.length) {
  85398. var boneScale1 = this._bone1.getScale();
  85399. var boneScale2 = this._bone2.getScale();
  85400. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  85401. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  85402. }
  85403. else if (this._bone1.children[0]) {
  85404. mesh.computeWorldMatrix(true);
  85405. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  85406. var pos2 = this._bone2.getAbsolutePosition(mesh);
  85407. var pos3 = this._bone1.getAbsolutePosition(mesh);
  85408. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  85409. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  85410. }
  85411. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  85412. this.maxAngle = Math.PI;
  85413. if (options) {
  85414. if (options.targetMesh) {
  85415. this.targetMesh = options.targetMesh;
  85416. this.targetMesh.computeWorldMatrix(true);
  85417. }
  85418. if (options.poleTargetMesh) {
  85419. this.poleTargetMesh = options.poleTargetMesh;
  85420. this.poleTargetMesh.computeWorldMatrix(true);
  85421. }
  85422. else if (options.poleTargetBone) {
  85423. this.poleTargetBone = options.poleTargetBone;
  85424. }
  85425. else if (this._bone1.getParent()) {
  85426. this.poleTargetBone = this._bone1.getParent();
  85427. }
  85428. if (options.poleTargetLocalOffset) {
  85429. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  85430. }
  85431. if (options.poleAngle) {
  85432. this.poleAngle = options.poleAngle;
  85433. }
  85434. if (options.bendAxis) {
  85435. this._bendAxis.copyFrom(options.bendAxis);
  85436. }
  85437. if (options.maxAngle) {
  85438. this.maxAngle = options.maxAngle;
  85439. }
  85440. if (options.slerpAmount) {
  85441. this.slerpAmount = options.slerpAmount;
  85442. }
  85443. }
  85444. }
  85445. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  85446. /**
  85447. * Gets or sets maximum allowed angle
  85448. */
  85449. get: function () {
  85450. return this._maxAngle;
  85451. },
  85452. set: function (value) {
  85453. this._setMaxAngle(value);
  85454. },
  85455. enumerable: true,
  85456. configurable: true
  85457. });
  85458. BoneIKController.prototype._setMaxAngle = function (ang) {
  85459. if (ang < 0) {
  85460. ang = 0;
  85461. }
  85462. if (ang > Math.PI || ang == undefined) {
  85463. ang = Math.PI;
  85464. }
  85465. this._maxAngle = ang;
  85466. var a = this._bone1Length;
  85467. var b = this._bone2Length;
  85468. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  85469. };
  85470. /**
  85471. * Force the controller to update the bones
  85472. */
  85473. BoneIKController.prototype.update = function () {
  85474. var bone1 = this._bone1;
  85475. if (!bone1) {
  85476. return;
  85477. }
  85478. var target = this.targetPosition;
  85479. var poleTarget = this.poleTargetPosition;
  85480. var mat1 = BoneIKController._tmpMats[0];
  85481. var mat2 = BoneIKController._tmpMats[1];
  85482. if (this.targetMesh) {
  85483. target.copyFrom(this.targetMesh.getAbsolutePosition());
  85484. }
  85485. if (this.poleTargetBone) {
  85486. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  85487. }
  85488. else if (this.poleTargetMesh) {
  85489. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  85490. }
  85491. var bonePos = BoneIKController._tmpVecs[0];
  85492. var zaxis = BoneIKController._tmpVecs[1];
  85493. var xaxis = BoneIKController._tmpVecs[2];
  85494. var yaxis = BoneIKController._tmpVecs[3];
  85495. var upAxis = BoneIKController._tmpVecs[4];
  85496. var _tmpQuat = BoneIKController._tmpQuat;
  85497. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  85498. poleTarget.subtractToRef(bonePos, upAxis);
  85499. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  85500. upAxis.y = 1;
  85501. }
  85502. else {
  85503. upAxis.normalize();
  85504. }
  85505. target.subtractToRef(bonePos, yaxis);
  85506. yaxis.normalize();
  85507. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  85508. zaxis.normalize();
  85509. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  85510. xaxis.normalize();
  85511. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  85512. var a = this._bone1Length;
  85513. var b = this._bone2Length;
  85514. var c = BABYLON.Vector3.Distance(bonePos, target);
  85515. if (this._maxReach > 0) {
  85516. c = Math.min(this._maxReach, c);
  85517. }
  85518. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  85519. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  85520. if (acosa > 1) {
  85521. acosa = 1;
  85522. }
  85523. if (acosb > 1) {
  85524. acosb = 1;
  85525. }
  85526. if (acosa < -1) {
  85527. acosa = -1;
  85528. }
  85529. if (acosb < -1) {
  85530. acosb = -1;
  85531. }
  85532. var angA = Math.acos(acosa);
  85533. var angB = Math.acos(acosb);
  85534. var angC = -angA - angB;
  85535. if (this._rightHandedSystem) {
  85536. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  85537. mat2.multiplyToRef(mat1, mat1);
  85538. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  85539. mat2.multiplyToRef(mat1, mat1);
  85540. }
  85541. else {
  85542. var _tmpVec = BoneIKController._tmpVecs[5];
  85543. _tmpVec.copyFrom(this._bendAxis);
  85544. _tmpVec.x *= -1;
  85545. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  85546. mat2.multiplyToRef(mat1, mat1);
  85547. }
  85548. if (this.poleAngle) {
  85549. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  85550. mat1.multiplyToRef(mat2, mat1);
  85551. }
  85552. if (this._bone1) {
  85553. if (this.slerpAmount < 1) {
  85554. if (!this._slerping) {
  85555. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  85556. }
  85557. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  85558. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  85559. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  85560. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  85561. this._slerping = true;
  85562. }
  85563. else {
  85564. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  85565. this._bone1Mat.copyFrom(mat1);
  85566. this._slerping = false;
  85567. }
  85568. }
  85569. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  85570. this._bone2Ang = angC;
  85571. };
  85572. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85573. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  85574. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  85575. return BoneIKController;
  85576. }());
  85577. BABYLON.BoneIKController = BoneIKController;
  85578. })(BABYLON || (BABYLON = {}));
  85579. //# sourceMappingURL=babylon.boneIKController.js.map
  85580. var BABYLON;
  85581. (function (BABYLON) {
  85582. /**
  85583. * Class used to make a bone look toward a point in space
  85584. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  85585. */
  85586. var BoneLookController = /** @class */ (function () {
  85587. /**
  85588. * Create a BoneLookController
  85589. * @param mesh the mesh that the bone belongs to
  85590. * @param bone the bone that will be looking to the target
  85591. * @param target the target Vector3 to look at
  85592. * @param settings optional settings:
  85593. * * maxYaw: the maximum angle the bone will yaw to
  85594. * * minYaw: the minimum angle the bone will yaw to
  85595. * * maxPitch: the maximum angle the bone will pitch to
  85596. * * minPitch: the minimum angle the bone will yaw to
  85597. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  85598. * * upAxis: the up axis of the coordinate system
  85599. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  85600. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  85601. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  85602. * * adjustYaw: used to make an adjustment to the yaw of the bone
  85603. * * adjustPitch: used to make an adjustment to the pitch of the bone
  85604. * * adjustRoll: used to make an adjustment to the roll of the bone
  85605. **/
  85606. function BoneLookController(mesh, bone, target, options) {
  85607. /**
  85608. * The up axis of the coordinate system that is used when the bone is rotated
  85609. */
  85610. this.upAxis = BABYLON.Vector3.Up();
  85611. /**
  85612. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  85613. */
  85614. this.upAxisSpace = BABYLON.Space.LOCAL;
  85615. /**
  85616. * Used to make an adjustment to the yaw of the bone
  85617. */
  85618. this.adjustYaw = 0;
  85619. /**
  85620. * Used to make an adjustment to the pitch of the bone
  85621. */
  85622. this.adjustPitch = 0;
  85623. /**
  85624. * Used to make an adjustment to the roll of the bone
  85625. */
  85626. this.adjustRoll = 0;
  85627. /**
  85628. * 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)
  85629. */
  85630. this.slerpAmount = 1;
  85631. this._boneQuat = BABYLON.Quaternion.Identity();
  85632. this._slerping = false;
  85633. this._firstFrameSkipped = false;
  85634. this._fowardAxis = BABYLON.Vector3.Forward();
  85635. this.mesh = mesh;
  85636. this.bone = bone;
  85637. this.target = target;
  85638. if (options) {
  85639. if (options.adjustYaw) {
  85640. this.adjustYaw = options.adjustYaw;
  85641. }
  85642. if (options.adjustPitch) {
  85643. this.adjustPitch = options.adjustPitch;
  85644. }
  85645. if (options.adjustRoll) {
  85646. this.adjustRoll = options.adjustRoll;
  85647. }
  85648. if (options.maxYaw != null) {
  85649. this.maxYaw = options.maxYaw;
  85650. }
  85651. else {
  85652. this.maxYaw = Math.PI;
  85653. }
  85654. if (options.minYaw != null) {
  85655. this.minYaw = options.minYaw;
  85656. }
  85657. else {
  85658. this.minYaw = -Math.PI;
  85659. }
  85660. if (options.maxPitch != null) {
  85661. this.maxPitch = options.maxPitch;
  85662. }
  85663. else {
  85664. this.maxPitch = Math.PI;
  85665. }
  85666. if (options.minPitch != null) {
  85667. this.minPitch = options.minPitch;
  85668. }
  85669. else {
  85670. this.minPitch = -Math.PI;
  85671. }
  85672. if (options.slerpAmount != null) {
  85673. this.slerpAmount = options.slerpAmount;
  85674. }
  85675. if (options.upAxis != null) {
  85676. this.upAxis = options.upAxis;
  85677. }
  85678. if (options.upAxisSpace != null) {
  85679. this.upAxisSpace = options.upAxisSpace;
  85680. }
  85681. if (options.yawAxis != null || options.pitchAxis != null) {
  85682. var newYawAxis = BABYLON.Axis.Y;
  85683. var newPitchAxis = BABYLON.Axis.X;
  85684. if (options.yawAxis != null) {
  85685. newYawAxis = options.yawAxis.clone();
  85686. newYawAxis.normalize();
  85687. }
  85688. if (options.pitchAxis != null) {
  85689. newPitchAxis = options.pitchAxis.clone();
  85690. newPitchAxis.normalize();
  85691. }
  85692. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  85693. this._transformYawPitch = BABYLON.Matrix.Identity();
  85694. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  85695. this._transformYawPitchInv = this._transformYawPitch.clone();
  85696. this._transformYawPitch.invert();
  85697. }
  85698. }
  85699. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  85700. this.upAxisSpace = BABYLON.Space.LOCAL;
  85701. }
  85702. }
  85703. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  85704. /**
  85705. * Gets or sets the minimum yaw angle that the bone can look to
  85706. */
  85707. get: function () {
  85708. return this._minYaw;
  85709. },
  85710. set: function (value) {
  85711. this._minYaw = value;
  85712. this._minYawSin = Math.sin(value);
  85713. this._minYawCos = Math.cos(value);
  85714. if (this._maxYaw != null) {
  85715. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  85716. this._yawRange = this._maxYaw - this._minYaw;
  85717. }
  85718. },
  85719. enumerable: true,
  85720. configurable: true
  85721. });
  85722. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  85723. /**
  85724. * Gets or sets the maximum yaw angle that the bone can look to
  85725. */
  85726. get: function () {
  85727. return this._maxYaw;
  85728. },
  85729. set: function (value) {
  85730. this._maxYaw = value;
  85731. this._maxYawSin = Math.sin(value);
  85732. this._maxYawCos = Math.cos(value);
  85733. if (this._minYaw != null) {
  85734. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  85735. this._yawRange = this._maxYaw - this._minYaw;
  85736. }
  85737. },
  85738. enumerable: true,
  85739. configurable: true
  85740. });
  85741. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  85742. /**
  85743. * Gets or sets the minimum pitch angle that the bone can look to
  85744. */
  85745. get: function () {
  85746. return this._minPitch;
  85747. },
  85748. set: function (value) {
  85749. this._minPitch = value;
  85750. this._minPitchTan = Math.tan(value);
  85751. },
  85752. enumerable: true,
  85753. configurable: true
  85754. });
  85755. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  85756. /**
  85757. * Gets or sets the maximum pitch angle that the bone can look to
  85758. */
  85759. get: function () {
  85760. return this._maxPitch;
  85761. },
  85762. set: function (value) {
  85763. this._maxPitch = value;
  85764. this._maxPitchTan = Math.tan(value);
  85765. },
  85766. enumerable: true,
  85767. configurable: true
  85768. });
  85769. /**
  85770. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  85771. */
  85772. BoneLookController.prototype.update = function () {
  85773. //skip the first frame when slerping so that the mesh rotation is correct
  85774. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  85775. this._firstFrameSkipped = true;
  85776. return;
  85777. }
  85778. var bone = this.bone;
  85779. var bonePos = BoneLookController._tmpVecs[0];
  85780. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  85781. var target = this.target;
  85782. var _tmpMat1 = BoneLookController._tmpMats[0];
  85783. var _tmpMat2 = BoneLookController._tmpMats[1];
  85784. var mesh = this.mesh;
  85785. var parentBone = bone.getParent();
  85786. var upAxis = BoneLookController._tmpVecs[1];
  85787. upAxis.copyFrom(this.upAxis);
  85788. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  85789. if (this._transformYawPitch) {
  85790. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  85791. }
  85792. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  85793. }
  85794. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  85795. mesh.getDirectionToRef(upAxis, upAxis);
  85796. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  85797. upAxis.normalize();
  85798. }
  85799. }
  85800. var checkYaw = false;
  85801. var checkPitch = false;
  85802. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  85803. checkYaw = true;
  85804. }
  85805. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  85806. checkPitch = true;
  85807. }
  85808. if (checkYaw || checkPitch) {
  85809. var spaceMat = BoneLookController._tmpMats[2];
  85810. var spaceMatInv = BoneLookController._tmpMats[3];
  85811. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  85812. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  85813. }
  85814. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  85815. spaceMat.copyFrom(mesh.getWorldMatrix());
  85816. }
  85817. else {
  85818. var forwardAxis = BoneLookController._tmpVecs[2];
  85819. forwardAxis.copyFrom(this._fowardAxis);
  85820. if (this._transformYawPitch) {
  85821. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  85822. }
  85823. if (parentBone) {
  85824. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  85825. }
  85826. else {
  85827. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  85828. }
  85829. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  85830. rightAxis.normalize();
  85831. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  85832. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  85833. }
  85834. spaceMat.invertToRef(spaceMatInv);
  85835. var xzlen = null;
  85836. if (checkPitch) {
  85837. var localTarget = BoneLookController._tmpVecs[3];
  85838. target.subtractToRef(bonePos, localTarget);
  85839. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  85840. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85841. var pitch = Math.atan2(localTarget.y, xzlen);
  85842. var newPitch = pitch;
  85843. if (pitch > this._maxPitch) {
  85844. localTarget.y = this._maxPitchTan * xzlen;
  85845. newPitch = this._maxPitch;
  85846. }
  85847. else if (pitch < this._minPitch) {
  85848. localTarget.y = this._minPitchTan * xzlen;
  85849. newPitch = this._minPitch;
  85850. }
  85851. if (pitch != newPitch) {
  85852. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  85853. localTarget.addInPlace(bonePos);
  85854. target = localTarget;
  85855. }
  85856. }
  85857. if (checkYaw) {
  85858. var localTarget = BoneLookController._tmpVecs[4];
  85859. target.subtractToRef(bonePos, localTarget);
  85860. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  85861. var yaw = Math.atan2(localTarget.x, localTarget.z);
  85862. var newYaw = yaw;
  85863. if (yaw > this._maxYaw || yaw < this._minYaw) {
  85864. if (xzlen == null) {
  85865. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85866. }
  85867. if (this._yawRange > Math.PI) {
  85868. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  85869. localTarget.z = this._maxYawCos * xzlen;
  85870. localTarget.x = this._maxYawSin * xzlen;
  85871. newYaw = this._maxYaw;
  85872. }
  85873. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  85874. localTarget.z = this._minYawCos * xzlen;
  85875. localTarget.x = this._minYawSin * xzlen;
  85876. newYaw = this._minYaw;
  85877. }
  85878. }
  85879. else {
  85880. if (yaw > this._maxYaw) {
  85881. localTarget.z = this._maxYawCos * xzlen;
  85882. localTarget.x = this._maxYawSin * xzlen;
  85883. newYaw = this._maxYaw;
  85884. }
  85885. else if (yaw < this._minYaw) {
  85886. localTarget.z = this._minYawCos * xzlen;
  85887. localTarget.x = this._minYawSin * xzlen;
  85888. newYaw = this._minYaw;
  85889. }
  85890. }
  85891. }
  85892. if (this._slerping && this._yawRange > Math.PI) {
  85893. //are we going to be crossing into the min/max region?
  85894. var boneFwd = BoneLookController._tmpVecs[8];
  85895. boneFwd.copyFrom(BABYLON.Axis.Z);
  85896. if (this._transformYawPitch) {
  85897. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  85898. }
  85899. var boneRotMat = BoneLookController._tmpMats[4];
  85900. this._boneQuat.toRotationMatrix(boneRotMat);
  85901. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  85902. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  85903. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  85904. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  85905. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  85906. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  85907. if (angBtwTar > angBtwMidYaw) {
  85908. if (xzlen == null) {
  85909. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85910. }
  85911. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  85912. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  85913. if (angBtwMin < angBtwMax) {
  85914. newYaw = boneYaw + Math.PI * .75;
  85915. localTarget.z = Math.cos(newYaw) * xzlen;
  85916. localTarget.x = Math.sin(newYaw) * xzlen;
  85917. }
  85918. else {
  85919. newYaw = boneYaw - Math.PI * .75;
  85920. localTarget.z = Math.cos(newYaw) * xzlen;
  85921. localTarget.x = Math.sin(newYaw) * xzlen;
  85922. }
  85923. }
  85924. }
  85925. if (yaw != newYaw) {
  85926. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  85927. localTarget.addInPlace(bonePos);
  85928. target = localTarget;
  85929. }
  85930. }
  85931. }
  85932. var zaxis = BoneLookController._tmpVecs[5];
  85933. var xaxis = BoneLookController._tmpVecs[6];
  85934. var yaxis = BoneLookController._tmpVecs[7];
  85935. var _tmpQuat = BoneLookController._tmpQuat;
  85936. target.subtractToRef(bonePos, zaxis);
  85937. zaxis.normalize();
  85938. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  85939. xaxis.normalize();
  85940. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  85941. yaxis.normalize();
  85942. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  85943. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  85944. return;
  85945. }
  85946. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  85947. return;
  85948. }
  85949. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  85950. return;
  85951. }
  85952. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  85953. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  85954. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  85955. }
  85956. if (this.slerpAmount < 1) {
  85957. if (!this._slerping) {
  85958. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  85959. }
  85960. if (this._transformYawPitch) {
  85961. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  85962. }
  85963. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  85964. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  85965. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  85966. this._slerping = true;
  85967. }
  85968. else {
  85969. if (this._transformYawPitch) {
  85970. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  85971. }
  85972. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  85973. this._slerping = false;
  85974. }
  85975. };
  85976. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  85977. var angDiff = ang2 - ang1;
  85978. angDiff %= Math.PI * 2;
  85979. if (angDiff > Math.PI) {
  85980. angDiff -= Math.PI * 2;
  85981. }
  85982. else if (angDiff < -Math.PI) {
  85983. angDiff += Math.PI * 2;
  85984. }
  85985. return angDiff;
  85986. };
  85987. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  85988. ang1 %= (2 * Math.PI);
  85989. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  85990. ang2 %= (2 * Math.PI);
  85991. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  85992. var ab = 0;
  85993. if (ang1 < ang2) {
  85994. ab = ang2 - ang1;
  85995. }
  85996. else {
  85997. ab = ang1 - ang2;
  85998. }
  85999. if (ab > Math.PI) {
  86000. ab = Math.PI * 2 - ab;
  86001. }
  86002. return ab;
  86003. };
  86004. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  86005. ang %= (2 * Math.PI);
  86006. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  86007. ang1 %= (2 * Math.PI);
  86008. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  86009. ang2 %= (2 * Math.PI);
  86010. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  86011. if (ang1 < ang2) {
  86012. if (ang > ang1 && ang < ang2) {
  86013. return true;
  86014. }
  86015. }
  86016. else {
  86017. if (ang > ang2 && ang < ang1) {
  86018. return true;
  86019. }
  86020. }
  86021. return false;
  86022. };
  86023. 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()];
  86024. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  86025. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  86026. return BoneLookController;
  86027. }());
  86028. BABYLON.BoneLookController = BoneLookController;
  86029. })(BABYLON || (BABYLON = {}));
  86030. //# sourceMappingURL=babylon.boneLookController.js.map
  86031. var BABYLON;
  86032. (function (BABYLON) {
  86033. /**
  86034. * Class used to handle skinning animations
  86035. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  86036. */
  86037. var Skeleton = /** @class */ (function () {
  86038. /**
  86039. * Creates a new skeleton
  86040. * @param name defines the skeleton name
  86041. * @param id defines the skeleton Id
  86042. * @param scene defines the hosting scene
  86043. */
  86044. function Skeleton(
  86045. /** defines the skeleton name */
  86046. name,
  86047. /** defines the skeleton Id */
  86048. id, scene) {
  86049. this.name = name;
  86050. this.id = id;
  86051. /**
  86052. * Gets the list of child bones
  86053. */
  86054. this.bones = new Array();
  86055. /**
  86056. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  86057. */
  86058. this.needInitialSkinMatrix = false;
  86059. this._isDirty = true;
  86060. this._meshesWithPoseMatrix = new Array();
  86061. this._identity = BABYLON.Matrix.Identity();
  86062. this._ranges = {};
  86063. this._lastAbsoluteTransformsUpdateId = -1;
  86064. /**
  86065. * Specifies if the skeleton should be serialized
  86066. */
  86067. this.doNotSerialize = false;
  86068. this._animationPropertiesOverride = null;
  86069. // Events
  86070. /**
  86071. * An observable triggered before computing the skeleton's matrices
  86072. */
  86073. this.onBeforeComputeObservable = new BABYLON.Observable();
  86074. this.bones = [];
  86075. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86076. scene.skeletons.push(this);
  86077. //make sure it will recalculate the matrix next time prepare is called.
  86078. this._isDirty = true;
  86079. }
  86080. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  86081. /**
  86082. * Gets or sets the animation properties override
  86083. */
  86084. get: function () {
  86085. if (!this._animationPropertiesOverride) {
  86086. return this._scene.animationPropertiesOverride;
  86087. }
  86088. return this._animationPropertiesOverride;
  86089. },
  86090. set: function (value) {
  86091. this._animationPropertiesOverride = value;
  86092. },
  86093. enumerable: true,
  86094. configurable: true
  86095. });
  86096. // Members
  86097. /**
  86098. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  86099. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  86100. * @returns a Float32Array containing matrices data
  86101. */
  86102. Skeleton.prototype.getTransformMatrices = function (mesh) {
  86103. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  86104. return mesh._bonesTransformMatrices;
  86105. }
  86106. if (!this._transformMatrices) {
  86107. this.prepare();
  86108. }
  86109. return this._transformMatrices;
  86110. };
  86111. /**
  86112. * Gets the current hosting scene
  86113. * @returns a scene object
  86114. */
  86115. Skeleton.prototype.getScene = function () {
  86116. return this._scene;
  86117. };
  86118. // Methods
  86119. /**
  86120. * Gets a string representing the current skeleton data
  86121. * @param fullDetails defines a boolean indicating if we want a verbose version
  86122. * @returns a string representing the current skeleton data
  86123. */
  86124. Skeleton.prototype.toString = function (fullDetails) {
  86125. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  86126. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  86127. if (fullDetails) {
  86128. ret += ", Ranges: {";
  86129. var first = true;
  86130. for (var name_1 in this._ranges) {
  86131. if (first) {
  86132. ret += ", ";
  86133. first = false;
  86134. }
  86135. ret += name_1;
  86136. }
  86137. ret += "}";
  86138. }
  86139. return ret;
  86140. };
  86141. /**
  86142. * Get bone's index searching by name
  86143. * @param name defines bone's name to search for
  86144. * @return the indice of the bone. Returns -1 if not found
  86145. */
  86146. Skeleton.prototype.getBoneIndexByName = function (name) {
  86147. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  86148. if (this.bones[boneIndex].name === name) {
  86149. return boneIndex;
  86150. }
  86151. }
  86152. return -1;
  86153. };
  86154. /**
  86155. * Creater a new animation range
  86156. * @param name defines the name of the range
  86157. * @param from defines the start key
  86158. * @param to defines the end key
  86159. */
  86160. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  86161. // check name not already in use
  86162. if (!this._ranges[name]) {
  86163. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  86164. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  86165. if (this.bones[i].animations[0]) {
  86166. this.bones[i].animations[0].createRange(name, from, to);
  86167. }
  86168. }
  86169. }
  86170. };
  86171. /**
  86172. * Delete a specific animation range
  86173. * @param name defines the name of the range
  86174. * @param deleteFrames defines if frames must be removed as well
  86175. */
  86176. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  86177. if (deleteFrames === void 0) { deleteFrames = true; }
  86178. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  86179. if (this.bones[i].animations[0]) {
  86180. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  86181. }
  86182. }
  86183. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  86184. };
  86185. /**
  86186. * Gets a specific animation range
  86187. * @param name defines the name of the range to look for
  86188. * @returns the requested animation range or null if not found
  86189. */
  86190. Skeleton.prototype.getAnimationRange = function (name) {
  86191. return this._ranges[name];
  86192. };
  86193. /**
  86194. * Gets the list of all animation ranges defined on this skeleton
  86195. * @returns an array
  86196. */
  86197. Skeleton.prototype.getAnimationRanges = function () {
  86198. var animationRanges = [];
  86199. var name;
  86200. var i = 0;
  86201. for (name in this._ranges) {
  86202. animationRanges[i] = this._ranges[name];
  86203. i++;
  86204. }
  86205. return animationRanges;
  86206. };
  86207. /**
  86208. * Copy animation range from a source skeleton.
  86209. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  86210. * @param source defines the source skeleton
  86211. * @param name defines the name of the range to copy
  86212. * @param rescaleAsRequired defines if rescaling must be applied if required
  86213. * @returns true if operation was successful
  86214. */
  86215. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  86216. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  86217. if (this._ranges[name] || !source.getAnimationRange(name)) {
  86218. return false;
  86219. }
  86220. var ret = true;
  86221. var frameOffset = this._getHighestAnimationFrame() + 1;
  86222. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  86223. var boneDict = {};
  86224. var sourceBones = source.bones;
  86225. var nBones;
  86226. var i;
  86227. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  86228. boneDict[sourceBones[i].name] = sourceBones[i];
  86229. }
  86230. if (this.bones.length !== sourceBones.length) {
  86231. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  86232. ret = false;
  86233. }
  86234. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  86235. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  86236. var boneName = this.bones[i].name;
  86237. var sourceBone = boneDict[boneName];
  86238. if (sourceBone) {
  86239. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  86240. }
  86241. else {
  86242. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  86243. ret = false;
  86244. }
  86245. }
  86246. // do not call createAnimationRange(), since it also is done to bones, which was already done
  86247. var range = source.getAnimationRange(name);
  86248. if (range) {
  86249. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  86250. }
  86251. return ret;
  86252. };
  86253. /**
  86254. * Forces the skeleton to go to rest pose
  86255. */
  86256. Skeleton.prototype.returnToRest = function () {
  86257. for (var index = 0; index < this.bones.length; index++) {
  86258. this.bones[index].returnToRest();
  86259. }
  86260. };
  86261. Skeleton.prototype._getHighestAnimationFrame = function () {
  86262. var ret = 0;
  86263. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  86264. if (this.bones[i].animations[0]) {
  86265. var highest = this.bones[i].animations[0].getHighestFrame();
  86266. if (ret < highest) {
  86267. ret = highest;
  86268. }
  86269. }
  86270. }
  86271. return ret;
  86272. };
  86273. /**
  86274. * Begin a specific animation range
  86275. * @param name defines the name of the range to start
  86276. * @param loop defines if looping must be turned on (false by default)
  86277. * @param speedRatio defines the speed ratio to apply (1 by default)
  86278. * @param onAnimationEnd defines a callback which will be called when animation will end
  86279. * @returns a new animatable
  86280. */
  86281. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  86282. var range = this.getAnimationRange(name);
  86283. if (!range) {
  86284. return null;
  86285. }
  86286. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  86287. };
  86288. /** @hidden */
  86289. Skeleton.prototype._markAsDirty = function () {
  86290. this._isDirty = true;
  86291. };
  86292. /** @hidden */
  86293. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  86294. this._meshesWithPoseMatrix.push(mesh);
  86295. };
  86296. /** @hidden */
  86297. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  86298. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  86299. if (index > -1) {
  86300. this._meshesWithPoseMatrix.splice(index, 1);
  86301. }
  86302. };
  86303. /** @hidden */
  86304. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  86305. this.onBeforeComputeObservable.notifyObservers(this);
  86306. for (var index = 0; index < this.bones.length; index++) {
  86307. var bone = this.bones[index];
  86308. var parentBone = bone.getParent();
  86309. if (parentBone) {
  86310. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  86311. }
  86312. else {
  86313. if (initialSkinMatrix) {
  86314. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  86315. }
  86316. else {
  86317. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  86318. }
  86319. }
  86320. if (bone._index !== -1) {
  86321. var mappedIndex = bone._index === null ? index : bone._index;
  86322. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  86323. }
  86324. }
  86325. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  86326. };
  86327. /**
  86328. * Build all resources required to render a skeleton
  86329. */
  86330. Skeleton.prototype.prepare = function () {
  86331. if (!this._isDirty) {
  86332. return;
  86333. }
  86334. if (this.needInitialSkinMatrix) {
  86335. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  86336. var mesh = this._meshesWithPoseMatrix[index];
  86337. var poseMatrix = mesh.getPoseMatrix();
  86338. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  86339. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  86340. }
  86341. if (this._synchronizedWithMesh !== mesh) {
  86342. this._synchronizedWithMesh = mesh;
  86343. // Prepare bones
  86344. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  86345. var bone = this.bones[boneIndex];
  86346. if (!bone.getParent()) {
  86347. var matrix = bone.getBaseMatrix();
  86348. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  86349. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  86350. }
  86351. }
  86352. }
  86353. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  86354. }
  86355. }
  86356. else {
  86357. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  86358. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  86359. }
  86360. this._computeTransformMatrices(this._transformMatrices, null);
  86361. }
  86362. this._isDirty = false;
  86363. this._scene._activeBones.addCount(this.bones.length, false);
  86364. };
  86365. /**
  86366. * Gets the list of animatables currently running for this skeleton
  86367. * @returns an array of animatables
  86368. */
  86369. Skeleton.prototype.getAnimatables = function () {
  86370. if (!this._animatables || this._animatables.length !== this.bones.length) {
  86371. this._animatables = [];
  86372. for (var index = 0; index < this.bones.length; index++) {
  86373. this._animatables.push(this.bones[index]);
  86374. }
  86375. }
  86376. return this._animatables;
  86377. };
  86378. /**
  86379. * Clone the current skeleton
  86380. * @param name defines the name of the new skeleton
  86381. * @param id defines the id of the enw skeleton
  86382. * @returns the new skeleton
  86383. */
  86384. Skeleton.prototype.clone = function (name, id) {
  86385. var result = new Skeleton(name, id || name, this._scene);
  86386. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  86387. for (var index = 0; index < this.bones.length; index++) {
  86388. var source = this.bones[index];
  86389. var parentBone = null;
  86390. var parent_1 = source.getParent();
  86391. if (parent_1) {
  86392. var parentIndex = this.bones.indexOf(parent_1);
  86393. parentBone = result.bones[parentIndex];
  86394. }
  86395. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  86396. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  86397. }
  86398. if (this._ranges) {
  86399. result._ranges = {};
  86400. for (var rangeName in this._ranges) {
  86401. var range = this._ranges[rangeName];
  86402. if (range) {
  86403. result._ranges[rangeName] = range.clone();
  86404. }
  86405. }
  86406. }
  86407. this._isDirty = true;
  86408. return result;
  86409. };
  86410. /**
  86411. * Enable animation blending for this skeleton
  86412. * @param blendingSpeed defines the blending speed to apply
  86413. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  86414. */
  86415. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  86416. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  86417. this.bones.forEach(function (bone) {
  86418. bone.animations.forEach(function (animation) {
  86419. animation.enableBlending = true;
  86420. animation.blendingSpeed = blendingSpeed;
  86421. });
  86422. });
  86423. };
  86424. /**
  86425. * Releases all resources associated with the current skeleton
  86426. */
  86427. Skeleton.prototype.dispose = function () {
  86428. this._meshesWithPoseMatrix = [];
  86429. // Animations
  86430. this.getScene().stopAnimation(this);
  86431. // Remove from scene
  86432. this.getScene().removeSkeleton(this);
  86433. };
  86434. /**
  86435. * Serialize the skeleton in a JSON object
  86436. * @returns a JSON object
  86437. */
  86438. Skeleton.prototype.serialize = function () {
  86439. var serializationObject = {};
  86440. serializationObject.name = this.name;
  86441. serializationObject.id = this.id;
  86442. if (this.dimensionsAtRest) {
  86443. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  86444. }
  86445. serializationObject.bones = [];
  86446. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  86447. for (var index = 0; index < this.bones.length; index++) {
  86448. var bone = this.bones[index];
  86449. var parent_2 = bone.getParent();
  86450. var serializedBone = {
  86451. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  86452. name: bone.name,
  86453. matrix: bone.getBaseMatrix().toArray(),
  86454. rest: bone.getRestPose().toArray()
  86455. };
  86456. serializationObject.bones.push(serializedBone);
  86457. if (bone.length) {
  86458. serializedBone.length = bone.length;
  86459. }
  86460. if (bone.metadata) {
  86461. serializedBone.metadata = bone.metadata;
  86462. }
  86463. if (bone.animations && bone.animations.length > 0) {
  86464. serializedBone.animation = bone.animations[0].serialize();
  86465. }
  86466. serializationObject.ranges = [];
  86467. for (var name in this._ranges) {
  86468. var source = this._ranges[name];
  86469. if (!source) {
  86470. continue;
  86471. }
  86472. var range = {};
  86473. range.name = name;
  86474. range.from = source.from;
  86475. range.to = source.to;
  86476. serializationObject.ranges.push(range);
  86477. }
  86478. }
  86479. return serializationObject;
  86480. };
  86481. /**
  86482. * Creates a new skeleton from serialized data
  86483. * @param parsedSkeleton defines the serialized data
  86484. * @param scene defines the hosting scene
  86485. * @returns a new skeleton
  86486. */
  86487. Skeleton.Parse = function (parsedSkeleton, scene) {
  86488. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  86489. if (parsedSkeleton.dimensionsAtRest) {
  86490. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  86491. }
  86492. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  86493. var index;
  86494. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  86495. var parsedBone = parsedSkeleton.bones[index];
  86496. var parentBone = null;
  86497. if (parsedBone.parentBoneIndex > -1) {
  86498. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  86499. }
  86500. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  86501. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  86502. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  86503. bone.id = parsedBone.id;
  86504. }
  86505. if (parsedBone.length) {
  86506. bone.length = parsedBone.length;
  86507. }
  86508. if (parsedBone.metadata) {
  86509. bone.metadata = parsedBone.metadata;
  86510. }
  86511. if (parsedBone.animation) {
  86512. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  86513. }
  86514. }
  86515. // placed after bones, so createAnimationRange can cascade down
  86516. if (parsedSkeleton.ranges) {
  86517. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  86518. var data = parsedSkeleton.ranges[index];
  86519. skeleton.createAnimationRange(data.name, data.from, data.to);
  86520. }
  86521. }
  86522. return skeleton;
  86523. };
  86524. /**
  86525. * Compute all node absolute transforms
  86526. * @param forceUpdate defines if computation must be done even if cache is up to date
  86527. */
  86528. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  86529. if (forceUpdate === void 0) { forceUpdate = false; }
  86530. var renderId = this._scene.getRenderId();
  86531. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  86532. this.bones[0].computeAbsoluteTransforms();
  86533. this._lastAbsoluteTransformsUpdateId = renderId;
  86534. }
  86535. };
  86536. /**
  86537. * Gets the root pose matrix
  86538. * @returns a matrix
  86539. */
  86540. Skeleton.prototype.getPoseMatrix = function () {
  86541. var poseMatrix = null;
  86542. if (this._meshesWithPoseMatrix.length > 0) {
  86543. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  86544. }
  86545. return poseMatrix;
  86546. };
  86547. /**
  86548. * Sorts bones per internal index
  86549. */
  86550. Skeleton.prototype.sortBones = function () {
  86551. var bones = new Array();
  86552. var visited = new Array(this.bones.length);
  86553. for (var index = 0; index < this.bones.length; index++) {
  86554. this._sortBones(index, bones, visited);
  86555. }
  86556. this.bones = bones;
  86557. };
  86558. Skeleton.prototype._sortBones = function (index, bones, visited) {
  86559. if (visited[index]) {
  86560. return;
  86561. }
  86562. visited[index] = true;
  86563. var bone = this.bones[index];
  86564. if (bone._index === undefined) {
  86565. bone._index = index;
  86566. }
  86567. var parentBone = bone.getParent();
  86568. if (parentBone) {
  86569. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  86570. }
  86571. bones.push(bone);
  86572. };
  86573. return Skeleton;
  86574. }());
  86575. BABYLON.Skeleton = Skeleton;
  86576. })(BABYLON || (BABYLON = {}));
  86577. //# sourceMappingURL=babylon.skeleton.js.map
  86578. var BABYLON;
  86579. (function (BABYLON) {
  86580. ;
  86581. /**
  86582. * This groups tools to convert HDR texture to native colors array.
  86583. */
  86584. var HDRTools = /** @class */ (function () {
  86585. function HDRTools() {
  86586. }
  86587. HDRTools.Ldexp = function (mantissa, exponent) {
  86588. if (exponent > 1023) {
  86589. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  86590. }
  86591. if (exponent < -1074) {
  86592. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  86593. }
  86594. return mantissa * Math.pow(2, exponent);
  86595. };
  86596. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  86597. if (exponent > 0) { /*nonzero pixel*/
  86598. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  86599. float32array[index + 0] = red * exponent;
  86600. float32array[index + 1] = green * exponent;
  86601. float32array[index + 2] = blue * exponent;
  86602. }
  86603. else {
  86604. float32array[index + 0] = 0;
  86605. float32array[index + 1] = 0;
  86606. float32array[index + 2] = 0;
  86607. }
  86608. };
  86609. HDRTools.readStringLine = function (uint8array, startIndex) {
  86610. var line = "";
  86611. var character = "";
  86612. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  86613. character = String.fromCharCode(uint8array[i]);
  86614. if (character == "\n") {
  86615. break;
  86616. }
  86617. line += character;
  86618. }
  86619. return line;
  86620. };
  86621. /**
  86622. * Reads header information from an RGBE texture stored in a native array.
  86623. * More information on this format are available here:
  86624. * https://en.wikipedia.org/wiki/RGBE_image_format
  86625. *
  86626. * @param uint8array The binary file stored in native array.
  86627. * @return The header information.
  86628. */
  86629. HDRTools.RGBE_ReadHeader = function (uint8array) {
  86630. var height = 0;
  86631. var width = 0;
  86632. var line = this.readStringLine(uint8array, 0);
  86633. if (line[0] != '#' || line[1] != '?') {
  86634. throw "Bad HDR Format.";
  86635. }
  86636. var endOfHeader = false;
  86637. var findFormat = false;
  86638. var lineIndex = 0;
  86639. do {
  86640. lineIndex += (line.length + 1);
  86641. line = this.readStringLine(uint8array, lineIndex);
  86642. if (line == "FORMAT=32-bit_rle_rgbe") {
  86643. findFormat = true;
  86644. }
  86645. else if (line.length == 0) {
  86646. endOfHeader = true;
  86647. }
  86648. } while (!endOfHeader);
  86649. if (!findFormat) {
  86650. throw "HDR Bad header format, unsupported FORMAT";
  86651. }
  86652. lineIndex += (line.length + 1);
  86653. line = this.readStringLine(uint8array, lineIndex);
  86654. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  86655. var match = sizeRegexp.exec(line);
  86656. // TODO. Support +Y and -X if needed.
  86657. if (!match || match.length < 3) {
  86658. throw "HDR Bad header format, no size";
  86659. }
  86660. width = parseInt(match[2]);
  86661. height = parseInt(match[1]);
  86662. if (width < 8 || width > 0x7fff) {
  86663. throw "HDR Bad header format, unsupported size";
  86664. }
  86665. lineIndex += (line.length + 1);
  86666. return {
  86667. height: height,
  86668. width: width,
  86669. dataPosition: lineIndex
  86670. };
  86671. };
  86672. /**
  86673. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  86674. * This RGBE texture needs to store the information as a panorama.
  86675. *
  86676. * More information on this format are available here:
  86677. * https://en.wikipedia.org/wiki/RGBE_image_format
  86678. *
  86679. * @param buffer The binary file stored in an array buffer.
  86680. * @param size The expected size of the extracted cubemap.
  86681. * @return The Cube Map information.
  86682. */
  86683. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  86684. var uint8array = new Uint8Array(buffer);
  86685. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  86686. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  86687. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  86688. return cubeMapData;
  86689. };
  86690. /**
  86691. * Returns the pixels data extracted from an RGBE texture.
  86692. * This pixels will be stored left to right up to down in the R G B order in one array.
  86693. *
  86694. * More information on this format are available here:
  86695. * https://en.wikipedia.org/wiki/RGBE_image_format
  86696. *
  86697. * @param uint8array The binary file stored in an array buffer.
  86698. * @param hdrInfo The header information of the file.
  86699. * @return The pixels data in RGB right to left up to down order.
  86700. */
  86701. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  86702. // Keep for multi format supports.
  86703. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  86704. };
  86705. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  86706. var num_scanlines = hdrInfo.height;
  86707. var scanline_width = hdrInfo.width;
  86708. var a, b, c, d, count;
  86709. var dataIndex = hdrInfo.dataPosition;
  86710. var index = 0, endIndex = 0, i = 0;
  86711. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  86712. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  86713. // 3 channels of 4 bytes per pixel in float.
  86714. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  86715. var resultArray = new Float32Array(resultBuffer);
  86716. // read in each successive scanline
  86717. while (num_scanlines > 0) {
  86718. a = uint8array[dataIndex++];
  86719. b = uint8array[dataIndex++];
  86720. c = uint8array[dataIndex++];
  86721. d = uint8array[dataIndex++];
  86722. if (a != 2 || b != 2 || (c & 0x80)) {
  86723. // this file is not run length encoded
  86724. throw "HDR Bad header format, not RLE";
  86725. }
  86726. if (((c << 8) | d) != scanline_width) {
  86727. throw "HDR Bad header format, wrong scan line width";
  86728. }
  86729. index = 0;
  86730. // read each of the four channels for the scanline into the buffer
  86731. for (i = 0; i < 4; i++) {
  86732. endIndex = (i + 1) * scanline_width;
  86733. while (index < endIndex) {
  86734. a = uint8array[dataIndex++];
  86735. b = uint8array[dataIndex++];
  86736. if (a > 128) {
  86737. // a run of the same value
  86738. count = a - 128;
  86739. if ((count == 0) || (count > endIndex - index)) {
  86740. throw "HDR Bad Format, bad scanline data (run)";
  86741. }
  86742. while (count-- > 0) {
  86743. scanLineArray[index++] = b;
  86744. }
  86745. }
  86746. else {
  86747. // a non-run
  86748. count = a;
  86749. if ((count == 0) || (count > endIndex - index)) {
  86750. throw "HDR Bad Format, bad scanline data (non-run)";
  86751. }
  86752. scanLineArray[index++] = b;
  86753. if (--count > 0) {
  86754. for (var j = 0; j < count; j++) {
  86755. scanLineArray[index++] = uint8array[dataIndex++];
  86756. }
  86757. }
  86758. }
  86759. }
  86760. }
  86761. // now convert data from buffer into floats
  86762. for (i = 0; i < scanline_width; i++) {
  86763. a = scanLineArray[i];
  86764. b = scanLineArray[i + scanline_width];
  86765. c = scanLineArray[i + 2 * scanline_width];
  86766. d = scanLineArray[i + 3 * scanline_width];
  86767. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  86768. }
  86769. num_scanlines--;
  86770. }
  86771. return resultArray;
  86772. };
  86773. return HDRTools;
  86774. }());
  86775. BABYLON.HDRTools = HDRTools;
  86776. })(BABYLON || (BABYLON = {}));
  86777. //# sourceMappingURL=babylon.hdr.js.map
  86778. var BABYLON;
  86779. (function (BABYLON) {
  86780. /**
  86781. * This represents a texture coming from an HDR input.
  86782. *
  86783. * The only supported format is currently panorama picture stored in RGBE format.
  86784. * Example of such files can be found on HDRLib: http://hdrlib.com/
  86785. */
  86786. var HDRCubeTexture = /** @class */ (function (_super) {
  86787. __extends(HDRCubeTexture, _super);
  86788. /**
  86789. * Instantiates an HDRTexture from the following parameters.
  86790. *
  86791. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  86792. * @param scene The scene the texture will be used in
  86793. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  86794. * @param noMipmap Forces to not generate the mipmap if true
  86795. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  86796. * @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)
  86797. * @param reserved Reserved flag for internal use.
  86798. */
  86799. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  86800. if (noMipmap === void 0) { noMipmap = false; }
  86801. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86802. if (gammaSpace === void 0) { gammaSpace = false; }
  86803. if (reserved === void 0) { reserved = false; }
  86804. if (onLoad === void 0) { onLoad = null; }
  86805. if (onError === void 0) { onError = null; }
  86806. var _this = _super.call(this, scene) || this;
  86807. _this._generateHarmonics = true;
  86808. _this._onLoad = null;
  86809. _this._onError = null;
  86810. /**
  86811. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  86812. */
  86813. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  86814. _this._isBlocking = true;
  86815. _this._rotationY = 0;
  86816. /**
  86817. * Gets or sets the center of the bounding box associated with the cube texture
  86818. * It must define where the camera used to render the texture was set
  86819. */
  86820. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  86821. if (!url) {
  86822. return _this;
  86823. }
  86824. _this.name = url;
  86825. _this.url = url;
  86826. _this.hasAlpha = false;
  86827. _this.isCube = true;
  86828. _this._textureMatrix = BABYLON.Matrix.Identity();
  86829. _this._onLoad = onLoad;
  86830. _this._onError = onError;
  86831. _this.gammaSpace = gammaSpace;
  86832. _this._noMipmap = noMipmap;
  86833. _this._size = size;
  86834. _this._texture = _this._getFromCache(url, _this._noMipmap);
  86835. if (!_this._texture) {
  86836. if (!scene.useDelayedTextureLoading) {
  86837. _this.loadTexture();
  86838. }
  86839. else {
  86840. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  86841. }
  86842. }
  86843. return _this;
  86844. }
  86845. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  86846. /**
  86847. * Gets wether or not the texture is blocking during loading.
  86848. */
  86849. get: function () {
  86850. return this._isBlocking;
  86851. },
  86852. /**
  86853. * Sets wether or not the texture is blocking during loading.
  86854. */
  86855. set: function (value) {
  86856. this._isBlocking = value;
  86857. },
  86858. enumerable: true,
  86859. configurable: true
  86860. });
  86861. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  86862. /**
  86863. * Gets texture matrix rotation angle around Y axis radians.
  86864. */
  86865. get: function () {
  86866. return this._rotationY;
  86867. },
  86868. /**
  86869. * Sets texture matrix rotation angle around Y axis in radians.
  86870. */
  86871. set: function (value) {
  86872. this._rotationY = value;
  86873. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  86874. },
  86875. enumerable: true,
  86876. configurable: true
  86877. });
  86878. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  86879. get: function () {
  86880. return this._boundingBoxSize;
  86881. },
  86882. /**
  86883. * Gets or sets the size of the bounding box associated with the cube texture
  86884. * When defined, the cubemap will switch to local mode
  86885. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  86886. * @example https://www.babylonjs-playground.com/#RNASML
  86887. */
  86888. set: function (value) {
  86889. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  86890. return;
  86891. }
  86892. this._boundingBoxSize = value;
  86893. var scene = this.getScene();
  86894. if (scene) {
  86895. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  86896. }
  86897. },
  86898. enumerable: true,
  86899. configurable: true
  86900. });
  86901. /**
  86902. * Occurs when the file is raw .hdr file.
  86903. */
  86904. HDRCubeTexture.prototype.loadTexture = function () {
  86905. var _this = this;
  86906. var callback = function (buffer) {
  86907. _this.lodGenerationOffset = 0.0;
  86908. _this.lodGenerationScale = 0.8;
  86909. var scene = _this.getScene();
  86910. if (!scene) {
  86911. return null;
  86912. }
  86913. // Extract the raw linear data.
  86914. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  86915. // Generate harmonics if needed.
  86916. if (_this._generateHarmonics) {
  86917. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  86918. _this.sphericalPolynomial = sphericalPolynomial;
  86919. }
  86920. var results = [];
  86921. var byteArray = null;
  86922. // Push each faces.
  86923. for (var j = 0; j < 6; j++) {
  86924. // Create uintarray fallback.
  86925. if (!scene.getEngine().getCaps().textureFloat) {
  86926. // 3 channels of 1 bytes per pixel in bytes.
  86927. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  86928. byteArray = new Uint8Array(byteBuffer);
  86929. }
  86930. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  86931. // If special cases.
  86932. if (_this.gammaSpace || byteArray) {
  86933. for (var i = 0; i < _this._size * _this._size; i++) {
  86934. // Put in gamma space if requested.
  86935. if (_this.gammaSpace) {
  86936. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  86937. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  86938. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  86939. }
  86940. // Convert to int texture for fallback.
  86941. if (byteArray) {
  86942. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  86943. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  86944. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  86945. // May use luminance instead if the result is not accurate.
  86946. var max = Math.max(Math.max(r, g), b);
  86947. if (max > 255) {
  86948. var scale = 255 / max;
  86949. r *= scale;
  86950. g *= scale;
  86951. b *= scale;
  86952. }
  86953. byteArray[(i * 3) + 0] = r;
  86954. byteArray[(i * 3) + 1] = g;
  86955. byteArray[(i * 3) + 2] = b;
  86956. }
  86957. }
  86958. }
  86959. if (byteArray) {
  86960. results.push(byteArray);
  86961. }
  86962. else {
  86963. results.push(dataFace);
  86964. }
  86965. }
  86966. return results;
  86967. };
  86968. var scene = this.getScene();
  86969. if (scene) {
  86970. 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);
  86971. }
  86972. };
  86973. HDRCubeTexture.prototype.clone = function () {
  86974. var scene = this.getScene();
  86975. if (!scene) {
  86976. return this;
  86977. }
  86978. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  86979. // Base texture
  86980. newTexture.level = this.level;
  86981. newTexture.wrapU = this.wrapU;
  86982. newTexture.wrapV = this.wrapV;
  86983. newTexture.coordinatesIndex = this.coordinatesIndex;
  86984. newTexture.coordinatesMode = this.coordinatesMode;
  86985. return newTexture;
  86986. };
  86987. // Methods
  86988. HDRCubeTexture.prototype.delayLoad = function () {
  86989. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  86990. return;
  86991. }
  86992. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  86993. this._texture = this._getFromCache(this.url, this._noMipmap);
  86994. if (!this._texture) {
  86995. this.loadTexture();
  86996. }
  86997. };
  86998. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  86999. return this._textureMatrix;
  87000. };
  87001. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  87002. this._textureMatrix = value;
  87003. };
  87004. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  87005. var texture = null;
  87006. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  87007. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  87008. texture.name = parsedTexture.name;
  87009. texture.hasAlpha = parsedTexture.hasAlpha;
  87010. texture.level = parsedTexture.level;
  87011. texture.coordinatesMode = parsedTexture.coordinatesMode;
  87012. texture.isBlocking = parsedTexture.isBlocking;
  87013. }
  87014. if (texture) {
  87015. if (parsedTexture.boundingBoxPosition) {
  87016. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  87017. }
  87018. if (parsedTexture.boundingBoxSize) {
  87019. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  87020. }
  87021. if (parsedTexture.rotationY) {
  87022. texture.rotationY = parsedTexture.rotationY;
  87023. }
  87024. }
  87025. return texture;
  87026. };
  87027. HDRCubeTexture.prototype.serialize = function () {
  87028. if (!this.name) {
  87029. return null;
  87030. }
  87031. var serializationObject = {};
  87032. serializationObject.name = this.name;
  87033. serializationObject.hasAlpha = this.hasAlpha;
  87034. serializationObject.isCube = true;
  87035. serializationObject.level = this.level;
  87036. serializationObject.size = this._size;
  87037. serializationObject.coordinatesMode = this.coordinatesMode;
  87038. serializationObject.useInGammaSpace = this.gammaSpace;
  87039. serializationObject.generateHarmonics = this._generateHarmonics;
  87040. serializationObject.customType = "BABYLON.HDRCubeTexture";
  87041. serializationObject.noMipmap = this._noMipmap;
  87042. serializationObject.isBlocking = this._isBlocking;
  87043. serializationObject.rotationY = this._rotationY;
  87044. return serializationObject;
  87045. };
  87046. HDRCubeTexture._facesMapping = [
  87047. "right",
  87048. "left",
  87049. "up",
  87050. "down",
  87051. "front",
  87052. "back"
  87053. ];
  87054. return HDRCubeTexture;
  87055. }(BABYLON.BaseTexture));
  87056. BABYLON.HDRCubeTexture = HDRCubeTexture;
  87057. })(BABYLON || (BABYLON = {}));
  87058. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  87059. var BABYLON;
  87060. (function (BABYLON) {
  87061. /**
  87062. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  87063. */
  87064. var PanoramaToCubeMapTools = /** @class */ (function () {
  87065. function PanoramaToCubeMapTools() {
  87066. }
  87067. /**
  87068. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  87069. *
  87070. * @param float32Array The source data.
  87071. * @param inputWidth The width of the input panorama.
  87072. * @param inputhHeight The height of the input panorama.
  87073. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  87074. * @return The cubemap data
  87075. */
  87076. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  87077. if (!float32Array) {
  87078. throw "ConvertPanoramaToCubemap: input cannot be null";
  87079. }
  87080. if (float32Array.length != inputWidth * inputHeight * 3) {
  87081. throw "ConvertPanoramaToCubemap: input size is wrong";
  87082. }
  87083. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  87084. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  87085. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  87086. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  87087. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  87088. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  87089. return {
  87090. front: textureFront,
  87091. back: textureBack,
  87092. left: textureLeft,
  87093. right: textureRight,
  87094. up: textureUp,
  87095. down: textureDown,
  87096. size: size,
  87097. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87098. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  87099. gammaSpace: false,
  87100. };
  87101. };
  87102. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  87103. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  87104. var textureArray = new Float32Array(buffer);
  87105. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  87106. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  87107. var dy = 1 / texSize;
  87108. var fy = 0;
  87109. for (var y = 0; y < texSize; y++) {
  87110. var xv1 = faceData[0];
  87111. var xv2 = faceData[2];
  87112. for (var x = 0; x < texSize; x++) {
  87113. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  87114. v.normalize();
  87115. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  87116. // 3 channels per pixels
  87117. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  87118. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  87119. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  87120. xv1 = xv1.add(rotDX1);
  87121. xv2 = xv2.add(rotDX2);
  87122. }
  87123. fy += dy;
  87124. }
  87125. return textureArray;
  87126. };
  87127. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  87128. var theta = Math.atan2(vDir.z, vDir.x);
  87129. var phi = Math.acos(vDir.y);
  87130. while (theta < -Math.PI)
  87131. theta += 2 * Math.PI;
  87132. while (theta > Math.PI)
  87133. theta -= 2 * Math.PI;
  87134. var dx = theta / Math.PI;
  87135. var dy = phi / Math.PI;
  87136. // recenter.
  87137. dx = dx * 0.5 + 0.5;
  87138. var px = Math.round(dx * inputWidth);
  87139. if (px < 0)
  87140. px = 0;
  87141. else if (px >= inputWidth)
  87142. px = inputWidth - 1;
  87143. var py = Math.round(dy * inputHeight);
  87144. if (py < 0)
  87145. py = 0;
  87146. else if (py >= inputHeight)
  87147. py = inputHeight - 1;
  87148. var inputY = (inputHeight - py - 1);
  87149. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  87150. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  87151. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  87152. return {
  87153. r: r,
  87154. g: g,
  87155. b: b
  87156. };
  87157. };
  87158. PanoramaToCubeMapTools.FACE_FRONT = [
  87159. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  87160. new BABYLON.Vector3(1.0, -1.0, -1.0),
  87161. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  87162. new BABYLON.Vector3(1.0, 1.0, -1.0)
  87163. ];
  87164. PanoramaToCubeMapTools.FACE_BACK = [
  87165. new BABYLON.Vector3(1.0, -1.0, 1.0),
  87166. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  87167. new BABYLON.Vector3(1.0, 1.0, 1.0),
  87168. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  87169. ];
  87170. PanoramaToCubeMapTools.FACE_RIGHT = [
  87171. new BABYLON.Vector3(1.0, -1.0, -1.0),
  87172. new BABYLON.Vector3(1.0, -1.0, 1.0),
  87173. new BABYLON.Vector3(1.0, 1.0, -1.0),
  87174. new BABYLON.Vector3(1.0, 1.0, 1.0)
  87175. ];
  87176. PanoramaToCubeMapTools.FACE_LEFT = [
  87177. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  87178. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  87179. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  87180. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  87181. ];
  87182. PanoramaToCubeMapTools.FACE_DOWN = [
  87183. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  87184. new BABYLON.Vector3(1.0, 1.0, -1.0),
  87185. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  87186. new BABYLON.Vector3(1.0, 1.0, 1.0)
  87187. ];
  87188. PanoramaToCubeMapTools.FACE_UP = [
  87189. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  87190. new BABYLON.Vector3(1.0, -1.0, 1.0),
  87191. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  87192. new BABYLON.Vector3(1.0, -1.0, -1.0)
  87193. ];
  87194. return PanoramaToCubeMapTools;
  87195. }());
  87196. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  87197. })(BABYLON || (BABYLON = {}));
  87198. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  87199. var BABYLON;
  87200. (function (BABYLON) {
  87201. var IndexedVector2 = /** @class */ (function (_super) {
  87202. __extends(IndexedVector2, _super);
  87203. function IndexedVector2(original, index) {
  87204. var _this = _super.call(this, original.x, original.y) || this;
  87205. _this.index = index;
  87206. return _this;
  87207. }
  87208. return IndexedVector2;
  87209. }(BABYLON.Vector2));
  87210. var PolygonPoints = /** @class */ (function () {
  87211. function PolygonPoints() {
  87212. this.elements = new Array();
  87213. }
  87214. PolygonPoints.prototype.add = function (originalPoints) {
  87215. var _this = this;
  87216. var result = new Array();
  87217. originalPoints.forEach(function (point) {
  87218. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  87219. var newPoint = new IndexedVector2(point, _this.elements.length);
  87220. result.push(newPoint);
  87221. _this.elements.push(newPoint);
  87222. }
  87223. });
  87224. return result;
  87225. };
  87226. PolygonPoints.prototype.computeBounds = function () {
  87227. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  87228. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  87229. this.elements.forEach(function (point) {
  87230. // x
  87231. if (point.x < lmin.x) {
  87232. lmin.x = point.x;
  87233. }
  87234. else if (point.x > lmax.x) {
  87235. lmax.x = point.x;
  87236. }
  87237. // y
  87238. if (point.y < lmin.y) {
  87239. lmin.y = point.y;
  87240. }
  87241. else if (point.y > lmax.y) {
  87242. lmax.y = point.y;
  87243. }
  87244. });
  87245. return {
  87246. min: lmin,
  87247. max: lmax,
  87248. width: lmax.x - lmin.x,
  87249. height: lmax.y - lmin.y
  87250. };
  87251. };
  87252. return PolygonPoints;
  87253. }());
  87254. var Polygon = /** @class */ (function () {
  87255. function Polygon() {
  87256. }
  87257. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  87258. return [
  87259. new BABYLON.Vector2(xmin, ymin),
  87260. new BABYLON.Vector2(xmax, ymin),
  87261. new BABYLON.Vector2(xmax, ymax),
  87262. new BABYLON.Vector2(xmin, ymax)
  87263. ];
  87264. };
  87265. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  87266. if (cx === void 0) { cx = 0; }
  87267. if (cy === void 0) { cy = 0; }
  87268. if (numberOfSides === void 0) { numberOfSides = 32; }
  87269. var result = new Array();
  87270. var angle = 0;
  87271. var increment = (Math.PI * 2) / numberOfSides;
  87272. for (var i = 0; i < numberOfSides; i++) {
  87273. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  87274. angle -= increment;
  87275. }
  87276. return result;
  87277. };
  87278. Polygon.Parse = function (input) {
  87279. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  87280. var i, result = [];
  87281. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  87282. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  87283. }
  87284. return result;
  87285. };
  87286. Polygon.StartingAt = function (x, y) {
  87287. return BABYLON.Path2.StartingAt(x, y);
  87288. };
  87289. return Polygon;
  87290. }());
  87291. BABYLON.Polygon = Polygon;
  87292. var PolygonMeshBuilder = /** @class */ (function () {
  87293. function PolygonMeshBuilder(name, contours, scene) {
  87294. this._points = new PolygonPoints();
  87295. this._outlinepoints = new PolygonPoints();
  87296. this._holes = new Array();
  87297. this._epoints = new Array();
  87298. this._eholes = new Array();
  87299. this._name = name;
  87300. this._scene = scene;
  87301. var points;
  87302. if (contours instanceof BABYLON.Path2) {
  87303. points = contours.getPoints();
  87304. }
  87305. else {
  87306. points = contours;
  87307. }
  87308. this._addToepoint(points);
  87309. this._points.add(points);
  87310. this._outlinepoints.add(points);
  87311. if (typeof earcut === 'undefined') {
  87312. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  87313. }
  87314. }
  87315. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  87316. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  87317. var p = points_1[_i];
  87318. this._epoints.push(p.x, p.y);
  87319. }
  87320. };
  87321. PolygonMeshBuilder.prototype.addHole = function (hole) {
  87322. this._points.add(hole);
  87323. var holepoints = new PolygonPoints();
  87324. holepoints.add(hole);
  87325. this._holes.push(holepoints);
  87326. this._eholes.push(this._epoints.length / 2);
  87327. this._addToepoint(hole);
  87328. return this;
  87329. };
  87330. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  87331. var _this = this;
  87332. if (updatable === void 0) { updatable = false; }
  87333. if (depth === void 0) { depth = 0; }
  87334. var result = new BABYLON.Mesh(this._name, this._scene);
  87335. var normals = new Array();
  87336. var positions = new Array();
  87337. var uvs = new Array();
  87338. var bounds = this._points.computeBounds();
  87339. this._points.elements.forEach(function (p) {
  87340. normals.push(0, 1.0, 0);
  87341. positions.push(p.x, 0, p.y);
  87342. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  87343. });
  87344. var indices = new Array();
  87345. var res = earcut(this._epoints, this._eholes, 2);
  87346. for (var i = 0; i < res.length; i++) {
  87347. indices.push(res[i]);
  87348. }
  87349. if (depth > 0) {
  87350. var positionscount = (positions.length / 3); //get the current pointcount
  87351. this._points.elements.forEach(function (p) {
  87352. normals.push(0, -1.0, 0);
  87353. positions.push(p.x, -depth, p.y);
  87354. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  87355. });
  87356. var totalCount = indices.length;
  87357. for (var i = 0; i < totalCount; i += 3) {
  87358. var i0 = indices[i + 0];
  87359. var i1 = indices[i + 1];
  87360. var i2 = indices[i + 2];
  87361. indices.push(i2 + positionscount);
  87362. indices.push(i1 + positionscount);
  87363. indices.push(i0 + positionscount);
  87364. }
  87365. //Add the sides
  87366. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  87367. this._holes.forEach(function (hole) {
  87368. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  87369. });
  87370. }
  87371. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  87372. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  87373. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  87374. result.setIndices(indices);
  87375. return result;
  87376. };
  87377. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  87378. var StartIndex = positions.length / 3;
  87379. var ulength = 0;
  87380. for (var i = 0; i < points.elements.length; i++) {
  87381. var p = points.elements[i];
  87382. var p1;
  87383. if ((i + 1) > points.elements.length - 1) {
  87384. p1 = points.elements[0];
  87385. }
  87386. else {
  87387. p1 = points.elements[i + 1];
  87388. }
  87389. positions.push(p.x, 0, p.y);
  87390. positions.push(p.x, -depth, p.y);
  87391. positions.push(p1.x, 0, p1.y);
  87392. positions.push(p1.x, -depth, p1.y);
  87393. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  87394. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  87395. var v3 = v2.subtract(v1);
  87396. var v4 = new BABYLON.Vector3(0, 1, 0);
  87397. var vn = BABYLON.Vector3.Cross(v3, v4);
  87398. vn = vn.normalize();
  87399. uvs.push(ulength / bounds.width, 0);
  87400. uvs.push(ulength / bounds.width, 1);
  87401. ulength += v3.length();
  87402. uvs.push((ulength / bounds.width), 0);
  87403. uvs.push((ulength / bounds.width), 1);
  87404. if (!flip) {
  87405. normals.push(-vn.x, -vn.y, -vn.z);
  87406. normals.push(-vn.x, -vn.y, -vn.z);
  87407. normals.push(-vn.x, -vn.y, -vn.z);
  87408. normals.push(-vn.x, -vn.y, -vn.z);
  87409. indices.push(StartIndex);
  87410. indices.push(StartIndex + 1);
  87411. indices.push(StartIndex + 2);
  87412. indices.push(StartIndex + 1);
  87413. indices.push(StartIndex + 3);
  87414. indices.push(StartIndex + 2);
  87415. }
  87416. else {
  87417. normals.push(vn.x, vn.y, vn.z);
  87418. normals.push(vn.x, vn.y, vn.z);
  87419. normals.push(vn.x, vn.y, vn.z);
  87420. normals.push(vn.x, vn.y, vn.z);
  87421. indices.push(StartIndex);
  87422. indices.push(StartIndex + 2);
  87423. indices.push(StartIndex + 1);
  87424. indices.push(StartIndex + 1);
  87425. indices.push(StartIndex + 2);
  87426. indices.push(StartIndex + 3);
  87427. }
  87428. StartIndex += 4;
  87429. }
  87430. ;
  87431. };
  87432. return PolygonMeshBuilder;
  87433. }());
  87434. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  87435. })(BABYLON || (BABYLON = {}));
  87436. //# sourceMappingURL=babylon.polygonMesh.js.map
  87437. var BABYLON;
  87438. (function (BABYLON) {
  87439. // Unique ID when we import meshes from Babylon to CSG
  87440. var currentCSGMeshId = 0;
  87441. // # class Vertex
  87442. // Represents a vertex of a polygon. Use your own vertex class instead of this
  87443. // one to provide additional features like texture coordinates and vertex
  87444. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  87445. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  87446. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  87447. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  87448. // is not used anywhere else.
  87449. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  87450. var Vertex = /** @class */ (function () {
  87451. function Vertex(pos, normal, uv) {
  87452. this.pos = pos;
  87453. this.normal = normal;
  87454. this.uv = uv;
  87455. }
  87456. Vertex.prototype.clone = function () {
  87457. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  87458. };
  87459. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  87460. // orientation of a polygon is flipped.
  87461. Vertex.prototype.flip = function () {
  87462. this.normal = this.normal.scale(-1);
  87463. };
  87464. // Create a new vertex between this vertex and `other` by linearly
  87465. // interpolating all properties using a parameter of `t`. Subclasses should
  87466. // override this to interpolate additional properties.
  87467. Vertex.prototype.interpolate = function (other, t) {
  87468. 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));
  87469. };
  87470. return Vertex;
  87471. }());
  87472. // # class Plane
  87473. // Represents a plane in 3D space.
  87474. var Plane = /** @class */ (function () {
  87475. function Plane(normal, w) {
  87476. this.normal = normal;
  87477. this.w = w;
  87478. }
  87479. Plane.FromPoints = function (a, b, c) {
  87480. var v0 = c.subtract(a);
  87481. var v1 = b.subtract(a);
  87482. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  87483. return null;
  87484. }
  87485. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  87486. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  87487. };
  87488. Plane.prototype.clone = function () {
  87489. return new Plane(this.normal.clone(), this.w);
  87490. };
  87491. Plane.prototype.flip = function () {
  87492. this.normal.scaleInPlace(-1);
  87493. this.w = -this.w;
  87494. };
  87495. // Split `polygon` by this plane if needed, then put the polygon or polygon
  87496. // fragments in the appropriate lists. Coplanar polygons go into either
  87497. // `coplanarFront` or `coplanarBack` depending on their orientation with
  87498. // respect to this plane. Polygons in front or in back of this plane go into
  87499. // either `front` or `back`.
  87500. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  87501. var COPLANAR = 0;
  87502. var FRONT = 1;
  87503. var BACK = 2;
  87504. var SPANNING = 3;
  87505. // Classify each point as well as the entire polygon into one of the above
  87506. // four classes.
  87507. var polygonType = 0;
  87508. var types = [];
  87509. var i;
  87510. var t;
  87511. for (i = 0; i < polygon.vertices.length; i++) {
  87512. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  87513. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  87514. polygonType |= type;
  87515. types.push(type);
  87516. }
  87517. // Put the polygon in the correct list, splitting it when necessary.
  87518. switch (polygonType) {
  87519. case COPLANAR:
  87520. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  87521. break;
  87522. case FRONT:
  87523. front.push(polygon);
  87524. break;
  87525. case BACK:
  87526. back.push(polygon);
  87527. break;
  87528. case SPANNING:
  87529. var f = [], b = [];
  87530. for (i = 0; i < polygon.vertices.length; i++) {
  87531. var j = (i + 1) % polygon.vertices.length;
  87532. var ti = types[i], tj = types[j];
  87533. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  87534. if (ti !== BACK)
  87535. f.push(vi);
  87536. if (ti !== FRONT)
  87537. b.push(ti !== BACK ? vi.clone() : vi);
  87538. if ((ti | tj) === SPANNING) {
  87539. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  87540. var v = vi.interpolate(vj, t);
  87541. f.push(v);
  87542. b.push(v.clone());
  87543. }
  87544. }
  87545. var poly;
  87546. if (f.length >= 3) {
  87547. poly = new Polygon(f, polygon.shared);
  87548. if (poly.plane)
  87549. front.push(poly);
  87550. }
  87551. if (b.length >= 3) {
  87552. poly = new Polygon(b, polygon.shared);
  87553. if (poly.plane)
  87554. back.push(poly);
  87555. }
  87556. break;
  87557. }
  87558. };
  87559. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  87560. // point is on the plane.
  87561. Plane.EPSILON = 1e-5;
  87562. return Plane;
  87563. }());
  87564. // # class Polygon
  87565. // Represents a convex polygon. The vertices used to initialize a polygon must
  87566. // be coplanar and form a convex loop.
  87567. //
  87568. // Each convex polygon has a `shared` property, which is shared between all
  87569. // polygons that are clones of each other or were split from the same polygon.
  87570. // This can be used to define per-polygon properties (such as surface color).
  87571. var Polygon = /** @class */ (function () {
  87572. function Polygon(vertices, shared) {
  87573. this.vertices = vertices;
  87574. this.shared = shared;
  87575. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  87576. }
  87577. Polygon.prototype.clone = function () {
  87578. var vertices = this.vertices.map(function (v) { return v.clone(); });
  87579. return new Polygon(vertices, this.shared);
  87580. };
  87581. Polygon.prototype.flip = function () {
  87582. this.vertices.reverse().map(function (v) { v.flip(); });
  87583. this.plane.flip();
  87584. };
  87585. return Polygon;
  87586. }());
  87587. // # class Node
  87588. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  87589. // by picking a polygon to split along. That polygon (and all other coplanar
  87590. // polygons) are added directly to that node and the other polygons are added to
  87591. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  87592. // no distinction between internal and leaf nodes.
  87593. var Node = /** @class */ (function () {
  87594. function Node(polygons) {
  87595. this.plane = null;
  87596. this.front = null;
  87597. this.back = null;
  87598. this.polygons = new Array();
  87599. if (polygons) {
  87600. this.build(polygons);
  87601. }
  87602. }
  87603. Node.prototype.clone = function () {
  87604. var node = new Node();
  87605. node.plane = this.plane && this.plane.clone();
  87606. node.front = this.front && this.front.clone();
  87607. node.back = this.back && this.back.clone();
  87608. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  87609. return node;
  87610. };
  87611. // Convert solid space to empty space and empty space to solid space.
  87612. Node.prototype.invert = function () {
  87613. for (var i = 0; i < this.polygons.length; i++) {
  87614. this.polygons[i].flip();
  87615. }
  87616. if (this.plane) {
  87617. this.plane.flip();
  87618. }
  87619. if (this.front) {
  87620. this.front.invert();
  87621. }
  87622. if (this.back) {
  87623. this.back.invert();
  87624. }
  87625. var temp = this.front;
  87626. this.front = this.back;
  87627. this.back = temp;
  87628. };
  87629. // Recursively remove all polygons in `polygons` that are inside this BSP
  87630. // tree.
  87631. Node.prototype.clipPolygons = function (polygons) {
  87632. if (!this.plane)
  87633. return polygons.slice();
  87634. var front = new Array(), back = new Array();
  87635. for (var i = 0; i < polygons.length; i++) {
  87636. this.plane.splitPolygon(polygons[i], front, back, front, back);
  87637. }
  87638. if (this.front) {
  87639. front = this.front.clipPolygons(front);
  87640. }
  87641. if (this.back) {
  87642. back = this.back.clipPolygons(back);
  87643. }
  87644. else {
  87645. back = [];
  87646. }
  87647. return front.concat(back);
  87648. };
  87649. // Remove all polygons in this BSP tree that are inside the other BSP tree
  87650. // `bsp`.
  87651. Node.prototype.clipTo = function (bsp) {
  87652. this.polygons = bsp.clipPolygons(this.polygons);
  87653. if (this.front)
  87654. this.front.clipTo(bsp);
  87655. if (this.back)
  87656. this.back.clipTo(bsp);
  87657. };
  87658. // Return a list of all polygons in this BSP tree.
  87659. Node.prototype.allPolygons = function () {
  87660. var polygons = this.polygons.slice();
  87661. if (this.front)
  87662. polygons = polygons.concat(this.front.allPolygons());
  87663. if (this.back)
  87664. polygons = polygons.concat(this.back.allPolygons());
  87665. return polygons;
  87666. };
  87667. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  87668. // new polygons are filtered down to the bottom of the tree and become new
  87669. // nodes there. Each set of polygons is partitioned using the first polygon
  87670. // (no heuristic is used to pick a good split).
  87671. Node.prototype.build = function (polygons) {
  87672. if (!polygons.length)
  87673. return;
  87674. if (!this.plane)
  87675. this.plane = polygons[0].plane.clone();
  87676. var front = new Array(), back = new Array();
  87677. for (var i = 0; i < polygons.length; i++) {
  87678. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  87679. }
  87680. if (front.length) {
  87681. if (!this.front)
  87682. this.front = new Node();
  87683. this.front.build(front);
  87684. }
  87685. if (back.length) {
  87686. if (!this.back)
  87687. this.back = new Node();
  87688. this.back.build(back);
  87689. }
  87690. };
  87691. return Node;
  87692. }());
  87693. var CSG = /** @class */ (function () {
  87694. function CSG() {
  87695. this.polygons = new Array();
  87696. }
  87697. // Convert BABYLON.Mesh to BABYLON.CSG
  87698. CSG.FromMesh = function (mesh) {
  87699. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  87700. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  87701. if (mesh instanceof BABYLON.Mesh) {
  87702. mesh.computeWorldMatrix(true);
  87703. matrix = mesh.getWorldMatrix();
  87704. meshPosition = mesh.position.clone();
  87705. meshRotation = mesh.rotation.clone();
  87706. if (mesh.rotationQuaternion) {
  87707. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  87708. }
  87709. meshScaling = mesh.scaling.clone();
  87710. }
  87711. else {
  87712. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  87713. }
  87714. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  87715. var subMeshes = mesh.subMeshes;
  87716. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  87717. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  87718. vertices = [];
  87719. for (var j = 0; j < 3; j++) {
  87720. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  87721. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  87722. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  87723. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  87724. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  87725. vertex = new Vertex(position, normal, uv);
  87726. vertices.push(vertex);
  87727. }
  87728. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  87729. // To handle the case of degenerated triangle
  87730. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  87731. if (polygon.plane)
  87732. polygons.push(polygon);
  87733. }
  87734. }
  87735. var csg = CSG.FromPolygons(polygons);
  87736. csg.matrix = matrix;
  87737. csg.position = meshPosition;
  87738. csg.rotation = meshRotation;
  87739. csg.scaling = meshScaling;
  87740. csg.rotationQuaternion = meshRotationQuaternion;
  87741. currentCSGMeshId++;
  87742. return csg;
  87743. };
  87744. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  87745. CSG.FromPolygons = function (polygons) {
  87746. var csg = new CSG();
  87747. csg.polygons = polygons;
  87748. return csg;
  87749. };
  87750. CSG.prototype.clone = function () {
  87751. var csg = new CSG();
  87752. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  87753. csg.copyTransformAttributes(this);
  87754. return csg;
  87755. };
  87756. CSG.prototype.union = function (csg) {
  87757. var a = new Node(this.clone().polygons);
  87758. var b = new Node(csg.clone().polygons);
  87759. a.clipTo(b);
  87760. b.clipTo(a);
  87761. b.invert();
  87762. b.clipTo(a);
  87763. b.invert();
  87764. a.build(b.allPolygons());
  87765. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  87766. };
  87767. CSG.prototype.unionInPlace = function (csg) {
  87768. var a = new Node(this.polygons);
  87769. var b = new Node(csg.polygons);
  87770. a.clipTo(b);
  87771. b.clipTo(a);
  87772. b.invert();
  87773. b.clipTo(a);
  87774. b.invert();
  87775. a.build(b.allPolygons());
  87776. this.polygons = a.allPolygons();
  87777. };
  87778. CSG.prototype.subtract = function (csg) {
  87779. var a = new Node(this.clone().polygons);
  87780. var b = new Node(csg.clone().polygons);
  87781. a.invert();
  87782. a.clipTo(b);
  87783. b.clipTo(a);
  87784. b.invert();
  87785. b.clipTo(a);
  87786. b.invert();
  87787. a.build(b.allPolygons());
  87788. a.invert();
  87789. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  87790. };
  87791. CSG.prototype.subtractInPlace = function (csg) {
  87792. var a = new Node(this.polygons);
  87793. var b = new Node(csg.polygons);
  87794. a.invert();
  87795. a.clipTo(b);
  87796. b.clipTo(a);
  87797. b.invert();
  87798. b.clipTo(a);
  87799. b.invert();
  87800. a.build(b.allPolygons());
  87801. a.invert();
  87802. this.polygons = a.allPolygons();
  87803. };
  87804. CSG.prototype.intersect = function (csg) {
  87805. var a = new Node(this.clone().polygons);
  87806. var b = new Node(csg.clone().polygons);
  87807. a.invert();
  87808. b.clipTo(a);
  87809. b.invert();
  87810. a.clipTo(b);
  87811. b.clipTo(a);
  87812. a.build(b.allPolygons());
  87813. a.invert();
  87814. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  87815. };
  87816. CSG.prototype.intersectInPlace = function (csg) {
  87817. var a = new Node(this.polygons);
  87818. var b = new Node(csg.polygons);
  87819. a.invert();
  87820. b.clipTo(a);
  87821. b.invert();
  87822. a.clipTo(b);
  87823. b.clipTo(a);
  87824. a.build(b.allPolygons());
  87825. a.invert();
  87826. this.polygons = a.allPolygons();
  87827. };
  87828. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  87829. // not modified.
  87830. CSG.prototype.inverse = function () {
  87831. var csg = this.clone();
  87832. csg.inverseInPlace();
  87833. return csg;
  87834. };
  87835. CSG.prototype.inverseInPlace = function () {
  87836. this.polygons.map(function (p) { p.flip(); });
  87837. };
  87838. // This is used to keep meshes transformations so they can be restored
  87839. // when we build back a Babylon Mesh
  87840. // NB : All CSG operations are performed in world coordinates
  87841. CSG.prototype.copyTransformAttributes = function (csg) {
  87842. this.matrix = csg.matrix;
  87843. this.position = csg.position;
  87844. this.rotation = csg.rotation;
  87845. this.scaling = csg.scaling;
  87846. this.rotationQuaternion = csg.rotationQuaternion;
  87847. return this;
  87848. };
  87849. // Build Raw mesh from CSG
  87850. // Coordinates here are in world space
  87851. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  87852. var matrix = this.matrix.clone();
  87853. matrix.invert();
  87854. 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;
  87855. if (keepSubMeshes) {
  87856. // Sort Polygons, since subMeshes are indices range
  87857. polygons.sort(function (a, b) {
  87858. if (a.shared.meshId === b.shared.meshId) {
  87859. return a.shared.subMeshId - b.shared.subMeshId;
  87860. }
  87861. else {
  87862. return a.shared.meshId - b.shared.meshId;
  87863. }
  87864. });
  87865. }
  87866. for (var i = 0, il = polygons.length; i < il; i++) {
  87867. polygon = polygons[i];
  87868. // Building SubMeshes
  87869. if (!subMesh_dict[polygon.shared.meshId]) {
  87870. subMesh_dict[polygon.shared.meshId] = {};
  87871. }
  87872. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  87873. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  87874. indexStart: +Infinity,
  87875. indexEnd: -Infinity,
  87876. materialIndex: polygon.shared.materialIndex
  87877. };
  87878. }
  87879. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  87880. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  87881. polygonIndices[0] = 0;
  87882. polygonIndices[1] = j - 1;
  87883. polygonIndices[2] = j;
  87884. for (var k = 0; k < 3; k++) {
  87885. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  87886. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  87887. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  87888. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  87889. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  87890. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  87891. // Check if 2 points can be merged
  87892. if (!(typeof vertex_idx !== 'undefined' &&
  87893. normals[vertex_idx * 3] === localNormal.x &&
  87894. normals[vertex_idx * 3 + 1] === localNormal.y &&
  87895. normals[vertex_idx * 3 + 2] === localNormal.z &&
  87896. uvs[vertex_idx * 2] === uv.x &&
  87897. uvs[vertex_idx * 2 + 1] === uv.y)) {
  87898. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  87899. uvs.push(uv.x, uv.y);
  87900. normals.push(normal.x, normal.y, normal.z);
  87901. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  87902. }
  87903. indices.push(vertex_idx);
  87904. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  87905. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  87906. currentIndex++;
  87907. }
  87908. }
  87909. }
  87910. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  87911. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  87912. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  87913. mesh.setIndices(indices, null);
  87914. if (keepSubMeshes) {
  87915. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  87916. var materialIndexOffset = 0, materialMaxIndex;
  87917. mesh.subMeshes = new Array();
  87918. for (var m in subMesh_dict) {
  87919. materialMaxIndex = -1;
  87920. for (var sm in subMesh_dict[m]) {
  87921. subMesh_obj = subMesh_dict[m][sm];
  87922. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  87923. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  87924. }
  87925. materialIndexOffset += ++materialMaxIndex;
  87926. }
  87927. }
  87928. return mesh;
  87929. };
  87930. // Build Mesh from CSG taking material and transforms into account
  87931. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  87932. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  87933. mesh.material = material;
  87934. mesh.position.copyFrom(this.position);
  87935. mesh.rotation.copyFrom(this.rotation);
  87936. if (this.rotationQuaternion) {
  87937. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  87938. }
  87939. mesh.scaling.copyFrom(this.scaling);
  87940. mesh.computeWorldMatrix(true);
  87941. return mesh;
  87942. };
  87943. return CSG;
  87944. }());
  87945. BABYLON.CSG = CSG;
  87946. })(BABYLON || (BABYLON = {}));
  87947. //# sourceMappingURL=babylon.csg.js.map
  87948. var BABYLON;
  87949. (function (BABYLON) {
  87950. var LensFlare = /** @class */ (function () {
  87951. function LensFlare(size, position, color, imgUrl, system) {
  87952. this.size = size;
  87953. this.position = position;
  87954. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  87955. this.color = color || new BABYLON.Color3(1, 1, 1);
  87956. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  87957. this._system = system;
  87958. system.lensFlares.push(this);
  87959. }
  87960. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  87961. return new LensFlare(size, position, color, imgUrl, system);
  87962. };
  87963. LensFlare.prototype.dispose = function () {
  87964. if (this.texture) {
  87965. this.texture.dispose();
  87966. }
  87967. // Remove from scene
  87968. var index = this._system.lensFlares.indexOf(this);
  87969. this._system.lensFlares.splice(index, 1);
  87970. };
  87971. ;
  87972. return LensFlare;
  87973. }());
  87974. BABYLON.LensFlare = LensFlare;
  87975. })(BABYLON || (BABYLON = {}));
  87976. //# sourceMappingURL=babylon.lensFlare.js.map
  87977. var BABYLON;
  87978. (function (BABYLON) {
  87979. // Adds the parser to the scene parsers.
  87980. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  87981. // Lens flares
  87982. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  87983. if (!container.lensFlareSystems) {
  87984. container.lensFlareSystems = new Array();
  87985. }
  87986. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  87987. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  87988. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  87989. container.lensFlareSystems.push(lf);
  87990. }
  87991. }
  87992. });
  87993. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  87994. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  87995. if (this.lensFlareSystems[index].name === name) {
  87996. return this.lensFlareSystems[index];
  87997. }
  87998. }
  87999. return null;
  88000. };
  88001. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  88002. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  88003. if (this.lensFlareSystems[index].id === id) {
  88004. return this.lensFlareSystems[index];
  88005. }
  88006. }
  88007. return null;
  88008. };
  88009. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  88010. var index = this.lensFlareSystems.indexOf(toRemove);
  88011. if (index !== -1) {
  88012. this.lensFlareSystems.splice(index, 1);
  88013. }
  88014. return index;
  88015. };
  88016. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  88017. this.lensFlareSystems.push(newLensFlareSystem);
  88018. };
  88019. /**
  88020. * Defines the lens flare scene component responsible to manage any lens flares
  88021. * in a given scene.
  88022. */
  88023. var LensFlareSystemSceneComponent = /** @class */ (function () {
  88024. /**
  88025. * Creates a new instance of the component for the given scene
  88026. * @param scene Defines the scene to register the component in
  88027. */
  88028. function LensFlareSystemSceneComponent(scene) {
  88029. /**
  88030. * The component name helpfull to identify the component in the list of scene components.
  88031. */
  88032. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  88033. this.scene = scene;
  88034. scene.lensFlareSystems = new Array();
  88035. }
  88036. /**
  88037. * Registers the component in a given scene
  88038. */
  88039. LensFlareSystemSceneComponent.prototype.register = function () {
  88040. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  88041. };
  88042. /**
  88043. * Rebuilds the elements related to this component in case of
  88044. * context lost for instance.
  88045. */
  88046. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  88047. // Nothing to do for lens flare
  88048. };
  88049. /**
  88050. * Adds all the element from the container to the scene
  88051. * @param container the container holding the elements
  88052. */
  88053. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  88054. var _this = this;
  88055. if (!container.lensFlareSystems) {
  88056. return;
  88057. }
  88058. container.lensFlareSystems.forEach(function (o) {
  88059. _this.scene.addLensFlareSystem(o);
  88060. });
  88061. };
  88062. /**
  88063. * Removes all the elements in the container from the scene
  88064. * @param container contains the elements to remove
  88065. */
  88066. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  88067. var _this = this;
  88068. if (!container.lensFlareSystems) {
  88069. return;
  88070. }
  88071. container.lensFlareSystems.forEach(function (o) {
  88072. _this.scene.removeLensFlareSystem(o);
  88073. });
  88074. };
  88075. /**
  88076. * Serializes the component data to the specified json object
  88077. * @param serializationObject The object to serialize to
  88078. */
  88079. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  88080. // Lens flares
  88081. serializationObject.lensFlareSystems = [];
  88082. var lensFlareSystems = this.scene.lensFlareSystems;
  88083. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  88084. var lensFlareSystem = lensFlareSystems_1[_i];
  88085. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  88086. }
  88087. };
  88088. /**
  88089. * Disposes the component and the associated ressources.
  88090. */
  88091. LensFlareSystemSceneComponent.prototype.dispose = function () {
  88092. var lensFlareSystems = this.scene.lensFlareSystems;
  88093. while (lensFlareSystems.length) {
  88094. lensFlareSystems[0].dispose();
  88095. }
  88096. };
  88097. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  88098. // Lens flares
  88099. if (this.scene.lensFlaresEnabled) {
  88100. var lensFlareSystems = this.scene.lensFlareSystems;
  88101. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  88102. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  88103. var lensFlareSystem = lensFlareSystems_2[_i];
  88104. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  88105. lensFlareSystem.render();
  88106. }
  88107. }
  88108. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  88109. }
  88110. };
  88111. return LensFlareSystemSceneComponent;
  88112. }());
  88113. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  88114. })(BABYLON || (BABYLON = {}));
  88115. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  88116. var BABYLON;
  88117. (function (BABYLON) {
  88118. var LensFlareSystem = /** @class */ (function () {
  88119. function LensFlareSystem(name, emitter, scene) {
  88120. this.name = name;
  88121. this.lensFlares = new Array();
  88122. this.borderLimit = 300;
  88123. this.viewportBorder = 0;
  88124. this.layerMask = 0x0FFFFFFF;
  88125. this._vertexBuffers = {};
  88126. this._isEnabled = true;
  88127. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88128. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  88129. if (!component) {
  88130. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  88131. scene._addComponent(component);
  88132. }
  88133. this._emitter = emitter;
  88134. this.id = name;
  88135. scene.lensFlareSystems.push(this);
  88136. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  88137. var engine = scene.getEngine();
  88138. // VBO
  88139. var vertices = [];
  88140. vertices.push(1, 1);
  88141. vertices.push(-1, 1);
  88142. vertices.push(-1, -1);
  88143. vertices.push(1, -1);
  88144. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  88145. // Indices
  88146. var indices = [];
  88147. indices.push(0);
  88148. indices.push(1);
  88149. indices.push(2);
  88150. indices.push(0);
  88151. indices.push(2);
  88152. indices.push(3);
  88153. this._indexBuffer = engine.createIndexBuffer(indices);
  88154. // Effects
  88155. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  88156. }
  88157. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  88158. get: function () {
  88159. return this._isEnabled;
  88160. },
  88161. set: function (value) {
  88162. this._isEnabled = value;
  88163. },
  88164. enumerable: true,
  88165. configurable: true
  88166. });
  88167. LensFlareSystem.prototype.getScene = function () {
  88168. return this._scene;
  88169. };
  88170. LensFlareSystem.prototype.getEmitter = function () {
  88171. return this._emitter;
  88172. };
  88173. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  88174. this._emitter = newEmitter;
  88175. };
  88176. LensFlareSystem.prototype.getEmitterPosition = function () {
  88177. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  88178. };
  88179. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  88180. var position = this.getEmitterPosition();
  88181. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  88182. this._positionX = position.x;
  88183. this._positionY = position.y;
  88184. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  88185. if (this.viewportBorder > 0) {
  88186. globalViewport.x -= this.viewportBorder;
  88187. globalViewport.y -= this.viewportBorder;
  88188. globalViewport.width += this.viewportBorder * 2;
  88189. globalViewport.height += this.viewportBorder * 2;
  88190. position.x += this.viewportBorder;
  88191. position.y += this.viewportBorder;
  88192. this._positionX += this.viewportBorder;
  88193. this._positionY += this.viewportBorder;
  88194. }
  88195. if (position.z > 0) {
  88196. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  88197. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  88198. return true;
  88199. }
  88200. return true;
  88201. }
  88202. return false;
  88203. };
  88204. /** @hidden */
  88205. LensFlareSystem.prototype._isVisible = function () {
  88206. if (!this._isEnabled || !this._scene.activeCamera) {
  88207. return false;
  88208. }
  88209. var emitterPosition = this.getEmitterPosition();
  88210. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  88211. var distance = direction.length();
  88212. direction.normalize();
  88213. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  88214. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  88215. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  88216. };
  88217. LensFlareSystem.prototype.render = function () {
  88218. if (!this._effect.isReady() || !this._scene.activeCamera)
  88219. return false;
  88220. var engine = this._scene.getEngine();
  88221. var viewport = this._scene.activeCamera.viewport;
  88222. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  88223. // Position
  88224. if (!this.computeEffectivePosition(globalViewport)) {
  88225. return false;
  88226. }
  88227. // Visibility
  88228. if (!this._isVisible()) {
  88229. return false;
  88230. }
  88231. // Intensity
  88232. var awayX;
  88233. var awayY;
  88234. if (this._positionX < this.borderLimit + globalViewport.x) {
  88235. awayX = this.borderLimit + globalViewport.x - this._positionX;
  88236. }
  88237. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  88238. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  88239. }
  88240. else {
  88241. awayX = 0;
  88242. }
  88243. if (this._positionY < this.borderLimit + globalViewport.y) {
  88244. awayY = this.borderLimit + globalViewport.y - this._positionY;
  88245. }
  88246. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  88247. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  88248. }
  88249. else {
  88250. awayY = 0;
  88251. }
  88252. var away = (awayX > awayY) ? awayX : awayY;
  88253. away -= this.viewportBorder;
  88254. if (away > this.borderLimit) {
  88255. away = this.borderLimit;
  88256. }
  88257. var intensity = 1.0 - (away / this.borderLimit);
  88258. if (intensity < 0) {
  88259. return false;
  88260. }
  88261. if (intensity > 1.0) {
  88262. intensity = 1.0;
  88263. }
  88264. if (this.viewportBorder > 0) {
  88265. globalViewport.x += this.viewportBorder;
  88266. globalViewport.y += this.viewportBorder;
  88267. globalViewport.width -= this.viewportBorder * 2;
  88268. globalViewport.height -= this.viewportBorder * 2;
  88269. this._positionX -= this.viewportBorder;
  88270. this._positionY -= this.viewportBorder;
  88271. }
  88272. // Position
  88273. var centerX = globalViewport.x + globalViewport.width / 2;
  88274. var centerY = globalViewport.y + globalViewport.height / 2;
  88275. var distX = centerX - this._positionX;
  88276. var distY = centerY - this._positionY;
  88277. // Effects
  88278. engine.enableEffect(this._effect);
  88279. engine.setState(false);
  88280. engine.setDepthBuffer(false);
  88281. // VBOs
  88282. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  88283. // Flares
  88284. for (var index = 0; index < this.lensFlares.length; index++) {
  88285. var flare = this.lensFlares[index];
  88286. engine.setAlphaMode(flare.alphaMode);
  88287. var x = centerX - (distX * flare.position);
  88288. var y = centerY - (distY * flare.position);
  88289. var cw = flare.size;
  88290. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  88291. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  88292. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  88293. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  88294. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  88295. // Texture
  88296. this._effect.setTexture("textureSampler", flare.texture);
  88297. // Color
  88298. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  88299. // Draw order
  88300. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88301. }
  88302. engine.setDepthBuffer(true);
  88303. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88304. return true;
  88305. };
  88306. LensFlareSystem.prototype.dispose = function () {
  88307. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88308. if (vertexBuffer) {
  88309. vertexBuffer.dispose();
  88310. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88311. }
  88312. if (this._indexBuffer) {
  88313. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88314. this._indexBuffer = null;
  88315. }
  88316. while (this.lensFlares.length) {
  88317. this.lensFlares[0].dispose();
  88318. }
  88319. // Remove from scene
  88320. var index = this._scene.lensFlareSystems.indexOf(this);
  88321. this._scene.lensFlareSystems.splice(index, 1);
  88322. };
  88323. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  88324. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  88325. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  88326. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  88327. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  88328. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  88329. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  88330. var parsedFlare = parsedLensFlareSystem.flares[index];
  88331. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  88332. }
  88333. return lensFlareSystem;
  88334. };
  88335. LensFlareSystem.prototype.serialize = function () {
  88336. var serializationObject = {};
  88337. serializationObject.id = this.id;
  88338. serializationObject.name = this.name;
  88339. serializationObject.emitterId = this.getEmitter().id;
  88340. serializationObject.borderLimit = this.borderLimit;
  88341. serializationObject.flares = [];
  88342. for (var index = 0; index < this.lensFlares.length; index++) {
  88343. var flare = this.lensFlares[index];
  88344. serializationObject.flares.push({
  88345. size: flare.size,
  88346. position: flare.position,
  88347. color: flare.color.asArray(),
  88348. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  88349. });
  88350. }
  88351. return serializationObject;
  88352. };
  88353. return LensFlareSystem;
  88354. }());
  88355. BABYLON.LensFlareSystem = LensFlareSystem;
  88356. })(BABYLON || (BABYLON = {}));
  88357. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  88358. var BABYLON;
  88359. (function (BABYLON) {
  88360. /**
  88361. * This is a holder class for the physics joint created by the physics plugin.
  88362. * It holds a set of functions to control the underlying joint.
  88363. */
  88364. var PhysicsJoint = /** @class */ (function () {
  88365. function PhysicsJoint(type, jointData) {
  88366. this.type = type;
  88367. this.jointData = jointData;
  88368. jointData.nativeParams = jointData.nativeParams || {};
  88369. }
  88370. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  88371. get: function () {
  88372. return this._physicsJoint;
  88373. },
  88374. set: function (newJoint) {
  88375. if (this._physicsJoint) {
  88376. //remove from the wolrd
  88377. }
  88378. this._physicsJoint = newJoint;
  88379. },
  88380. enumerable: true,
  88381. configurable: true
  88382. });
  88383. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  88384. set: function (physicsPlugin) {
  88385. this._physicsPlugin = physicsPlugin;
  88386. },
  88387. enumerable: true,
  88388. configurable: true
  88389. });
  88390. /**
  88391. * Execute a function that is physics-plugin specific.
  88392. * @param {Function} func the function that will be executed.
  88393. * It accepts two parameters: the physics world and the physics joint.
  88394. */
  88395. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  88396. func(this._physicsPlugin.world, this._physicsJoint);
  88397. };
  88398. //TODO check if the native joints are the same
  88399. //Joint Types
  88400. PhysicsJoint.DistanceJoint = 0;
  88401. PhysicsJoint.HingeJoint = 1;
  88402. PhysicsJoint.BallAndSocketJoint = 2;
  88403. PhysicsJoint.WheelJoint = 3;
  88404. PhysicsJoint.SliderJoint = 4;
  88405. //OIMO
  88406. PhysicsJoint.PrismaticJoint = 5;
  88407. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  88408. PhysicsJoint.UniversalJoint = 6;
  88409. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  88410. //Cannon
  88411. //Similar to a Ball-Joint. Different in params
  88412. PhysicsJoint.PointToPointJoint = 8;
  88413. //Cannon only at the moment
  88414. PhysicsJoint.SpringJoint = 9;
  88415. PhysicsJoint.LockJoint = 10;
  88416. return PhysicsJoint;
  88417. }());
  88418. BABYLON.PhysicsJoint = PhysicsJoint;
  88419. /**
  88420. * A class representing a physics distance joint.
  88421. */
  88422. var DistanceJoint = /** @class */ (function (_super) {
  88423. __extends(DistanceJoint, _super);
  88424. function DistanceJoint(jointData) {
  88425. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  88426. }
  88427. /**
  88428. * Update the predefined distance.
  88429. */
  88430. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  88431. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  88432. };
  88433. return DistanceJoint;
  88434. }(PhysicsJoint));
  88435. BABYLON.DistanceJoint = DistanceJoint;
  88436. var MotorEnabledJoint = /** @class */ (function (_super) {
  88437. __extends(MotorEnabledJoint, _super);
  88438. function MotorEnabledJoint(type, jointData) {
  88439. return _super.call(this, type, jointData) || this;
  88440. }
  88441. /**
  88442. * Set the motor values.
  88443. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88444. * @param {number} force the force to apply
  88445. * @param {number} maxForce max force for this motor.
  88446. */
  88447. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  88448. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  88449. };
  88450. /**
  88451. * Set the motor's limits.
  88452. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88453. */
  88454. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  88455. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  88456. };
  88457. return MotorEnabledJoint;
  88458. }(PhysicsJoint));
  88459. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  88460. /**
  88461. * This class represents a single hinge physics joint
  88462. */
  88463. var HingeJoint = /** @class */ (function (_super) {
  88464. __extends(HingeJoint, _super);
  88465. function HingeJoint(jointData) {
  88466. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  88467. }
  88468. /**
  88469. * Set the motor values.
  88470. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88471. * @param {number} force the force to apply
  88472. * @param {number} maxForce max force for this motor.
  88473. */
  88474. HingeJoint.prototype.setMotor = function (force, maxForce) {
  88475. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  88476. };
  88477. /**
  88478. * Set the motor's limits.
  88479. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88480. */
  88481. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  88482. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  88483. };
  88484. return HingeJoint;
  88485. }(MotorEnabledJoint));
  88486. BABYLON.HingeJoint = HingeJoint;
  88487. /**
  88488. * This class represents a dual hinge physics joint (same as wheel joint)
  88489. */
  88490. var Hinge2Joint = /** @class */ (function (_super) {
  88491. __extends(Hinge2Joint, _super);
  88492. function Hinge2Joint(jointData) {
  88493. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  88494. }
  88495. /**
  88496. * Set the motor values.
  88497. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88498. * @param {number} force the force to apply
  88499. * @param {number} maxForce max force for this motor.
  88500. * @param {motorIndex} the motor's index, 0 or 1.
  88501. */
  88502. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  88503. if (motorIndex === void 0) { motorIndex = 0; }
  88504. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  88505. };
  88506. /**
  88507. * Set the motor limits.
  88508. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88509. * @param {number} upperLimit the upper limit
  88510. * @param {number} lowerLimit lower limit
  88511. * @param {motorIndex} the motor's index, 0 or 1.
  88512. */
  88513. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  88514. if (motorIndex === void 0) { motorIndex = 0; }
  88515. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  88516. };
  88517. return Hinge2Joint;
  88518. }(MotorEnabledJoint));
  88519. BABYLON.Hinge2Joint = Hinge2Joint;
  88520. })(BABYLON || (BABYLON = {}));
  88521. //# sourceMappingURL=babylon.physicsJoint.js.map
  88522. var BABYLON;
  88523. (function (BABYLON) {
  88524. var PhysicsImpostor = /** @class */ (function () {
  88525. function PhysicsImpostor(object, type, _options, _scene) {
  88526. if (_options === void 0) { _options = { mass: 0 }; }
  88527. var _this = this;
  88528. this.object = object;
  88529. this.type = type;
  88530. this._options = _options;
  88531. this._scene = _scene;
  88532. this._bodyUpdateRequired = false;
  88533. this._onBeforePhysicsStepCallbacks = new Array();
  88534. this._onAfterPhysicsStepCallbacks = new Array();
  88535. this._onPhysicsCollideCallbacks = [];
  88536. this._deltaPosition = BABYLON.Vector3.Zero();
  88537. this._isDisposed = false;
  88538. //temp variables for parent rotation calculations
  88539. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  88540. this._tmpQuat = new BABYLON.Quaternion();
  88541. this._tmpQuat2 = new BABYLON.Quaternion();
  88542. /**
  88543. * this function is executed by the physics engine.
  88544. */
  88545. this.beforeStep = function () {
  88546. if (!_this._physicsEngine) {
  88547. return;
  88548. }
  88549. _this.object.translate(_this._deltaPosition, -1);
  88550. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  88551. _this.object.computeWorldMatrix(false);
  88552. if (_this.object.parent && _this.object.rotationQuaternion) {
  88553. _this.getParentsRotation();
  88554. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  88555. }
  88556. else {
  88557. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  88558. }
  88559. if (!_this._options.disableBidirectionalTransformation) {
  88560. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  88561. }
  88562. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  88563. func(_this);
  88564. });
  88565. };
  88566. /**
  88567. * this function is executed by the physics engine.
  88568. */
  88569. this.afterStep = function () {
  88570. if (!_this._physicsEngine) {
  88571. return;
  88572. }
  88573. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  88574. func(_this);
  88575. });
  88576. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  88577. // object has now its world rotation. needs to be converted to local.
  88578. if (_this.object.parent && _this.object.rotationQuaternion) {
  88579. _this.getParentsRotation();
  88580. _this._tmpQuat.conjugateInPlace();
  88581. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  88582. }
  88583. // take the position set and make it the absolute position of this object.
  88584. _this.object.setAbsolutePosition(_this.object.position);
  88585. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  88586. _this.object.translate(_this._deltaPosition, 1);
  88587. };
  88588. /**
  88589. * Legacy collision detection event support
  88590. */
  88591. this.onCollideEvent = null;
  88592. //event and body object due to cannon's event-based architecture.
  88593. this.onCollide = function (e) {
  88594. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  88595. return;
  88596. }
  88597. if (!_this._physicsEngine) {
  88598. return;
  88599. }
  88600. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  88601. if (otherImpostor) {
  88602. // Legacy collision detection event support
  88603. if (_this.onCollideEvent) {
  88604. _this.onCollideEvent(_this, otherImpostor);
  88605. }
  88606. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  88607. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  88608. }).forEach(function (obj) {
  88609. obj.callback(_this, otherImpostor);
  88610. });
  88611. }
  88612. };
  88613. //sanity check!
  88614. if (!this.object) {
  88615. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  88616. return;
  88617. }
  88618. //legacy support for old syntax.
  88619. if (!this._scene && object.getScene) {
  88620. this._scene = object.getScene();
  88621. }
  88622. if (!this._scene) {
  88623. return;
  88624. }
  88625. this._physicsEngine = this._scene.getPhysicsEngine();
  88626. if (!this._physicsEngine) {
  88627. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  88628. }
  88629. else {
  88630. //set the object's quaternion, if not set
  88631. if (!this.object.rotationQuaternion) {
  88632. if (this.object.rotation) {
  88633. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  88634. }
  88635. else {
  88636. this.object.rotationQuaternion = new BABYLON.Quaternion();
  88637. }
  88638. }
  88639. //default options params
  88640. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  88641. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  88642. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  88643. this._joints = [];
  88644. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  88645. if (!this.object.parent || this._options.ignoreParent) {
  88646. this._init();
  88647. }
  88648. else if (this.object.parent.physicsImpostor) {
  88649. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  88650. }
  88651. }
  88652. }
  88653. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  88654. get: function () {
  88655. return this._isDisposed;
  88656. },
  88657. enumerable: true,
  88658. configurable: true
  88659. });
  88660. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  88661. get: function () {
  88662. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  88663. },
  88664. set: function (value) {
  88665. this.setMass(value);
  88666. },
  88667. enumerable: true,
  88668. configurable: true
  88669. });
  88670. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  88671. get: function () {
  88672. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  88673. },
  88674. set: function (value) {
  88675. if (!this._physicsEngine) {
  88676. return;
  88677. }
  88678. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  88679. },
  88680. enumerable: true,
  88681. configurable: true
  88682. });
  88683. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  88684. get: function () {
  88685. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  88686. },
  88687. set: function (value) {
  88688. if (!this._physicsEngine) {
  88689. return;
  88690. }
  88691. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  88692. },
  88693. enumerable: true,
  88694. configurable: true
  88695. });
  88696. /**
  88697. * This function will completly initialize this impostor.
  88698. * It will create a new body - but only if this mesh has no parent.
  88699. * If it has, this impostor will not be used other than to define the impostor
  88700. * of the child mesh.
  88701. * @hidden
  88702. */
  88703. PhysicsImpostor.prototype._init = function () {
  88704. if (!this._physicsEngine) {
  88705. return;
  88706. }
  88707. this._physicsEngine.removeImpostor(this);
  88708. this.physicsBody = null;
  88709. this._parent = this._parent || this._getPhysicsParent();
  88710. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  88711. this._physicsEngine.addImpostor(this);
  88712. }
  88713. };
  88714. PhysicsImpostor.prototype._getPhysicsParent = function () {
  88715. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  88716. var parentMesh = this.object.parent;
  88717. return parentMesh.physicsImpostor;
  88718. }
  88719. return null;
  88720. };
  88721. /**
  88722. * Should a new body be generated.
  88723. */
  88724. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  88725. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  88726. };
  88727. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  88728. this.forceUpdate();
  88729. };
  88730. /**
  88731. * Force a regeneration of this or the parent's impostor's body.
  88732. * Use under cautious - This will remove all joints already implemented.
  88733. */
  88734. PhysicsImpostor.prototype.forceUpdate = function () {
  88735. this._init();
  88736. if (this.parent && !this._options.ignoreParent) {
  88737. this.parent.forceUpdate();
  88738. }
  88739. };
  88740. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  88741. /*public get mesh(): AbstractMesh {
  88742. return this._mesh;
  88743. }*/
  88744. /**
  88745. * Gets the body that holds this impostor. Either its own, or its parent.
  88746. */
  88747. get: function () {
  88748. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  88749. },
  88750. /**
  88751. * Set the physics body. Used mainly by the physics engine/plugin
  88752. */
  88753. set: function (physicsBody) {
  88754. if (this._physicsBody && this._physicsEngine) {
  88755. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  88756. }
  88757. this._physicsBody = physicsBody;
  88758. this.resetUpdateFlags();
  88759. },
  88760. enumerable: true,
  88761. configurable: true
  88762. });
  88763. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  88764. get: function () {
  88765. return !this._options.ignoreParent && this._parent ? this._parent : null;
  88766. },
  88767. set: function (value) {
  88768. this._parent = value;
  88769. },
  88770. enumerable: true,
  88771. configurable: true
  88772. });
  88773. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  88774. this._bodyUpdateRequired = false;
  88775. };
  88776. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  88777. if (this.object.getBoundingInfo) {
  88778. var q = this.object.rotationQuaternion;
  88779. //reset rotation
  88780. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  88781. //calculate the world matrix with no rotation
  88782. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  88783. var boundingInfo = this.object.getBoundingInfo();
  88784. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  88785. //bring back the rotation
  88786. this.object.rotationQuaternion = q;
  88787. //calculate the world matrix with the new rotation
  88788. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  88789. return size;
  88790. }
  88791. else {
  88792. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  88793. }
  88794. };
  88795. PhysicsImpostor.prototype.getObjectCenter = function () {
  88796. if (this.object.getBoundingInfo) {
  88797. var boundingInfo = this.object.getBoundingInfo();
  88798. return boundingInfo.boundingBox.centerWorld;
  88799. }
  88800. else {
  88801. return this.object.position;
  88802. }
  88803. };
  88804. /**
  88805. * Get a specific parametes from the options parameter.
  88806. */
  88807. PhysicsImpostor.prototype.getParam = function (paramName) {
  88808. return this._options[paramName];
  88809. };
  88810. /**
  88811. * Sets a specific parameter in the options given to the physics plugin
  88812. */
  88813. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  88814. this._options[paramName] = value;
  88815. this._bodyUpdateRequired = true;
  88816. };
  88817. /**
  88818. * Specifically change the body's mass option. Won't recreate the physics body object
  88819. */
  88820. PhysicsImpostor.prototype.setMass = function (mass) {
  88821. if (this.getParam("mass") !== mass) {
  88822. this.setParam("mass", mass);
  88823. }
  88824. if (this._physicsEngine) {
  88825. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  88826. }
  88827. };
  88828. PhysicsImpostor.prototype.getLinearVelocity = function () {
  88829. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  88830. };
  88831. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  88832. if (this._physicsEngine) {
  88833. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  88834. }
  88835. };
  88836. PhysicsImpostor.prototype.getAngularVelocity = function () {
  88837. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  88838. };
  88839. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  88840. if (this._physicsEngine) {
  88841. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  88842. }
  88843. };
  88844. /**
  88845. * Execute a function with the physics plugin native code.
  88846. * Provide a function the will have two variables - the world object and the physics body object.
  88847. */
  88848. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  88849. if (this._physicsEngine) {
  88850. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  88851. }
  88852. };
  88853. /**
  88854. * Register a function that will be executed before the physics world is stepping forward.
  88855. */
  88856. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  88857. this._onBeforePhysicsStepCallbacks.push(func);
  88858. };
  88859. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  88860. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  88861. if (index > -1) {
  88862. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  88863. }
  88864. else {
  88865. BABYLON.Tools.Warn("Function to remove was not found");
  88866. }
  88867. };
  88868. /**
  88869. * Register a function that will be executed after the physics step
  88870. */
  88871. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  88872. this._onAfterPhysicsStepCallbacks.push(func);
  88873. };
  88874. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  88875. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  88876. if (index > -1) {
  88877. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  88878. }
  88879. else {
  88880. BABYLON.Tools.Warn("Function to remove was not found");
  88881. }
  88882. };
  88883. /**
  88884. * register a function that will be executed when this impostor collides against a different body.
  88885. */
  88886. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  88887. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  88888. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  88889. };
  88890. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  88891. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  88892. var index = -1;
  88893. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  88894. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  88895. // chcek the arrays match
  88896. var sameList = cbDef.otherImpostors.every(function (impostor) {
  88897. return collidedAgainstList.indexOf(impostor) > -1;
  88898. });
  88899. if (sameList) {
  88900. index = idx;
  88901. }
  88902. return sameList;
  88903. }
  88904. return false;
  88905. });
  88906. if (found) {
  88907. this._onPhysicsCollideCallbacks.splice(index, 1);
  88908. }
  88909. else {
  88910. BABYLON.Tools.Warn("Function to remove was not found");
  88911. }
  88912. };
  88913. PhysicsImpostor.prototype.getParentsRotation = function () {
  88914. var parent = this.object.parent;
  88915. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  88916. while (parent) {
  88917. if (parent.rotationQuaternion) {
  88918. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  88919. }
  88920. else {
  88921. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  88922. }
  88923. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  88924. parent = parent.parent;
  88925. }
  88926. return this._tmpQuat;
  88927. };
  88928. /**
  88929. * Apply a force
  88930. */
  88931. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  88932. if (this._physicsEngine) {
  88933. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  88934. }
  88935. return this;
  88936. };
  88937. /**
  88938. * Apply an impulse
  88939. */
  88940. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  88941. if (this._physicsEngine) {
  88942. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  88943. }
  88944. return this;
  88945. };
  88946. /**
  88947. * A help function to create a joint.
  88948. */
  88949. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  88950. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  88951. this.addJoint(otherImpostor, joint);
  88952. return this;
  88953. };
  88954. /**
  88955. * Add a joint to this impostor with a different impostor.
  88956. */
  88957. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  88958. this._joints.push({
  88959. otherImpostor: otherImpostor,
  88960. joint: joint
  88961. });
  88962. if (this._physicsEngine) {
  88963. this._physicsEngine.addJoint(this, otherImpostor, joint);
  88964. }
  88965. return this;
  88966. };
  88967. /**
  88968. * Will keep this body still, in a sleep mode.
  88969. */
  88970. PhysicsImpostor.prototype.sleep = function () {
  88971. if (this._physicsEngine) {
  88972. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  88973. }
  88974. return this;
  88975. };
  88976. /**
  88977. * Wake the body up.
  88978. */
  88979. PhysicsImpostor.prototype.wakeUp = function () {
  88980. if (this._physicsEngine) {
  88981. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  88982. }
  88983. return this;
  88984. };
  88985. PhysicsImpostor.prototype.clone = function (newObject) {
  88986. if (!newObject)
  88987. return null;
  88988. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  88989. };
  88990. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  88991. var _this = this;
  88992. //no dispose if no physics engine is available.
  88993. if (!this._physicsEngine) {
  88994. return;
  88995. }
  88996. this._joints.forEach(function (j) {
  88997. if (_this._physicsEngine) {
  88998. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  88999. }
  89000. });
  89001. //dispose the physics body
  89002. this._physicsEngine.removeImpostor(this);
  89003. if (this.parent) {
  89004. this.parent.forceUpdate();
  89005. }
  89006. else {
  89007. /*this._object.getChildMeshes().forEach(function(mesh) {
  89008. if (mesh.physicsImpostor) {
  89009. if (disposeChildren) {
  89010. mesh.physicsImpostor.dispose();
  89011. mesh.physicsImpostor = null;
  89012. }
  89013. }
  89014. })*/
  89015. }
  89016. this._isDisposed = true;
  89017. };
  89018. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  89019. this._deltaPosition.copyFrom(position);
  89020. };
  89021. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  89022. if (!this._deltaRotation) {
  89023. this._deltaRotation = new BABYLON.Quaternion();
  89024. }
  89025. this._deltaRotation.copyFrom(rotation);
  89026. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  89027. };
  89028. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  89029. if (this._physicsEngine) {
  89030. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  89031. }
  89032. return this;
  89033. };
  89034. PhysicsImpostor.prototype.getRadius = function () {
  89035. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  89036. };
  89037. /**
  89038. * Sync a bone with this impostor
  89039. * @param bone The bone to sync to the impostor.
  89040. * @param boneMesh The mesh that the bone is influencing.
  89041. * @param jointPivot The pivot of the joint / bone in local space.
  89042. * @param distToJoint Optional distance from the impostor to the joint.
  89043. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  89044. */
  89045. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  89046. var tempVec = PhysicsImpostor._tmpVecs[0];
  89047. var mesh = this.object;
  89048. if (mesh.rotationQuaternion) {
  89049. if (adjustRotation) {
  89050. var tempQuat = PhysicsImpostor._tmpQuat;
  89051. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  89052. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  89053. }
  89054. else {
  89055. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  89056. }
  89057. }
  89058. tempVec.x = 0;
  89059. tempVec.y = 0;
  89060. tempVec.z = 0;
  89061. if (jointPivot) {
  89062. tempVec.x = jointPivot.x;
  89063. tempVec.y = jointPivot.y;
  89064. tempVec.z = jointPivot.z;
  89065. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  89066. if (distToJoint === undefined || distToJoint === null) {
  89067. distToJoint = jointPivot.length();
  89068. }
  89069. tempVec.x *= distToJoint;
  89070. tempVec.y *= distToJoint;
  89071. tempVec.z *= distToJoint;
  89072. }
  89073. if (bone.getParent()) {
  89074. tempVec.addInPlace(mesh.getAbsolutePosition());
  89075. bone.setAbsolutePosition(tempVec, boneMesh);
  89076. }
  89077. else {
  89078. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  89079. boneMesh.position.x -= tempVec.x;
  89080. boneMesh.position.y -= tempVec.y;
  89081. boneMesh.position.z -= tempVec.z;
  89082. }
  89083. };
  89084. /**
  89085. * Sync impostor to a bone
  89086. * @param bone The bone that the impostor will be synced to.
  89087. * @param boneMesh The mesh that the bone is influencing.
  89088. * @param jointPivot The pivot of the joint / bone in local space.
  89089. * @param distToJoint Optional distance from the impostor to the joint.
  89090. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  89091. * @param boneAxis Optional vector3 axis the bone is aligned with
  89092. */
  89093. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  89094. var mesh = this.object;
  89095. if (mesh.rotationQuaternion) {
  89096. if (adjustRotation) {
  89097. var tempQuat = PhysicsImpostor._tmpQuat;
  89098. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  89099. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  89100. }
  89101. else {
  89102. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  89103. }
  89104. }
  89105. var pos = PhysicsImpostor._tmpVecs[0];
  89106. var boneDir = PhysicsImpostor._tmpVecs[1];
  89107. if (!boneAxis) {
  89108. boneAxis = PhysicsImpostor._tmpVecs[2];
  89109. boneAxis.x = 0;
  89110. boneAxis.y = 1;
  89111. boneAxis.z = 0;
  89112. }
  89113. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  89114. bone.getAbsolutePositionToRef(boneMesh, pos);
  89115. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  89116. distToJoint = jointPivot.length();
  89117. }
  89118. if (distToJoint !== undefined && distToJoint !== null) {
  89119. pos.x += boneDir.x * distToJoint;
  89120. pos.y += boneDir.y * distToJoint;
  89121. pos.z += boneDir.z * distToJoint;
  89122. }
  89123. mesh.setAbsolutePosition(pos);
  89124. };
  89125. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  89126. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  89127. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  89128. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  89129. //Impostor types
  89130. PhysicsImpostor.NoImpostor = 0;
  89131. PhysicsImpostor.SphereImpostor = 1;
  89132. PhysicsImpostor.BoxImpostor = 2;
  89133. PhysicsImpostor.PlaneImpostor = 3;
  89134. PhysicsImpostor.MeshImpostor = 4;
  89135. PhysicsImpostor.CylinderImpostor = 7;
  89136. PhysicsImpostor.ParticleImpostor = 8;
  89137. PhysicsImpostor.HeightmapImpostor = 9;
  89138. return PhysicsImpostor;
  89139. }());
  89140. BABYLON.PhysicsImpostor = PhysicsImpostor;
  89141. })(BABYLON || (BABYLON = {}));
  89142. //# sourceMappingURL=babylon.physicsImpostor.js.map
  89143. var BABYLON;
  89144. (function (BABYLON) {
  89145. /**
  89146. * Class used to control physics engine
  89147. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  89148. */
  89149. var PhysicsEngine = /** @class */ (function () {
  89150. /**
  89151. * Creates a new Physics Engine
  89152. * @param gravity defines the gravity vector used by the simulation
  89153. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  89154. */
  89155. function PhysicsEngine(gravity, _physicsPlugin) {
  89156. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  89157. this._physicsPlugin = _physicsPlugin;
  89158. this._impostors = [];
  89159. this._joints = [];
  89160. if (!this._physicsPlugin.isSupported()) {
  89161. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  89162. + "Please make sure it is included.");
  89163. }
  89164. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  89165. this.setGravity(gravity);
  89166. this.setTimeStep();
  89167. }
  89168. /**
  89169. * Sets the gravity vector used by the simulation
  89170. * @param gravity defines the gravity vector to use
  89171. */
  89172. PhysicsEngine.prototype.setGravity = function (gravity) {
  89173. this.gravity = gravity;
  89174. this._physicsPlugin.setGravity(this.gravity);
  89175. };
  89176. /**
  89177. * Set the time step of the physics engine.
  89178. * Default is 1/60.
  89179. * To slow it down, enter 1/600 for example.
  89180. * To speed it up, 1/30
  89181. * @param newTimeStep defines the new timestep to apply to this world.
  89182. */
  89183. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  89184. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  89185. this._physicsPlugin.setTimeStep(newTimeStep);
  89186. };
  89187. /**
  89188. * Get the time step of the physics engine.
  89189. * @returns the current time step
  89190. */
  89191. PhysicsEngine.prototype.getTimeStep = function () {
  89192. return this._physicsPlugin.getTimeStep();
  89193. };
  89194. /**
  89195. * Release all resources
  89196. */
  89197. PhysicsEngine.prototype.dispose = function () {
  89198. this._impostors.forEach(function (impostor) {
  89199. impostor.dispose();
  89200. });
  89201. this._physicsPlugin.dispose();
  89202. };
  89203. /**
  89204. * Gets the name of the current physics plugin
  89205. * @returns the name of the plugin
  89206. */
  89207. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  89208. return this._physicsPlugin.name;
  89209. };
  89210. /**
  89211. * Adding a new impostor for the impostor tracking.
  89212. * This will be done by the impostor itself.
  89213. * @param impostor the impostor to add
  89214. */
  89215. PhysicsEngine.prototype.addImpostor = function (impostor) {
  89216. impostor.uniqueId = this._impostors.push(impostor);
  89217. //if no parent, generate the body
  89218. if (!impostor.parent) {
  89219. this._physicsPlugin.generatePhysicsBody(impostor);
  89220. }
  89221. };
  89222. /**
  89223. * Remove an impostor from the engine.
  89224. * This impostor and its mesh will not longer be updated by the physics engine.
  89225. * @param impostor the impostor to remove
  89226. */
  89227. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  89228. var index = this._impostors.indexOf(impostor);
  89229. if (index > -1) {
  89230. var removed = this._impostors.splice(index, 1);
  89231. //Is it needed?
  89232. if (removed.length) {
  89233. //this will also remove it from the world.
  89234. removed[0].physicsBody = null;
  89235. }
  89236. }
  89237. };
  89238. /**
  89239. * Add a joint to the physics engine
  89240. * @param mainImpostor defines the main impostor to which the joint is added.
  89241. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  89242. * @param joint defines the joint that will connect both impostors.
  89243. */
  89244. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  89245. var impostorJoint = {
  89246. mainImpostor: mainImpostor,
  89247. connectedImpostor: connectedImpostor,
  89248. joint: joint
  89249. };
  89250. joint.physicsPlugin = this._physicsPlugin;
  89251. this._joints.push(impostorJoint);
  89252. this._physicsPlugin.generateJoint(impostorJoint);
  89253. };
  89254. /**
  89255. * Removes a joint from the simulation
  89256. * @param mainImpostor defines the impostor used with the joint
  89257. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  89258. * @param joint defines the joint to remove
  89259. */
  89260. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  89261. var matchingJoints = this._joints.filter(function (impostorJoint) {
  89262. return (impostorJoint.connectedImpostor === connectedImpostor
  89263. && impostorJoint.joint === joint
  89264. && impostorJoint.mainImpostor === mainImpostor);
  89265. });
  89266. if (matchingJoints.length) {
  89267. this._physicsPlugin.removeJoint(matchingJoints[0]);
  89268. //TODO remove it from the list as well
  89269. }
  89270. };
  89271. /**
  89272. * Called by the scene. No need to call it.
  89273. * @param delta defines the timespam between frames
  89274. */
  89275. PhysicsEngine.prototype._step = function (delta) {
  89276. var _this = this;
  89277. //check if any mesh has no body / requires an update
  89278. this._impostors.forEach(function (impostor) {
  89279. if (impostor.isBodyInitRequired()) {
  89280. _this._physicsPlugin.generatePhysicsBody(impostor);
  89281. }
  89282. });
  89283. if (delta > 0.1) {
  89284. delta = 0.1;
  89285. }
  89286. else if (delta <= 0) {
  89287. delta = 1.0 / 60.0;
  89288. }
  89289. this._physicsPlugin.executeStep(delta, this._impostors);
  89290. };
  89291. /**
  89292. * Gets the current plugin used to run the simulation
  89293. * @returns current plugin
  89294. */
  89295. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  89296. return this._physicsPlugin;
  89297. };
  89298. /**
  89299. * Gets the list of physic impostors
  89300. * @returns an array of PhysicsImpostor
  89301. */
  89302. PhysicsEngine.prototype.getImpostors = function () {
  89303. return this._impostors;
  89304. };
  89305. /**
  89306. * Gets the impostor for a physics enabled object
  89307. * @param object defines the object impersonated by the impostor
  89308. * @returns the PhysicsImpostor or null if not found
  89309. */
  89310. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  89311. for (var i = 0; i < this._impostors.length; ++i) {
  89312. if (this._impostors[i].object === object) {
  89313. return this._impostors[i];
  89314. }
  89315. }
  89316. return null;
  89317. };
  89318. /**
  89319. * Gets the impostor for a physics body object
  89320. * @param body defines physics body used by the impostor
  89321. * @returns the PhysicsImpostor or null if not found
  89322. */
  89323. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  89324. for (var i = 0; i < this._impostors.length; ++i) {
  89325. if (this._impostors[i].physicsBody === body) {
  89326. return this._impostors[i];
  89327. }
  89328. }
  89329. return null;
  89330. };
  89331. /**
  89332. * Global value used to control the smallest number supported by the simulation
  89333. */
  89334. PhysicsEngine.Epsilon = 0.001;
  89335. return PhysicsEngine;
  89336. }());
  89337. BABYLON.PhysicsEngine = PhysicsEngine;
  89338. })(BABYLON || (BABYLON = {}));
  89339. //# sourceMappingURL=babylon.physicsEngine.js.map
  89340. var BABYLON;
  89341. (function (BABYLON) {
  89342. var PhysicsHelper = /** @class */ (function () {
  89343. function PhysicsHelper(scene) {
  89344. this._scene = scene;
  89345. this._physicsEngine = this._scene.getPhysicsEngine();
  89346. if (!this._physicsEngine) {
  89347. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  89348. }
  89349. }
  89350. /**
  89351. * @param {Vector3} origin the origin of the explosion
  89352. * @param {number} radius the explosion radius
  89353. * @param {number} strength the explosion strength
  89354. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89355. */
  89356. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  89357. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89358. if (!this._physicsEngine) {
  89359. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  89360. return null;
  89361. }
  89362. var impostors = this._physicsEngine.getImpostors();
  89363. if (impostors.length === 0) {
  89364. return null;
  89365. }
  89366. var event = new PhysicsRadialExplosionEvent(this._scene);
  89367. impostors.forEach(function (impostor) {
  89368. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  89369. if (!impostorForceAndContactPoint) {
  89370. return;
  89371. }
  89372. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89373. });
  89374. event.dispose(false);
  89375. return event;
  89376. };
  89377. /**
  89378. * @param {Vector3} origin the origin of the explosion
  89379. * @param {number} radius the explosion radius
  89380. * @param {number} strength the explosion strength
  89381. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89382. */
  89383. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  89384. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89385. if (!this._physicsEngine) {
  89386. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89387. return null;
  89388. }
  89389. var impostors = this._physicsEngine.getImpostors();
  89390. if (impostors.length === 0) {
  89391. return null;
  89392. }
  89393. var event = new PhysicsRadialExplosionEvent(this._scene);
  89394. impostors.forEach(function (impostor) {
  89395. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  89396. if (!impostorForceAndContactPoint) {
  89397. return;
  89398. }
  89399. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89400. });
  89401. event.dispose(false);
  89402. return event;
  89403. };
  89404. /**
  89405. * @param {Vector3} origin the origin of the explosion
  89406. * @param {number} radius the explosion radius
  89407. * @param {number} strength the explosion strength
  89408. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89409. */
  89410. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  89411. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89412. if (!this._physicsEngine) {
  89413. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89414. return null;
  89415. }
  89416. var impostors = this._physicsEngine.getImpostors();
  89417. if (impostors.length === 0) {
  89418. return null;
  89419. }
  89420. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  89421. event.dispose(false);
  89422. return event;
  89423. };
  89424. /**
  89425. * @param {Vector3} origin the origin of the updraft
  89426. * @param {number} radius the radius of the updraft
  89427. * @param {number} strength the strength of the updraft
  89428. * @param {number} height the height of the updraft
  89429. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  89430. */
  89431. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  89432. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  89433. if (!this._physicsEngine) {
  89434. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89435. return null;
  89436. }
  89437. if (this._physicsEngine.getImpostors().length === 0) {
  89438. return null;
  89439. }
  89440. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  89441. event.dispose(false);
  89442. return event;
  89443. };
  89444. /**
  89445. * @param {Vector3} origin the of the vortex
  89446. * @param {number} radius the radius of the vortex
  89447. * @param {number} strength the strength of the vortex
  89448. * @param {number} height the height of the vortex
  89449. */
  89450. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  89451. if (!this._physicsEngine) {
  89452. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89453. return null;
  89454. }
  89455. if (this._physicsEngine.getImpostors().length === 0) {
  89456. return null;
  89457. }
  89458. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  89459. event.dispose(false);
  89460. return event;
  89461. };
  89462. return PhysicsHelper;
  89463. }());
  89464. BABYLON.PhysicsHelper = PhysicsHelper;
  89465. /***** Radial explosion *****/
  89466. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  89467. function PhysicsRadialExplosionEvent(scene) {
  89468. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  89469. this._rays = [];
  89470. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  89471. this._scene = scene;
  89472. }
  89473. /**
  89474. * Returns the data related to the radial explosion event (sphere & rays).
  89475. * @returns {PhysicsRadialExplosionEventData}
  89476. */
  89477. PhysicsRadialExplosionEvent.prototype.getData = function () {
  89478. this._dataFetched = true;
  89479. return {
  89480. sphere: this._sphere,
  89481. rays: this._rays,
  89482. };
  89483. };
  89484. /**
  89485. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  89486. * @param impostor
  89487. * @param {Vector3} origin the origin of the explosion
  89488. * @param {number} radius the explosion radius
  89489. * @param {number} strength the explosion strength
  89490. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  89491. * @returns {Nullable<PhysicsForceAndContactPoint>}
  89492. */
  89493. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  89494. if (impostor.mass === 0) {
  89495. return null;
  89496. }
  89497. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  89498. return null;
  89499. }
  89500. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  89501. return null;
  89502. }
  89503. var impostorObjectCenter = impostor.getObjectCenter();
  89504. var direction = impostorObjectCenter.subtract(origin);
  89505. var ray = new BABYLON.Ray(origin, direction, radius);
  89506. this._rays.push(ray);
  89507. var hit = ray.intersectsMesh(impostor.object);
  89508. var contactPoint = hit.pickedPoint;
  89509. if (!contactPoint) {
  89510. return null;
  89511. }
  89512. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  89513. if (distanceFromOrigin > radius) {
  89514. return null;
  89515. }
  89516. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  89517. ? strength
  89518. : strength * (1 - (distanceFromOrigin / radius));
  89519. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  89520. return { force: force, contactPoint: contactPoint };
  89521. };
  89522. /**
  89523. * Disposes the sphere.
  89524. * @param {bolean} force
  89525. */
  89526. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  89527. var _this = this;
  89528. if (force === void 0) { force = true; }
  89529. if (force) {
  89530. this._sphere.dispose();
  89531. }
  89532. else {
  89533. setTimeout(function () {
  89534. if (!_this._dataFetched) {
  89535. _this._sphere.dispose();
  89536. }
  89537. }, 0);
  89538. }
  89539. };
  89540. /*** Helpers ***/
  89541. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  89542. if (!this._sphere) {
  89543. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  89544. this._sphere.isVisible = false;
  89545. }
  89546. };
  89547. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  89548. var impostorObject = impostor.object;
  89549. this._prepareSphere();
  89550. this._sphere.position = origin;
  89551. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  89552. this._sphere._updateBoundingInfo();
  89553. this._sphere.computeWorldMatrix(true);
  89554. return this._sphere.intersectsMesh(impostorObject, true);
  89555. };
  89556. return PhysicsRadialExplosionEvent;
  89557. }());
  89558. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  89559. /***** Gravitational Field *****/
  89560. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  89561. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  89562. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89563. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89564. this._physicsHelper = physicsHelper;
  89565. this._scene = scene;
  89566. this._origin = origin;
  89567. this._radius = radius;
  89568. this._strength = strength;
  89569. this._falloff = falloff;
  89570. this._tickCallback = this._tick.bind(this);
  89571. }
  89572. /**
  89573. * Returns the data related to the gravitational field event (sphere).
  89574. * @returns {PhysicsGravitationalFieldEventData}
  89575. */
  89576. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  89577. this._dataFetched = true;
  89578. return {
  89579. sphere: this._sphere,
  89580. };
  89581. };
  89582. /**
  89583. * Enables the gravitational field.
  89584. */
  89585. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  89586. this._tickCallback.call(this);
  89587. this._scene.registerBeforeRender(this._tickCallback);
  89588. };
  89589. /**
  89590. * Disables the gravitational field.
  89591. */
  89592. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  89593. this._scene.unregisterBeforeRender(this._tickCallback);
  89594. };
  89595. /**
  89596. * Disposes the sphere.
  89597. * @param {bolean} force
  89598. */
  89599. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  89600. var _this = this;
  89601. if (force === void 0) { force = true; }
  89602. if (force) {
  89603. this._sphere.dispose();
  89604. }
  89605. else {
  89606. setTimeout(function () {
  89607. if (!_this._dataFetched) {
  89608. _this._sphere.dispose();
  89609. }
  89610. }, 0);
  89611. }
  89612. };
  89613. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  89614. // Since the params won't change, we fetch the event only once
  89615. if (this._sphere) {
  89616. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  89617. }
  89618. else {
  89619. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  89620. if (radialExplosionEvent) {
  89621. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  89622. }
  89623. }
  89624. };
  89625. return PhysicsGravitationalFieldEvent;
  89626. }());
  89627. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  89628. /***** Updraft *****/
  89629. var PhysicsUpdraftEvent = /** @class */ (function () {
  89630. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  89631. this._scene = _scene;
  89632. this._origin = _origin;
  89633. this._radius = _radius;
  89634. this._strength = _strength;
  89635. this._height = _height;
  89636. this._updraftMode = _updraftMode;
  89637. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  89638. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  89639. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  89640. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89641. this._physicsEngine = this._scene.getPhysicsEngine();
  89642. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  89643. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  89644. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  89645. this._originDirection = this._origin.subtract(this._originTop).normalize();
  89646. }
  89647. this._tickCallback = this._tick.bind(this);
  89648. }
  89649. /**
  89650. * Returns the data related to the updraft event (cylinder).
  89651. * @returns {PhysicsUpdraftEventData}
  89652. */
  89653. PhysicsUpdraftEvent.prototype.getData = function () {
  89654. this._dataFetched = true;
  89655. return {
  89656. cylinder: this._cylinder,
  89657. };
  89658. };
  89659. /**
  89660. * Enables the updraft.
  89661. */
  89662. PhysicsUpdraftEvent.prototype.enable = function () {
  89663. this._tickCallback.call(this);
  89664. this._scene.registerBeforeRender(this._tickCallback);
  89665. };
  89666. /**
  89667. * Disables the cortex.
  89668. */
  89669. PhysicsUpdraftEvent.prototype.disable = function () {
  89670. this._scene.unregisterBeforeRender(this._tickCallback);
  89671. };
  89672. /**
  89673. * Disposes the sphere.
  89674. * @param {bolean} force
  89675. */
  89676. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  89677. var _this = this;
  89678. if (force === void 0) { force = true; }
  89679. if (force) {
  89680. this._cylinder.dispose();
  89681. }
  89682. else {
  89683. setTimeout(function () {
  89684. if (!_this._dataFetched) {
  89685. _this._cylinder.dispose();
  89686. }
  89687. }, 0);
  89688. }
  89689. };
  89690. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  89691. if (impostor.mass === 0) {
  89692. return null;
  89693. }
  89694. if (!this._intersectsWithCylinder(impostor)) {
  89695. return null;
  89696. }
  89697. var impostorObjectCenter = impostor.getObjectCenter();
  89698. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  89699. var direction = this._originDirection;
  89700. }
  89701. else {
  89702. var direction = impostorObjectCenter.subtract(this._originTop);
  89703. }
  89704. var multiplier = this._strength * -1;
  89705. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  89706. return { force: force, contactPoint: impostorObjectCenter };
  89707. };
  89708. PhysicsUpdraftEvent.prototype._tick = function () {
  89709. var _this = this;
  89710. this._physicsEngine.getImpostors().forEach(function (impostor) {
  89711. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  89712. if (!impostorForceAndContactPoint) {
  89713. return;
  89714. }
  89715. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89716. });
  89717. };
  89718. /*** Helpers ***/
  89719. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  89720. if (!this._cylinder) {
  89721. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  89722. height: this._height,
  89723. diameter: this._radius * 2,
  89724. }, this._scene);
  89725. this._cylinder.isVisible = false;
  89726. }
  89727. };
  89728. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  89729. var impostorObject = impostor.object;
  89730. this._prepareCylinder();
  89731. this._cylinder.position = this._cylinderPosition;
  89732. return this._cylinder.intersectsMesh(impostorObject, true);
  89733. };
  89734. return PhysicsUpdraftEvent;
  89735. }());
  89736. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  89737. /***** Vortex *****/
  89738. var PhysicsVortexEvent = /** @class */ (function () {
  89739. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  89740. this._scene = _scene;
  89741. this._origin = _origin;
  89742. this._radius = _radius;
  89743. this._strength = _strength;
  89744. this._height = _height;
  89745. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  89746. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  89747. this._updraftMultiplier = 0.02;
  89748. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  89749. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89750. this._physicsEngine = this._scene.getPhysicsEngine();
  89751. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  89752. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  89753. this._tickCallback = this._tick.bind(this);
  89754. }
  89755. /**
  89756. * Returns the data related to the vortex event (cylinder).
  89757. * @returns {PhysicsVortexEventData}
  89758. */
  89759. PhysicsVortexEvent.prototype.getData = function () {
  89760. this._dataFetched = true;
  89761. return {
  89762. cylinder: this._cylinder,
  89763. };
  89764. };
  89765. /**
  89766. * Enables the vortex.
  89767. */
  89768. PhysicsVortexEvent.prototype.enable = function () {
  89769. this._tickCallback.call(this);
  89770. this._scene.registerBeforeRender(this._tickCallback);
  89771. };
  89772. /**
  89773. * Disables the cortex.
  89774. */
  89775. PhysicsVortexEvent.prototype.disable = function () {
  89776. this._scene.unregisterBeforeRender(this._tickCallback);
  89777. };
  89778. /**
  89779. * Disposes the sphere.
  89780. * @param {bolean} force
  89781. */
  89782. PhysicsVortexEvent.prototype.dispose = function (force) {
  89783. var _this = this;
  89784. if (force === void 0) { force = true; }
  89785. if (force) {
  89786. this._cylinder.dispose();
  89787. }
  89788. else {
  89789. setTimeout(function () {
  89790. if (!_this._dataFetched) {
  89791. _this._cylinder.dispose();
  89792. }
  89793. }, 0);
  89794. }
  89795. };
  89796. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  89797. if (impostor.mass === 0) {
  89798. return null;
  89799. }
  89800. if (!this._intersectsWithCylinder(impostor)) {
  89801. return null;
  89802. }
  89803. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  89804. return null;
  89805. }
  89806. var impostorObjectCenter = impostor.getObjectCenter();
  89807. 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)
  89808. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  89809. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  89810. var hit = ray.intersectsMesh(impostor.object);
  89811. var contactPoint = hit.pickedPoint;
  89812. if (!contactPoint) {
  89813. return null;
  89814. }
  89815. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  89816. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  89817. var directionToOrigin = contactPoint.normalize();
  89818. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  89819. directionToOrigin = directionToOrigin.negate();
  89820. }
  89821. // TODO: find a more physically based solution
  89822. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  89823. var forceX = directionToOrigin.x * this._strength / 8;
  89824. var forceY = directionToOrigin.y * this._updraftMultiplier;
  89825. var forceZ = directionToOrigin.z * this._strength / 8;
  89826. }
  89827. else {
  89828. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  89829. var forceY = this._originTop.y * this._updraftMultiplier;
  89830. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  89831. }
  89832. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  89833. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  89834. return { force: force, contactPoint: impostorObjectCenter };
  89835. };
  89836. PhysicsVortexEvent.prototype._tick = function () {
  89837. var _this = this;
  89838. this._physicsEngine.getImpostors().forEach(function (impostor) {
  89839. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  89840. if (!impostorForceAndContactPoint) {
  89841. return;
  89842. }
  89843. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89844. });
  89845. };
  89846. /*** Helpers ***/
  89847. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  89848. if (!this._cylinder) {
  89849. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  89850. height: this._height,
  89851. diameter: this._radius * 2,
  89852. }, this._scene);
  89853. this._cylinder.isVisible = false;
  89854. }
  89855. };
  89856. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  89857. var impostorObject = impostor.object;
  89858. this._prepareCylinder();
  89859. this._cylinder.position = this._cylinderPosition;
  89860. return this._cylinder.intersectsMesh(impostorObject, true);
  89861. };
  89862. return PhysicsVortexEvent;
  89863. }());
  89864. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  89865. /***** Enums *****/
  89866. /**
  89867. * The strenght of the force in correspondence to the distance of the affected object
  89868. */
  89869. var PhysicsRadialImpulseFalloff;
  89870. (function (PhysicsRadialImpulseFalloff) {
  89871. /** Defines that impulse is constant in strength across it's whole radius */
  89872. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  89873. /** DEfines that impulse gets weaker if it's further from the origin */
  89874. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  89875. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  89876. /**
  89877. * The strenght of the force in correspondence to the distance of the affected object
  89878. */
  89879. var PhysicsUpdraftMode;
  89880. (function (PhysicsUpdraftMode) {
  89881. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  89882. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  89883. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  89884. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  89885. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  89886. })(BABYLON || (BABYLON = {}));
  89887. //# sourceMappingURL=babylon.physicsHelper.js.map
  89888. var BABYLON;
  89889. (function (BABYLON) {
  89890. var CannonJSPlugin = /** @class */ (function () {
  89891. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  89892. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  89893. if (iterations === void 0) { iterations = 10; }
  89894. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  89895. this.name = "CannonJSPlugin";
  89896. this._physicsMaterials = new Array();
  89897. this._fixedTimeStep = 1 / 60;
  89898. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  89899. this.BJSCANNON = CANNON;
  89900. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  89901. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  89902. this._tmpPosition = BABYLON.Vector3.Zero();
  89903. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  89904. this._tmpUnityRotation = new BABYLON.Quaternion();
  89905. if (!this.isSupported()) {
  89906. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  89907. return;
  89908. }
  89909. this._extendNamespace();
  89910. this.world = new this.BJSCANNON.World();
  89911. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  89912. this.world.solver.iterations = iterations;
  89913. }
  89914. CannonJSPlugin.prototype.setGravity = function (gravity) {
  89915. this.world.gravity.copy(gravity);
  89916. };
  89917. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  89918. this._fixedTimeStep = timeStep;
  89919. };
  89920. CannonJSPlugin.prototype.getTimeStep = function () {
  89921. return this._fixedTimeStep;
  89922. };
  89923. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  89924. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  89925. };
  89926. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  89927. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  89928. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  89929. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  89930. };
  89931. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  89932. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  89933. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  89934. impostor.physicsBody.applyForce(impulse, worldPoint);
  89935. };
  89936. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  89937. //parent-child relationship. Does this impostor has a parent impostor?
  89938. if (impostor.parent) {
  89939. if (impostor.physicsBody) {
  89940. this.removePhysicsBody(impostor);
  89941. //TODO is that needed?
  89942. impostor.forceUpdate();
  89943. }
  89944. return;
  89945. }
  89946. //should a new body be created for this impostor?
  89947. if (impostor.isBodyInitRequired()) {
  89948. var shape = this._createShape(impostor);
  89949. //unregister events, if body is being changed
  89950. var oldBody = impostor.physicsBody;
  89951. if (oldBody) {
  89952. this.removePhysicsBody(impostor);
  89953. }
  89954. //create the body and material
  89955. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  89956. var bodyCreationObject = {
  89957. mass: impostor.getParam("mass"),
  89958. material: material
  89959. };
  89960. // A simple extend, in case native options were used.
  89961. var nativeOptions = impostor.getParam("nativeOptions");
  89962. for (var key in nativeOptions) {
  89963. if (nativeOptions.hasOwnProperty(key)) {
  89964. bodyCreationObject[key] = nativeOptions[key];
  89965. }
  89966. }
  89967. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  89968. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  89969. this.world.addEventListener("preStep", impostor.beforeStep);
  89970. this.world.addEventListener("postStep", impostor.afterStep);
  89971. impostor.physicsBody.addShape(shape);
  89972. this.world.add(impostor.physicsBody);
  89973. //try to keep the body moving in the right direction by taking old properties.
  89974. //Should be tested!
  89975. if (oldBody) {
  89976. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  89977. impostor.physicsBody[param].copy(oldBody[param]);
  89978. });
  89979. }
  89980. this._processChildMeshes(impostor);
  89981. }
  89982. //now update the body's transformation
  89983. this._updatePhysicsBodyTransformation(impostor);
  89984. };
  89985. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  89986. var _this = this;
  89987. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  89988. var currentRotation = mainImpostor.object.rotationQuaternion;
  89989. if (meshChildren.length) {
  89990. var processMesh = function (localPosition, mesh) {
  89991. if (!currentRotation || !mesh.rotationQuaternion) {
  89992. return;
  89993. }
  89994. var childImpostor = mesh.getPhysicsImpostor();
  89995. if (childImpostor) {
  89996. var parent = childImpostor.parent;
  89997. if (parent !== mainImpostor) {
  89998. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  89999. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  90000. if (childImpostor.physicsBody) {
  90001. _this.removePhysicsBody(childImpostor);
  90002. childImpostor.physicsBody = null;
  90003. }
  90004. childImpostor.parent = mainImpostor;
  90005. childImpostor.resetUpdateFlags();
  90006. 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));
  90007. //Add the mass of the children.
  90008. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  90009. }
  90010. }
  90011. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  90012. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  90013. };
  90014. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  90015. }
  90016. };
  90017. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  90018. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  90019. this.world.removeEventListener("preStep", impostor.beforeStep);
  90020. this.world.removeEventListener("postStep", impostor.afterStep);
  90021. this.world.remove(impostor.physicsBody);
  90022. };
  90023. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  90024. var mainBody = impostorJoint.mainImpostor.physicsBody;
  90025. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  90026. if (!mainBody || !connectedBody) {
  90027. return;
  90028. }
  90029. var constraint;
  90030. var jointData = impostorJoint.joint.jointData;
  90031. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  90032. var constraintData = {
  90033. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  90034. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  90035. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  90036. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  90037. maxForce: jointData.nativeParams.maxForce,
  90038. collideConnected: !!jointData.collision
  90039. };
  90040. switch (impostorJoint.joint.type) {
  90041. case BABYLON.PhysicsJoint.HingeJoint:
  90042. case BABYLON.PhysicsJoint.Hinge2Joint:
  90043. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  90044. break;
  90045. case BABYLON.PhysicsJoint.DistanceJoint:
  90046. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  90047. break;
  90048. case BABYLON.PhysicsJoint.SpringJoint:
  90049. var springData = jointData;
  90050. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  90051. restLength: springData.length,
  90052. stiffness: springData.stiffness,
  90053. damping: springData.damping,
  90054. localAnchorA: constraintData.pivotA,
  90055. localAnchorB: constraintData.pivotB
  90056. });
  90057. break;
  90058. case BABYLON.PhysicsJoint.LockJoint:
  90059. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  90060. break;
  90061. case BABYLON.PhysicsJoint.PointToPointJoint:
  90062. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  90063. default:
  90064. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  90065. break;
  90066. }
  90067. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  90068. constraint.collideConnected = !!jointData.collision;
  90069. impostorJoint.joint.physicsJoint = constraint;
  90070. //don't add spring as constraint, as it is not one.
  90071. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  90072. this.world.addConstraint(constraint);
  90073. }
  90074. else {
  90075. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  90076. constraint.applyForce();
  90077. };
  90078. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  90079. }
  90080. };
  90081. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  90082. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  90083. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  90084. }
  90085. else {
  90086. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  90087. }
  90088. };
  90089. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  90090. var index;
  90091. var mat;
  90092. for (index = 0; index < this._physicsMaterials.length; index++) {
  90093. mat = this._physicsMaterials[index];
  90094. if (mat.friction === friction && mat.restitution === restitution) {
  90095. return mat;
  90096. }
  90097. }
  90098. var currentMat = new this.BJSCANNON.Material(name);
  90099. currentMat.friction = friction;
  90100. currentMat.restitution = restitution;
  90101. this._physicsMaterials.push(currentMat);
  90102. return currentMat;
  90103. };
  90104. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  90105. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  90106. };
  90107. CannonJSPlugin.prototype._createShape = function (impostor) {
  90108. var object = impostor.object;
  90109. var returnValue;
  90110. var extendSize = impostor.getObjectExtendSize();
  90111. switch (impostor.type) {
  90112. case BABYLON.PhysicsImpostor.SphereImpostor:
  90113. var radiusX = extendSize.x;
  90114. var radiusY = extendSize.y;
  90115. var radiusZ = extendSize.z;
  90116. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  90117. break;
  90118. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  90119. case BABYLON.PhysicsImpostor.CylinderImpostor:
  90120. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  90121. break;
  90122. case BABYLON.PhysicsImpostor.BoxImpostor:
  90123. var box = extendSize.scale(0.5);
  90124. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  90125. break;
  90126. case BABYLON.PhysicsImpostor.PlaneImpostor:
  90127. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  90128. returnValue = new this.BJSCANNON.Plane();
  90129. break;
  90130. case BABYLON.PhysicsImpostor.MeshImpostor:
  90131. // should transform the vertex data to world coordinates!!
  90132. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  90133. var rawFaces = object.getIndices ? object.getIndices() : [];
  90134. if (!rawVerts)
  90135. return;
  90136. // get only scale! so the object could transform correctly.
  90137. var oldPosition = object.position.clone();
  90138. var oldRotation = object.rotation && object.rotation.clone();
  90139. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  90140. object.position.copyFromFloats(0, 0, 0);
  90141. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  90142. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  90143. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  90144. var transform = object.computeWorldMatrix(true);
  90145. // convert rawVerts to object space
  90146. var temp = new Array();
  90147. var index;
  90148. for (index = 0; index < rawVerts.length; index += 3) {
  90149. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  90150. }
  90151. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  90152. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  90153. //now set back the transformation!
  90154. object.position.copyFrom(oldPosition);
  90155. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  90156. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  90157. break;
  90158. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  90159. var oldPosition2 = object.position.clone();
  90160. var oldRotation2 = object.rotation && object.rotation.clone();
  90161. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  90162. object.position.copyFromFloats(0, 0, 0);
  90163. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  90164. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  90165. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  90166. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  90167. returnValue = this._createHeightmap(object);
  90168. object.position.copyFrom(oldPosition2);
  90169. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  90170. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  90171. object.computeWorldMatrix(true);
  90172. break;
  90173. case BABYLON.PhysicsImpostor.ParticleImpostor:
  90174. returnValue = new this.BJSCANNON.Particle();
  90175. break;
  90176. }
  90177. return returnValue;
  90178. };
  90179. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  90180. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  90181. var transform = object.computeWorldMatrix(true);
  90182. // convert rawVerts to object space
  90183. var temp = new Array();
  90184. var index;
  90185. for (index = 0; index < pos.length; index += 3) {
  90186. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  90187. }
  90188. pos = temp;
  90189. var matrix = new Array();
  90190. //For now pointDepth will not be used and will be automatically calculated.
  90191. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  90192. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  90193. var boundingInfo = object.getBoundingInfo();
  90194. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  90195. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  90196. var elementSize = dim * 2 / arraySize;
  90197. for (var i = 0; i < pos.length; i = i + 3) {
  90198. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  90199. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  90200. var y = -pos[i + 2] + minY;
  90201. if (!matrix[x]) {
  90202. matrix[x] = [];
  90203. }
  90204. if (!matrix[x][z]) {
  90205. matrix[x][z] = y;
  90206. }
  90207. matrix[x][z] = Math.max(y, matrix[x][z]);
  90208. }
  90209. for (var x = 0; x <= arraySize; ++x) {
  90210. if (!matrix[x]) {
  90211. var loc = 1;
  90212. while (!matrix[(x + loc) % arraySize]) {
  90213. loc++;
  90214. }
  90215. matrix[x] = matrix[(x + loc) % arraySize].slice();
  90216. //console.log("missing x", x);
  90217. }
  90218. for (var z = 0; z <= arraySize; ++z) {
  90219. if (!matrix[x][z]) {
  90220. var loc = 1;
  90221. var newValue;
  90222. while (newValue === undefined) {
  90223. newValue = matrix[x][(z + loc++) % arraySize];
  90224. }
  90225. matrix[x][z] = newValue;
  90226. }
  90227. }
  90228. }
  90229. var shape = new this.BJSCANNON.Heightfield(matrix, {
  90230. elementSize: elementSize
  90231. });
  90232. //For future reference, needed for body transformation
  90233. shape.minY = minY;
  90234. return shape;
  90235. };
  90236. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  90237. var object = impostor.object;
  90238. //make sure it is updated...
  90239. object.computeWorldMatrix && object.computeWorldMatrix(true);
  90240. // The delta between the mesh position and the mesh bounding box center
  90241. var bInfo = object.getBoundingInfo();
  90242. if (!bInfo)
  90243. return;
  90244. var center = impostor.getObjectCenter();
  90245. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  90246. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  90247. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  90248. this._tmpPosition.copyFrom(center);
  90249. var quaternion = object.rotationQuaternion;
  90250. if (!quaternion) {
  90251. return;
  90252. }
  90253. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  90254. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  90255. //-90 DEG in X, precalculated
  90256. quaternion = quaternion.multiply(this._minus90X);
  90257. //Invert! (Precalculated, 90 deg in X)
  90258. //No need to clone. this will never change.
  90259. impostor.setDeltaRotation(this._plus90X);
  90260. }
  90261. //If it is a heightfield, if should be centered.
  90262. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  90263. var mesh = object;
  90264. var boundingInfo = mesh.getBoundingInfo();
  90265. //calculate the correct body position:
  90266. var rotationQuaternion = mesh.rotationQuaternion;
  90267. mesh.rotationQuaternion = this._tmpUnityRotation;
  90268. mesh.computeWorldMatrix(true);
  90269. //get original center with no rotation
  90270. var c = center.clone();
  90271. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  90272. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  90273. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  90274. mesh.setPreTransformMatrix(p);
  90275. mesh.computeWorldMatrix(true);
  90276. //calculate the translation
  90277. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  90278. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  90279. //add it inverted to the delta
  90280. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  90281. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  90282. //rotation is back
  90283. mesh.rotationQuaternion = rotationQuaternion;
  90284. mesh.setPreTransformMatrix(oldPivot);
  90285. mesh.computeWorldMatrix(true);
  90286. }
  90287. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  90288. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  90289. //this._tmpPosition.copyFrom(object.position);
  90290. }
  90291. impostor.setDeltaPosition(this._tmpDeltaPosition);
  90292. //Now update the impostor object
  90293. impostor.physicsBody.position.copy(this._tmpPosition);
  90294. impostor.physicsBody.quaternion.copy(quaternion);
  90295. };
  90296. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  90297. impostor.object.position.copyFrom(impostor.physicsBody.position);
  90298. if (impostor.object.rotationQuaternion) {
  90299. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  90300. }
  90301. };
  90302. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  90303. impostor.physicsBody.position.copy(newPosition);
  90304. impostor.physicsBody.quaternion.copy(newRotation);
  90305. };
  90306. CannonJSPlugin.prototype.isSupported = function () {
  90307. return this.BJSCANNON !== undefined;
  90308. };
  90309. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  90310. impostor.physicsBody.velocity.copy(velocity);
  90311. };
  90312. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  90313. impostor.physicsBody.angularVelocity.copy(velocity);
  90314. };
  90315. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  90316. var v = impostor.physicsBody.velocity;
  90317. if (!v) {
  90318. return null;
  90319. }
  90320. return new BABYLON.Vector3(v.x, v.y, v.z);
  90321. };
  90322. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  90323. var v = impostor.physicsBody.angularVelocity;
  90324. if (!v) {
  90325. return null;
  90326. }
  90327. return new BABYLON.Vector3(v.x, v.y, v.z);
  90328. };
  90329. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  90330. impostor.physicsBody.mass = mass;
  90331. impostor.physicsBody.updateMassProperties();
  90332. };
  90333. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  90334. return impostor.physicsBody.mass;
  90335. };
  90336. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  90337. return impostor.physicsBody.material.friction;
  90338. };
  90339. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  90340. impostor.physicsBody.material.friction = friction;
  90341. };
  90342. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  90343. return impostor.physicsBody.material.restitution;
  90344. };
  90345. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  90346. impostor.physicsBody.material.restitution = restitution;
  90347. };
  90348. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  90349. impostor.physicsBody.sleep();
  90350. };
  90351. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  90352. impostor.physicsBody.wakeUp();
  90353. };
  90354. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  90355. joint.physicsJoint.distance = maxDistance;
  90356. };
  90357. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  90358. // if (!motorIndex) {
  90359. // joint.physicsJoint.enableMotor();
  90360. // }
  90361. // }
  90362. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  90363. // if (!motorIndex) {
  90364. // joint.physicsJoint.disableMotor();
  90365. // }
  90366. // }
  90367. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  90368. if (!motorIndex) {
  90369. joint.physicsJoint.enableMotor();
  90370. joint.physicsJoint.setMotorSpeed(speed);
  90371. if (maxForce) {
  90372. this.setLimit(joint, maxForce);
  90373. }
  90374. }
  90375. };
  90376. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  90377. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  90378. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  90379. };
  90380. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  90381. var body = impostor.physicsBody;
  90382. mesh.position.x = body.position.x;
  90383. mesh.position.y = body.position.y;
  90384. mesh.position.z = body.position.z;
  90385. if (mesh.rotationQuaternion) {
  90386. mesh.rotationQuaternion.x = body.quaternion.x;
  90387. mesh.rotationQuaternion.y = body.quaternion.y;
  90388. mesh.rotationQuaternion.z = body.quaternion.z;
  90389. mesh.rotationQuaternion.w = body.quaternion.w;
  90390. }
  90391. };
  90392. CannonJSPlugin.prototype.getRadius = function (impostor) {
  90393. var shape = impostor.physicsBody.shapes[0];
  90394. return shape.boundingSphereRadius;
  90395. };
  90396. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  90397. var shape = impostor.physicsBody.shapes[0];
  90398. result.x = shape.halfExtents.x * 2;
  90399. result.y = shape.halfExtents.y * 2;
  90400. result.z = shape.halfExtents.z * 2;
  90401. };
  90402. CannonJSPlugin.prototype.dispose = function () {
  90403. };
  90404. CannonJSPlugin.prototype._extendNamespace = function () {
  90405. //this will force cannon to execute at least one step when using interpolation
  90406. var step_tmp1 = new this.BJSCANNON.Vec3();
  90407. var Engine = this.BJSCANNON;
  90408. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  90409. maxSubSteps = maxSubSteps || 10;
  90410. timeSinceLastCalled = timeSinceLastCalled || 0;
  90411. if (timeSinceLastCalled === 0) {
  90412. this.internalStep(dt);
  90413. this.time += dt;
  90414. }
  90415. else {
  90416. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  90417. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  90418. var t0 = performance.now();
  90419. for (var i = 0; i !== internalSteps; i++) {
  90420. this.internalStep(dt);
  90421. if (performance.now() - t0 > dt * 1000) {
  90422. break;
  90423. }
  90424. }
  90425. this.time += timeSinceLastCalled;
  90426. var h = this.time % dt;
  90427. var h_div_dt = h / dt;
  90428. var interpvelo = step_tmp1;
  90429. var bodies = this.bodies;
  90430. for (var j = 0; j !== bodies.length; j++) {
  90431. var b = bodies[j];
  90432. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  90433. b.position.vsub(b.previousPosition, interpvelo);
  90434. interpvelo.scale(h_div_dt, interpvelo);
  90435. b.position.vadd(interpvelo, b.interpolatedPosition);
  90436. }
  90437. else {
  90438. b.interpolatedPosition.copy(b.position);
  90439. b.interpolatedQuaternion.copy(b.quaternion);
  90440. }
  90441. }
  90442. }
  90443. };
  90444. };
  90445. return CannonJSPlugin;
  90446. }());
  90447. BABYLON.CannonJSPlugin = CannonJSPlugin;
  90448. })(BABYLON || (BABYLON = {}));
  90449. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  90450. var BABYLON;
  90451. (function (BABYLON) {
  90452. var OimoJSPlugin = /** @class */ (function () {
  90453. function OimoJSPlugin(iterations) {
  90454. this.name = "OimoJSPlugin";
  90455. this._tmpImpostorsArray = [];
  90456. this._tmpPositionVector = BABYLON.Vector3.Zero();
  90457. this.BJSOIMO = OIMO;
  90458. this.world = new this.BJSOIMO.World({
  90459. iterations: iterations
  90460. });
  90461. this.world.clear();
  90462. }
  90463. OimoJSPlugin.prototype.setGravity = function (gravity) {
  90464. this.world.gravity.copy(gravity);
  90465. };
  90466. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  90467. this.world.timeStep = timeStep;
  90468. };
  90469. OimoJSPlugin.prototype.getTimeStep = function () {
  90470. return this.world.timeStep;
  90471. };
  90472. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  90473. var _this = this;
  90474. impostors.forEach(function (impostor) {
  90475. impostor.beforeStep();
  90476. });
  90477. this.world.step();
  90478. impostors.forEach(function (impostor) {
  90479. impostor.afterStep();
  90480. //update the ordered impostors array
  90481. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  90482. });
  90483. //check for collisions
  90484. var contact = this.world.contacts;
  90485. while (contact !== null) {
  90486. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  90487. contact = contact.next;
  90488. continue;
  90489. }
  90490. //is this body colliding with any other? get the impostor
  90491. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  90492. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  90493. if (!mainImpostor || !collidingImpostor) {
  90494. contact = contact.next;
  90495. continue;
  90496. }
  90497. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  90498. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  90499. contact = contact.next;
  90500. }
  90501. };
  90502. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  90503. var mass = impostor.physicsBody.mass;
  90504. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  90505. };
  90506. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  90507. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  90508. this.applyImpulse(impostor, force, contactPoint);
  90509. };
  90510. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  90511. var _this = this;
  90512. //parent-child relationship. Does this impostor has a parent impostor?
  90513. if (impostor.parent) {
  90514. if (impostor.physicsBody) {
  90515. this.removePhysicsBody(impostor);
  90516. //TODO is that needed?
  90517. impostor.forceUpdate();
  90518. }
  90519. return;
  90520. }
  90521. if (impostor.isBodyInitRequired()) {
  90522. var bodyConfig = {
  90523. name: impostor.uniqueId,
  90524. //Oimo must have mass, also for static objects.
  90525. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  90526. size: [],
  90527. type: [],
  90528. pos: [],
  90529. posShape: [],
  90530. rot: [],
  90531. rotShape: [],
  90532. move: impostor.getParam("mass") !== 0,
  90533. density: impostor.getParam("mass"),
  90534. friction: impostor.getParam("friction"),
  90535. restitution: impostor.getParam("restitution"),
  90536. //Supporting older versions of Oimo
  90537. world: this.world
  90538. };
  90539. var impostors = [impostor];
  90540. var addToArray = function (parent) {
  90541. if (!parent.getChildMeshes)
  90542. return;
  90543. parent.getChildMeshes().forEach(function (m) {
  90544. if (m.physicsImpostor) {
  90545. impostors.push(m.physicsImpostor);
  90546. //m.physicsImpostor._init();
  90547. }
  90548. });
  90549. };
  90550. addToArray(impostor.object);
  90551. var checkWithEpsilon_1 = function (value) {
  90552. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  90553. };
  90554. var globalQuaternion_1 = new BABYLON.Quaternion();
  90555. impostors.forEach(function (i) {
  90556. if (!i.object.rotationQuaternion) {
  90557. return;
  90558. }
  90559. //get the correct bounding box
  90560. var oldQuaternion = i.object.rotationQuaternion;
  90561. globalQuaternion_1 = oldQuaternion.clone();
  90562. var rot = oldQuaternion.toEulerAngles();
  90563. var extendSize = i.getObjectExtendSize();
  90564. var radToDeg = 57.295779513082320876;
  90565. if (i === impostor) {
  90566. var center = impostor.getObjectCenter();
  90567. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  90568. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  90569. //Can also use Array.prototype.push.apply
  90570. bodyConfig.pos.push(center.x);
  90571. bodyConfig.pos.push(center.y);
  90572. bodyConfig.pos.push(center.z);
  90573. bodyConfig.posShape.push(0, 0, 0);
  90574. //tmp solution
  90575. bodyConfig.rot.push(0);
  90576. bodyConfig.rot.push(0);
  90577. bodyConfig.rot.push(0);
  90578. bodyConfig.rotShape.push(0, 0, 0);
  90579. }
  90580. else {
  90581. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  90582. bodyConfig.posShape.push(localPosition.x);
  90583. bodyConfig.posShape.push(localPosition.y);
  90584. bodyConfig.posShape.push(localPosition.z);
  90585. bodyConfig.pos.push(0, 0, 0);
  90586. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  90587. bodyConfig.rot.push(0);
  90588. bodyConfig.rot.push(0);
  90589. bodyConfig.rot.push(0);
  90590. bodyConfig.rotShape.push(rot.x * radToDeg);
  90591. bodyConfig.rotShape.push(rot.y * radToDeg);
  90592. bodyConfig.rotShape.push(rot.z * radToDeg);
  90593. }
  90594. // register mesh
  90595. switch (i.type) {
  90596. case BABYLON.PhysicsImpostor.ParticleImpostor:
  90597. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  90598. case BABYLON.PhysicsImpostor.SphereImpostor:
  90599. var radiusX = extendSize.x;
  90600. var radiusY = extendSize.y;
  90601. var radiusZ = extendSize.z;
  90602. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  90603. bodyConfig.type.push('sphere');
  90604. //due to the way oimo works with compounds, add 3 times
  90605. bodyConfig.size.push(size);
  90606. bodyConfig.size.push(size);
  90607. bodyConfig.size.push(size);
  90608. break;
  90609. case BABYLON.PhysicsImpostor.CylinderImpostor:
  90610. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  90611. var sizeY = checkWithEpsilon_1(extendSize.y);
  90612. bodyConfig.type.push('cylinder');
  90613. bodyConfig.size.push(sizeX);
  90614. bodyConfig.size.push(sizeY);
  90615. //due to the way oimo works with compounds, add one more value.
  90616. bodyConfig.size.push(sizeY);
  90617. break;
  90618. case BABYLON.PhysicsImpostor.PlaneImpostor:
  90619. case BABYLON.PhysicsImpostor.BoxImpostor:
  90620. default:
  90621. var sizeX = checkWithEpsilon_1(extendSize.x);
  90622. var sizeY = checkWithEpsilon_1(extendSize.y);
  90623. var sizeZ = checkWithEpsilon_1(extendSize.z);
  90624. bodyConfig.type.push('box');
  90625. //if (i === impostor) {
  90626. bodyConfig.size.push(sizeX);
  90627. bodyConfig.size.push(sizeY);
  90628. bodyConfig.size.push(sizeZ);
  90629. //} else {
  90630. // bodyConfig.size.push(0,0,0);
  90631. //}
  90632. break;
  90633. }
  90634. //actually not needed, but hey...
  90635. i.object.rotationQuaternion = oldQuaternion;
  90636. });
  90637. impostor.physicsBody = this.world.add(bodyConfig);
  90638. // set the quaternion, ignoring the previously defined (euler) rotation
  90639. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  90640. // update with delta 0, so the body will reveive the new rotation.
  90641. impostor.physicsBody.updatePosition(0);
  90642. }
  90643. else {
  90644. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  90645. }
  90646. impostor.setDeltaPosition(this._tmpPositionVector);
  90647. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  90648. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  90649. };
  90650. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  90651. //impostor.physicsBody.dispose();
  90652. //Same as : (older oimo versions)
  90653. this.world.removeRigidBody(impostor.physicsBody);
  90654. };
  90655. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  90656. var mainBody = impostorJoint.mainImpostor.physicsBody;
  90657. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  90658. if (!mainBody || !connectedBody) {
  90659. return;
  90660. }
  90661. var jointData = impostorJoint.joint.jointData;
  90662. var options = jointData.nativeParams || {};
  90663. var type;
  90664. var nativeJointData = {
  90665. body1: mainBody,
  90666. body2: connectedBody,
  90667. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  90668. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  90669. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  90670. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  90671. min: options.min,
  90672. max: options.max,
  90673. collision: options.collision || jointData.collision,
  90674. spring: options.spring,
  90675. //supporting older version of Oimo
  90676. world: this.world
  90677. };
  90678. switch (impostorJoint.joint.type) {
  90679. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  90680. type = "jointBall";
  90681. break;
  90682. case BABYLON.PhysicsJoint.SpringJoint:
  90683. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  90684. var springData = jointData;
  90685. nativeJointData.min = springData.length || nativeJointData.min;
  90686. //Max should also be set, just make sure it is at least min
  90687. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  90688. case BABYLON.PhysicsJoint.DistanceJoint:
  90689. type = "jointDistance";
  90690. nativeJointData.max = jointData.maxDistance;
  90691. break;
  90692. case BABYLON.PhysicsJoint.PrismaticJoint:
  90693. type = "jointPrisme";
  90694. break;
  90695. case BABYLON.PhysicsJoint.SliderJoint:
  90696. type = "jointSlide";
  90697. break;
  90698. case BABYLON.PhysicsJoint.WheelJoint:
  90699. type = "jointWheel";
  90700. break;
  90701. case BABYLON.PhysicsJoint.HingeJoint:
  90702. default:
  90703. type = "jointHinge";
  90704. break;
  90705. }
  90706. nativeJointData.type = type;
  90707. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  90708. };
  90709. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  90710. //Bug in Oimo prevents us from disposing a joint in the playground
  90711. //joint.joint.physicsJoint.dispose();
  90712. //So we will bruteforce it!
  90713. try {
  90714. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  90715. }
  90716. catch (e) {
  90717. BABYLON.Tools.Warn(e);
  90718. }
  90719. };
  90720. OimoJSPlugin.prototype.isSupported = function () {
  90721. return this.BJSOIMO !== undefined;
  90722. };
  90723. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  90724. if (!impostor.physicsBody.sleeping) {
  90725. //TODO check that
  90726. /*if (impostor.physicsBody.shapes.next) {
  90727. var parentShape = this._getLastShape(impostor.physicsBody);
  90728. impostor.object.position.copyFrom(parentShape.position);
  90729. console.log(parentShape.position);
  90730. } else {*/
  90731. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  90732. //}
  90733. if (impostor.object.rotationQuaternion) {
  90734. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  90735. }
  90736. }
  90737. };
  90738. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  90739. var body = impostor.physicsBody;
  90740. body.position.copy(newPosition);
  90741. body.orientation.copy(newRotation);
  90742. body.syncShapes();
  90743. body.awake();
  90744. };
  90745. /*private _getLastShape(body: any): any {
  90746. var lastShape = body.shapes;
  90747. while (lastShape.next) {
  90748. lastShape = lastShape.next;
  90749. }
  90750. return lastShape;
  90751. }*/
  90752. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  90753. impostor.physicsBody.linearVelocity.copy(velocity);
  90754. };
  90755. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  90756. impostor.physicsBody.angularVelocity.copy(velocity);
  90757. };
  90758. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  90759. var v = impostor.physicsBody.linearVelocity;
  90760. if (!v) {
  90761. return null;
  90762. }
  90763. return new BABYLON.Vector3(v.x, v.y, v.z);
  90764. };
  90765. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  90766. var v = impostor.physicsBody.angularVelocity;
  90767. if (!v) {
  90768. return null;
  90769. }
  90770. return new BABYLON.Vector3(v.x, v.y, v.z);
  90771. };
  90772. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  90773. var staticBody = mass === 0;
  90774. //this will actually set the body's density and not its mass.
  90775. //But this is how oimo treats the mass variable.
  90776. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  90777. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  90778. };
  90779. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  90780. return impostor.physicsBody.shapes.density;
  90781. };
  90782. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  90783. return impostor.physicsBody.shapes.friction;
  90784. };
  90785. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  90786. impostor.physicsBody.shapes.friction = friction;
  90787. };
  90788. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  90789. return impostor.physicsBody.shapes.restitution;
  90790. };
  90791. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  90792. impostor.physicsBody.shapes.restitution = restitution;
  90793. };
  90794. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  90795. impostor.physicsBody.sleep();
  90796. };
  90797. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  90798. impostor.physicsBody.awake();
  90799. };
  90800. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  90801. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  90802. if (minDistance !== void 0) {
  90803. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  90804. }
  90805. };
  90806. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  90807. //TODO separate rotational and transational motors.
  90808. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  90809. if (motor) {
  90810. motor.setMotor(speed, maxForce);
  90811. }
  90812. };
  90813. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  90814. //TODO separate rotational and transational motors.
  90815. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  90816. if (motor) {
  90817. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  90818. }
  90819. };
  90820. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  90821. var body = impostor.physicsBody;
  90822. mesh.position.x = body.position.x;
  90823. mesh.position.y = body.position.y;
  90824. mesh.position.z = body.position.z;
  90825. if (mesh.rotationQuaternion) {
  90826. mesh.rotationQuaternion.x = body.orientation.x;
  90827. mesh.rotationQuaternion.y = body.orientation.y;
  90828. mesh.rotationQuaternion.z = body.orientation.z;
  90829. mesh.rotationQuaternion.w = body.orientation.s;
  90830. }
  90831. };
  90832. OimoJSPlugin.prototype.getRadius = function (impostor) {
  90833. return impostor.physicsBody.shapes.radius;
  90834. };
  90835. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  90836. var shape = impostor.physicsBody.shapes;
  90837. result.x = shape.halfWidth * 2;
  90838. result.y = shape.halfHeight * 2;
  90839. result.z = shape.halfDepth * 2;
  90840. };
  90841. OimoJSPlugin.prototype.dispose = function () {
  90842. this.world.clear();
  90843. };
  90844. return OimoJSPlugin;
  90845. }());
  90846. BABYLON.OimoJSPlugin = OimoJSPlugin;
  90847. })(BABYLON || (BABYLON = {}));
  90848. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  90849. var BABYLON;
  90850. (function (BABYLON) {
  90851. /**
  90852. * Gets the current physics engine
  90853. * @returns a IPhysicsEngine or null if none attached
  90854. */
  90855. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  90856. return this._physicsEngine;
  90857. };
  90858. /**
  90859. * Enables physics to the current scene
  90860. * @param gravity defines the scene's gravity for the physics engine
  90861. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  90862. * @return a boolean indicating if the physics engine was initialized
  90863. */
  90864. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  90865. if (gravity === void 0) { gravity = null; }
  90866. if (this._physicsEngine) {
  90867. return true;
  90868. }
  90869. // Register the component to the scene
  90870. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  90871. if (!component) {
  90872. component = new PhysicsEngineSceneComponent(this);
  90873. this._addComponent(component);
  90874. }
  90875. try {
  90876. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  90877. return true;
  90878. }
  90879. catch (e) {
  90880. BABYLON.Tools.Error(e.message);
  90881. return false;
  90882. }
  90883. };
  90884. /**
  90885. * Disables and disposes the physics engine associated with the scene
  90886. */
  90887. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  90888. if (!this._physicsEngine) {
  90889. return;
  90890. }
  90891. this._physicsEngine.dispose();
  90892. this._physicsEngine = null;
  90893. };
  90894. /**
  90895. * Gets a boolean indicating if there is an active physics engine
  90896. * @returns a boolean indicating if there is an active physics engine
  90897. */
  90898. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  90899. return this._physicsEngine !== undefined;
  90900. };
  90901. /**
  90902. * Deletes a physics compound impostor
  90903. * @param compound defines the compound to delete
  90904. */
  90905. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  90906. var mesh = compound.parts[0].mesh;
  90907. if (mesh.physicsImpostor) {
  90908. mesh.physicsImpostor.dispose( /*true*/);
  90909. mesh.physicsImpostor = null;
  90910. }
  90911. };
  90912. /** @hidden */
  90913. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  90914. if (this._physicsEngine) {
  90915. this.onBeforePhysicsObservable.notifyObservers(this);
  90916. this._physicsEngine._step(step / 1000);
  90917. this.onAfterPhysicsObservable.notifyObservers(this);
  90918. }
  90919. };
  90920. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  90921. get: function () {
  90922. return this._physicsImpostor;
  90923. },
  90924. set: function (value) {
  90925. var _this = this;
  90926. if (this._physicsImpostor === value) {
  90927. return;
  90928. }
  90929. if (this._disposePhysicsObserver) {
  90930. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  90931. }
  90932. this._physicsImpostor = value;
  90933. if (value) {
  90934. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  90935. // Physics
  90936. if (_this.physicsImpostor) {
  90937. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  90938. _this.physicsImpostor = null;
  90939. }
  90940. });
  90941. }
  90942. },
  90943. enumerable: true,
  90944. configurable: true
  90945. });
  90946. /**
  90947. * Gets the current physics impostor
  90948. * @see http://doc.babylonjs.com/features/physics_engine
  90949. * @returns a physics impostor or null
  90950. */
  90951. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  90952. return this.physicsImpostor;
  90953. };
  90954. /**
  90955. * Apply a physic impulse to the mesh
  90956. * @param force defines the force to apply
  90957. * @param contactPoint defines where to apply the force
  90958. * @returns the current mesh
  90959. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  90960. */
  90961. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  90962. if (!this.physicsImpostor) {
  90963. return this;
  90964. }
  90965. this.physicsImpostor.applyImpulse(force, contactPoint);
  90966. return this;
  90967. };
  90968. /**
  90969. * Creates a physic joint between two meshes
  90970. * @param otherMesh defines the other mesh to use
  90971. * @param pivot1 defines the pivot to use on this mesh
  90972. * @param pivot2 defines the pivot to use on the other mesh
  90973. * @param options defines additional options (can be plugin dependent)
  90974. * @returns the current mesh
  90975. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  90976. */
  90977. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  90978. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  90979. return this;
  90980. }
  90981. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  90982. mainPivot: pivot1,
  90983. connectedPivot: pivot2,
  90984. nativeParams: options
  90985. });
  90986. return this;
  90987. };
  90988. /**
  90989. * Defines the physics engine scene component responsible to manage a physics engine
  90990. */
  90991. var PhysicsEngineSceneComponent = /** @class */ (function () {
  90992. /**
  90993. * Creates a new instance of the component for the given scene
  90994. * @param scene Defines the scene to register the component in
  90995. */
  90996. function PhysicsEngineSceneComponent(scene) {
  90997. var _this = this;
  90998. /**
  90999. * The component name helpful to identify the component in the list of scene components.
  91000. */
  91001. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  91002. this.scene = scene;
  91003. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  91004. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  91005. // Replace the function used to get the deterministic frame time
  91006. this.scene.getDeterministicFrameTime = function () {
  91007. if (_this.scene._physicsEngine) {
  91008. return _this.scene._physicsEngine.getTimeStep() * 1000;
  91009. }
  91010. return 1000.0 / 60.0;
  91011. };
  91012. }
  91013. /**
  91014. * Registers the component in a given scene
  91015. */
  91016. PhysicsEngineSceneComponent.prototype.register = function () {
  91017. };
  91018. /**
  91019. * Rebuilds the elements related to this component in case of
  91020. * context lost for instance.
  91021. */
  91022. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  91023. // Nothing to do for this component
  91024. };
  91025. /**
  91026. * Disposes the component and the associated ressources
  91027. */
  91028. PhysicsEngineSceneComponent.prototype.dispose = function () {
  91029. this.scene.onBeforePhysicsObservable.clear();
  91030. this.scene.onAfterPhysicsObservable.clear();
  91031. if (this.scene._physicsEngine) {
  91032. this.scene.disablePhysicsEngine();
  91033. }
  91034. };
  91035. return PhysicsEngineSceneComponent;
  91036. }());
  91037. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  91038. })(BABYLON || (BABYLON = {}));
  91039. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  91040. var BABYLON;
  91041. (function (BABYLON) {
  91042. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  91043. // All values and structures referenced from:
  91044. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  91045. var DDS_MAGIC = 0x20534444;
  91046. var
  91047. //DDSD_CAPS = 0x1,
  91048. //DDSD_HEIGHT = 0x2,
  91049. //DDSD_WIDTH = 0x4,
  91050. //DDSD_PITCH = 0x8,
  91051. //DDSD_PIXELFORMAT = 0x1000,
  91052. DDSD_MIPMAPCOUNT = 0x20000;
  91053. //DDSD_LINEARSIZE = 0x80000,
  91054. //DDSD_DEPTH = 0x800000;
  91055. // var DDSCAPS_COMPLEX = 0x8,
  91056. // DDSCAPS_MIPMAP = 0x400000,
  91057. // DDSCAPS_TEXTURE = 0x1000;
  91058. var DDSCAPS2_CUBEMAP = 0x200;
  91059. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  91060. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  91061. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  91062. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  91063. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  91064. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  91065. // DDSCAPS2_VOLUME = 0x200000;
  91066. var
  91067. //DDPF_ALPHAPIXELS = 0x1,
  91068. //DDPF_ALPHA = 0x2,
  91069. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  91070. //DDPF_YUV = 0x200,
  91071. DDPF_LUMINANCE = 0x20000;
  91072. function FourCCToInt32(value) {
  91073. return value.charCodeAt(0) +
  91074. (value.charCodeAt(1) << 8) +
  91075. (value.charCodeAt(2) << 16) +
  91076. (value.charCodeAt(3) << 24);
  91077. }
  91078. function Int32ToFourCC(value) {
  91079. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  91080. }
  91081. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  91082. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  91083. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  91084. var FOURCC_DX10 = FourCCToInt32("DX10");
  91085. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  91086. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  91087. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  91088. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  91089. var headerLengthInt = 31; // The header length in 32 bit ints
  91090. // Offsets into the header array
  91091. var off_magic = 0;
  91092. var off_size = 1;
  91093. var off_flags = 2;
  91094. var off_height = 3;
  91095. var off_width = 4;
  91096. var off_mipmapCount = 7;
  91097. var off_pfFlags = 20;
  91098. var off_pfFourCC = 21;
  91099. var off_RGBbpp = 22;
  91100. var off_RMask = 23;
  91101. var off_GMask = 24;
  91102. var off_BMask = 25;
  91103. var off_AMask = 26;
  91104. // var off_caps1 = 27;
  91105. var off_caps2 = 28;
  91106. // var off_caps3 = 29;
  91107. // var off_caps4 = 30;
  91108. var off_dxgiFormat = 32;
  91109. ;
  91110. var DDSTools = /** @class */ (function () {
  91111. function DDSTools() {
  91112. }
  91113. DDSTools.GetDDSInfo = function (arrayBuffer) {
  91114. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  91115. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  91116. var mipmapCount = 1;
  91117. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  91118. mipmapCount = Math.max(1, header[off_mipmapCount]);
  91119. }
  91120. var fourCC = header[off_pfFourCC];
  91121. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  91122. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91123. switch (fourCC) {
  91124. case FOURCC_D3DFMT_R16G16B16A16F:
  91125. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91126. break;
  91127. case FOURCC_D3DFMT_R32G32B32A32F:
  91128. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91129. break;
  91130. case FOURCC_DX10:
  91131. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  91132. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91133. break;
  91134. }
  91135. }
  91136. return {
  91137. width: header[off_width],
  91138. height: header[off_height],
  91139. mipmapCount: mipmapCount,
  91140. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  91141. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  91142. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  91143. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  91144. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  91145. dxgiFormat: dxgiFormat,
  91146. textureType: textureType
  91147. };
  91148. };
  91149. DDSTools._ToHalfFloat = function (value) {
  91150. if (!DDSTools._FloatView) {
  91151. DDSTools._FloatView = new Float32Array(1);
  91152. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  91153. }
  91154. DDSTools._FloatView[0] = value;
  91155. var x = DDSTools._Int32View[0];
  91156. var bits = (x >> 16) & 0x8000; /* Get the sign */
  91157. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  91158. var e = (x >> 23) & 0xff; /* Using int is faster here */
  91159. /* If zero, or denormal, or exponent underflows too much for a denormal
  91160. * half, return signed zero. */
  91161. if (e < 103) {
  91162. return bits;
  91163. }
  91164. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  91165. if (e > 142) {
  91166. bits |= 0x7c00;
  91167. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  91168. * not Inf, so make sure we set one mantissa bit too. */
  91169. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  91170. return bits;
  91171. }
  91172. /* If exponent underflows but not too much, return a denormal */
  91173. if (e < 113) {
  91174. m |= 0x0800;
  91175. /* Extra rounding may overflow and set mantissa to 0 and exponent
  91176. * to 1, which is OK. */
  91177. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  91178. return bits;
  91179. }
  91180. bits |= ((e - 112) << 10) | (m >> 1);
  91181. bits += m & 1;
  91182. return bits;
  91183. };
  91184. DDSTools._FromHalfFloat = function (value) {
  91185. var s = (value & 0x8000) >> 15;
  91186. var e = (value & 0x7C00) >> 10;
  91187. var f = value & 0x03FF;
  91188. if (e === 0) {
  91189. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  91190. }
  91191. else if (e == 0x1F) {
  91192. return f ? NaN : ((s ? -1 : 1) * Infinity);
  91193. }
  91194. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  91195. };
  91196. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91197. var destArray = new Float32Array(dataLength);
  91198. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  91199. var index = 0;
  91200. for (var y = 0; y < height; y++) {
  91201. for (var x = 0; x < width; x++) {
  91202. var srcPos = (x + y * width) * 4;
  91203. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  91204. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  91205. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  91206. if (DDSTools.StoreLODInAlphaChannel) {
  91207. destArray[index + 3] = lod;
  91208. }
  91209. else {
  91210. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  91211. }
  91212. index += 4;
  91213. }
  91214. }
  91215. return destArray;
  91216. };
  91217. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91218. if (DDSTools.StoreLODInAlphaChannel) {
  91219. var destArray = new Uint16Array(dataLength);
  91220. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  91221. var index = 0;
  91222. for (var y = 0; y < height; y++) {
  91223. for (var x = 0; x < width; x++) {
  91224. var srcPos = (x + y * width) * 4;
  91225. destArray[index] = srcData[srcPos];
  91226. destArray[index + 1] = srcData[srcPos + 1];
  91227. destArray[index + 2] = srcData[srcPos + 2];
  91228. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  91229. index += 4;
  91230. }
  91231. }
  91232. return destArray;
  91233. }
  91234. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  91235. };
  91236. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91237. if (DDSTools.StoreLODInAlphaChannel) {
  91238. var destArray = new Float32Array(dataLength);
  91239. var srcData = new Float32Array(arrayBuffer, dataOffset);
  91240. var index = 0;
  91241. for (var y = 0; y < height; y++) {
  91242. for (var x = 0; x < width; x++) {
  91243. var srcPos = (x + y * width) * 4;
  91244. destArray[index] = srcData[srcPos];
  91245. destArray[index + 1] = srcData[srcPos + 1];
  91246. destArray[index + 2] = srcData[srcPos + 2];
  91247. destArray[index + 3] = lod;
  91248. index += 4;
  91249. }
  91250. }
  91251. return destArray;
  91252. }
  91253. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  91254. };
  91255. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91256. var destArray = new Uint8Array(dataLength);
  91257. var srcData = new Float32Array(arrayBuffer, dataOffset);
  91258. var index = 0;
  91259. for (var y = 0; y < height; y++) {
  91260. for (var x = 0; x < width; x++) {
  91261. var srcPos = (x + y * width) * 4;
  91262. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  91263. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  91264. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  91265. if (DDSTools.StoreLODInAlphaChannel) {
  91266. destArray[index + 3] = lod;
  91267. }
  91268. else {
  91269. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  91270. }
  91271. index += 4;
  91272. }
  91273. }
  91274. return destArray;
  91275. };
  91276. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  91277. var destArray = new Uint8Array(dataLength);
  91278. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  91279. var index = 0;
  91280. for (var y = 0; y < height; y++) {
  91281. for (var x = 0; x < width; x++) {
  91282. var srcPos = (x + y * width) * 4;
  91283. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  91284. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  91285. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  91286. if (DDSTools.StoreLODInAlphaChannel) {
  91287. destArray[index + 3] = lod;
  91288. }
  91289. else {
  91290. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  91291. }
  91292. index += 4;
  91293. }
  91294. }
  91295. return destArray;
  91296. };
  91297. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  91298. var byteArray = new Uint8Array(dataLength);
  91299. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  91300. var index = 0;
  91301. for (var y = 0; y < height; y++) {
  91302. for (var x = 0; x < width; x++) {
  91303. var srcPos = (x + y * width) * 4;
  91304. byteArray[index] = srcData[srcPos + rOffset];
  91305. byteArray[index + 1] = srcData[srcPos + gOffset];
  91306. byteArray[index + 2] = srcData[srcPos + bOffset];
  91307. byteArray[index + 3] = srcData[srcPos + aOffset];
  91308. index += 4;
  91309. }
  91310. }
  91311. return byteArray;
  91312. };
  91313. DDSTools._ExtractLongWordOrder = function (value) {
  91314. if (value === 0 || value === 255 || value === -16777216) {
  91315. return 0;
  91316. }
  91317. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  91318. };
  91319. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  91320. var byteArray = new Uint8Array(dataLength);
  91321. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  91322. var index = 0;
  91323. for (var y = 0; y < height; y++) {
  91324. for (var x = 0; x < width; x++) {
  91325. var srcPos = (x + y * width) * 3;
  91326. byteArray[index] = srcData[srcPos + rOffset];
  91327. byteArray[index + 1] = srcData[srcPos + gOffset];
  91328. byteArray[index + 2] = srcData[srcPos + bOffset];
  91329. index += 3;
  91330. }
  91331. }
  91332. return byteArray;
  91333. };
  91334. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  91335. var byteArray = new Uint8Array(dataLength);
  91336. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  91337. var index = 0;
  91338. for (var y = 0; y < height; y++) {
  91339. for (var x = 0; x < width; x++) {
  91340. var srcPos = (x + y * width);
  91341. byteArray[index] = srcData[srcPos];
  91342. index++;
  91343. }
  91344. }
  91345. return byteArray;
  91346. };
  91347. /**
  91348. * Uploads DDS Levels to a Babylon Texture
  91349. * @hidden
  91350. */
  91351. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  91352. if (lodIndex === void 0) { lodIndex = -1; }
  91353. var sphericalPolynomialFaces = null;
  91354. if (info.sphericalPolynomial) {
  91355. sphericalPolynomialFaces = new Array();
  91356. }
  91357. var ext = engine.getCaps().s3tc;
  91358. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  91359. var fourCC, width, height, dataLength = 0, dataOffset;
  91360. var byteArray, mipmapCount, mip;
  91361. var internalCompressedFormat = 0;
  91362. var blockBytes = 1;
  91363. if (header[off_magic] !== DDS_MAGIC) {
  91364. BABYLON.Tools.Error("Invalid magic number in DDS header");
  91365. return;
  91366. }
  91367. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  91368. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  91369. return;
  91370. }
  91371. if (info.isCompressed && !ext) {
  91372. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  91373. return;
  91374. }
  91375. var bpp = header[off_RGBbpp];
  91376. dataOffset = header[off_size] + 4;
  91377. var computeFormats = false;
  91378. if (info.isFourCC) {
  91379. fourCC = header[off_pfFourCC];
  91380. switch (fourCC) {
  91381. case FOURCC_DXT1:
  91382. blockBytes = 8;
  91383. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  91384. break;
  91385. case FOURCC_DXT3:
  91386. blockBytes = 16;
  91387. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  91388. break;
  91389. case FOURCC_DXT5:
  91390. blockBytes = 16;
  91391. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  91392. break;
  91393. case FOURCC_D3DFMT_R16G16B16A16F:
  91394. computeFormats = true;
  91395. break;
  91396. case FOURCC_D3DFMT_R32G32B32A32F:
  91397. computeFormats = true;
  91398. break;
  91399. case FOURCC_DX10:
  91400. // There is an additionnal header so dataOffset need to be changed
  91401. dataOffset += 5 * 4; // 5 uints
  91402. var supported = false;
  91403. switch (info.dxgiFormat) {
  91404. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  91405. computeFormats = true;
  91406. supported = true;
  91407. break;
  91408. case DXGI_FORMAT_B8G8R8X8_UNORM:
  91409. info.isRGB = true;
  91410. info.isFourCC = false;
  91411. bpp = 32;
  91412. supported = true;
  91413. break;
  91414. }
  91415. if (supported) {
  91416. break;
  91417. }
  91418. default:
  91419. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  91420. return;
  91421. }
  91422. }
  91423. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  91424. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  91425. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  91426. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  91427. if (computeFormats) {
  91428. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  91429. }
  91430. mipmapCount = 1;
  91431. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  91432. mipmapCount = Math.max(1, header[off_mipmapCount]);
  91433. }
  91434. for (var face = 0; face < faces; face++) {
  91435. width = header[off_width];
  91436. height = header[off_height];
  91437. for (mip = 0; mip < mipmapCount; ++mip) {
  91438. if (lodIndex === -1 || lodIndex === mip) {
  91439. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  91440. var i = (lodIndex === -1) ? mip : 0;
  91441. if (!info.isCompressed && info.isFourCC) {
  91442. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  91443. dataLength = width * height * 4;
  91444. var floatArray = null;
  91445. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  91446. if (bpp === 128) {
  91447. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91448. if (sphericalPolynomialFaces && i == 0) {
  91449. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  91450. }
  91451. }
  91452. else if (bpp === 64) {
  91453. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91454. if (sphericalPolynomialFaces && i == 0) {
  91455. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  91456. }
  91457. }
  91458. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91459. }
  91460. else {
  91461. if (bpp === 128) {
  91462. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91463. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91464. if (sphericalPolynomialFaces && i == 0) {
  91465. sphericalPolynomialFaces.push(floatArray);
  91466. }
  91467. }
  91468. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  91469. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91470. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91471. if (sphericalPolynomialFaces && i == 0) {
  91472. sphericalPolynomialFaces.push(floatArray);
  91473. }
  91474. }
  91475. else { // 64
  91476. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91477. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  91478. if (sphericalPolynomialFaces && i == 0) {
  91479. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  91480. }
  91481. }
  91482. }
  91483. if (floatArray) {
  91484. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  91485. }
  91486. }
  91487. else if (info.isRGB) {
  91488. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91489. if (bpp === 24) {
  91490. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  91491. dataLength = width * height * 3;
  91492. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  91493. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  91494. }
  91495. else { // 32
  91496. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  91497. dataLength = width * height * 4;
  91498. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  91499. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  91500. }
  91501. }
  91502. else if (info.isLuminance) {
  91503. var unpackAlignment = engine._getUnpackAlignement();
  91504. var unpaddedRowSize = width;
  91505. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  91506. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  91507. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  91508. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  91509. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91510. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  91511. }
  91512. else {
  91513. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  91514. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  91515. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91516. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  91517. }
  91518. }
  91519. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  91520. width *= 0.5;
  91521. height *= 0.5;
  91522. width = Math.max(1.0, width);
  91523. height = Math.max(1.0, height);
  91524. }
  91525. if (currentFace !== undefined) {
  91526. // Loading a single face
  91527. break;
  91528. }
  91529. }
  91530. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  91531. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  91532. size: header[off_width],
  91533. right: sphericalPolynomialFaces[0],
  91534. left: sphericalPolynomialFaces[1],
  91535. up: sphericalPolynomialFaces[2],
  91536. down: sphericalPolynomialFaces[3],
  91537. front: sphericalPolynomialFaces[4],
  91538. back: sphericalPolynomialFaces[5],
  91539. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  91540. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  91541. gammaSpace: false,
  91542. });
  91543. }
  91544. else {
  91545. info.sphericalPolynomial = undefined;
  91546. }
  91547. };
  91548. DDSTools.StoreLODInAlphaChannel = false;
  91549. return DDSTools;
  91550. }());
  91551. BABYLON.DDSTools = DDSTools;
  91552. })(BABYLON || (BABYLON = {}));
  91553. //# sourceMappingURL=babylon.dds.js.map
  91554. var BABYLON;
  91555. (function (BABYLON) {
  91556. /**
  91557. * Implementation of the DDS Texture Loader.
  91558. */
  91559. var DDSTextureLoader = /** @class */ (function () {
  91560. function DDSTextureLoader() {
  91561. /**
  91562. * Defines wether the loader supports cascade loading the different faces.
  91563. */
  91564. this.supportCascades = true;
  91565. }
  91566. /**
  91567. * This returns if the loader support the current file information.
  91568. * @param extension defines the file extension of the file being loaded
  91569. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91570. * @param fallback defines the fallback internal texture if any
  91571. * @param isBase64 defines whether the texture is encoded as a base64
  91572. * @param isBuffer defines whether the texture data are stored as a buffer
  91573. * @returns true if the loader can load the specified file
  91574. */
  91575. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91576. return extension.indexOf(".dds") === 0;
  91577. };
  91578. /**
  91579. * Transform the url before loading if required.
  91580. * @param rootUrl the url of the texture
  91581. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91582. * @returns the transformed texture
  91583. */
  91584. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91585. return rootUrl;
  91586. };
  91587. /**
  91588. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91589. * @param rootUrl the url of the texture
  91590. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91591. * @returns the fallback texture
  91592. */
  91593. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91594. return null;
  91595. };
  91596. /**
  91597. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91598. * @param data contains the texture data
  91599. * @param texture defines the BabylonJS internal texture
  91600. * @param createPolynomials will be true if polynomials have been requested
  91601. * @param onLoad defines the callback to trigger once the texture is ready
  91602. * @param onError defines the callback to trigger in case of error
  91603. */
  91604. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  91605. var engine = texture.getEngine();
  91606. var info;
  91607. var loadMipmap = false;
  91608. if (Array.isArray(imgs)) {
  91609. for (var index = 0; index < imgs.length; index++) {
  91610. var data_1 = imgs[index];
  91611. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  91612. texture.width = info.width;
  91613. texture.height = info.height;
  91614. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  91615. engine._unpackFlipY(info.isCompressed);
  91616. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  91617. if (!info.isFourCC && info.mipmapCount === 1) {
  91618. engine.generateMipMapsForCubemap(texture);
  91619. }
  91620. }
  91621. }
  91622. else {
  91623. var data = imgs;
  91624. info = BABYLON.DDSTools.GetDDSInfo(data);
  91625. texture.width = info.width;
  91626. texture.height = info.height;
  91627. if (createPolynomials) {
  91628. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  91629. }
  91630. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  91631. engine._unpackFlipY(info.isCompressed);
  91632. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  91633. if (!info.isFourCC && info.mipmapCount === 1) {
  91634. engine.generateMipMapsForCubemap(texture);
  91635. }
  91636. }
  91637. engine._setCubeMapTextureParams(loadMipmap);
  91638. texture.isReady = true;
  91639. if (onLoad) {
  91640. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  91641. }
  91642. };
  91643. /**
  91644. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91645. * @param data contains the texture data
  91646. * @param texture defines the BabylonJS internal texture
  91647. * @param callback defines the method to call once ready to upload
  91648. */
  91649. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  91650. var info = BABYLON.DDSTools.GetDDSInfo(data);
  91651. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  91652. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  91653. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  91654. });
  91655. };
  91656. return DDSTextureLoader;
  91657. }());
  91658. // Register the loader.
  91659. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  91660. })(BABYLON || (BABYLON = {}));
  91661. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  91662. var BABYLON;
  91663. (function (BABYLON) {
  91664. /*
  91665. * Based on jsTGALoader - Javascript loader for TGA file
  91666. * By Vincent Thibault
  91667. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  91668. */
  91669. var TGATools = /** @class */ (function () {
  91670. function TGATools() {
  91671. }
  91672. TGATools.GetTGAHeader = function (data) {
  91673. var offset = 0;
  91674. var header = {
  91675. id_length: data[offset++],
  91676. colormap_type: data[offset++],
  91677. image_type: data[offset++],
  91678. colormap_index: data[offset++] | data[offset++] << 8,
  91679. colormap_length: data[offset++] | data[offset++] << 8,
  91680. colormap_size: data[offset++],
  91681. origin: [
  91682. data[offset++] | data[offset++] << 8,
  91683. data[offset++] | data[offset++] << 8
  91684. ],
  91685. width: data[offset++] | data[offset++] << 8,
  91686. height: data[offset++] | data[offset++] << 8,
  91687. pixel_size: data[offset++],
  91688. flags: data[offset++]
  91689. };
  91690. return header;
  91691. };
  91692. /**
  91693. * Uploads TGA content to a Babylon Texture
  91694. * @hidden
  91695. */
  91696. TGATools.UploadContent = function (texture, data) {
  91697. // Not enough data to contain header ?
  91698. if (data.length < 19) {
  91699. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  91700. return;
  91701. }
  91702. // Read Header
  91703. var offset = 18;
  91704. var header = TGATools.GetTGAHeader(data);
  91705. // Assume it's a valid Targa file.
  91706. if (header.id_length + offset > data.length) {
  91707. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  91708. return;
  91709. }
  91710. // Skip not needed data
  91711. offset += header.id_length;
  91712. var use_rle = false;
  91713. var use_pal = false;
  91714. var use_grey = false;
  91715. // Get some informations.
  91716. switch (header.image_type) {
  91717. case TGATools._TYPE_RLE_INDEXED:
  91718. use_rle = true;
  91719. case TGATools._TYPE_INDEXED:
  91720. use_pal = true;
  91721. break;
  91722. case TGATools._TYPE_RLE_RGB:
  91723. use_rle = true;
  91724. case TGATools._TYPE_RGB:
  91725. // use_rgb = true;
  91726. break;
  91727. case TGATools._TYPE_RLE_GREY:
  91728. use_rle = true;
  91729. case TGATools._TYPE_GREY:
  91730. use_grey = true;
  91731. break;
  91732. }
  91733. var pixel_data;
  91734. // var numAlphaBits = header.flags & 0xf;
  91735. var pixel_size = header.pixel_size >> 3;
  91736. var pixel_total = header.width * header.height * pixel_size;
  91737. // Read palettes
  91738. var palettes;
  91739. if (use_pal) {
  91740. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  91741. }
  91742. // Read LRE
  91743. if (use_rle) {
  91744. pixel_data = new Uint8Array(pixel_total);
  91745. var c, count, i;
  91746. var localOffset = 0;
  91747. var pixels = new Uint8Array(pixel_size);
  91748. while (offset < pixel_total && localOffset < pixel_total) {
  91749. c = data[offset++];
  91750. count = (c & 0x7f) + 1;
  91751. // RLE pixels
  91752. if (c & 0x80) {
  91753. // Bind pixel tmp array
  91754. for (i = 0; i < pixel_size; ++i) {
  91755. pixels[i] = data[offset++];
  91756. }
  91757. // Copy pixel array
  91758. for (i = 0; i < count; ++i) {
  91759. pixel_data.set(pixels, localOffset + i * pixel_size);
  91760. }
  91761. localOffset += pixel_size * count;
  91762. }
  91763. // Raw pixels
  91764. else {
  91765. count *= pixel_size;
  91766. for (i = 0; i < count; ++i) {
  91767. pixel_data[localOffset + i] = data[offset++];
  91768. }
  91769. localOffset += count;
  91770. }
  91771. }
  91772. }
  91773. // RAW Pixels
  91774. else {
  91775. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  91776. }
  91777. // Load to texture
  91778. var x_start, y_start, x_step, y_step, y_end, x_end;
  91779. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  91780. default:
  91781. case TGATools._ORIGIN_UL:
  91782. x_start = 0;
  91783. x_step = 1;
  91784. x_end = header.width;
  91785. y_start = 0;
  91786. y_step = 1;
  91787. y_end = header.height;
  91788. break;
  91789. case TGATools._ORIGIN_BL:
  91790. x_start = 0;
  91791. x_step = 1;
  91792. x_end = header.width;
  91793. y_start = header.height - 1;
  91794. y_step = -1;
  91795. y_end = -1;
  91796. break;
  91797. case TGATools._ORIGIN_UR:
  91798. x_start = header.width - 1;
  91799. x_step = -1;
  91800. x_end = -1;
  91801. y_start = 0;
  91802. y_step = 1;
  91803. y_end = header.height;
  91804. break;
  91805. case TGATools._ORIGIN_BR:
  91806. x_start = header.width - 1;
  91807. x_step = -1;
  91808. x_end = -1;
  91809. y_start = header.height - 1;
  91810. y_step = -1;
  91811. y_end = -1;
  91812. break;
  91813. }
  91814. // Load the specify method
  91815. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  91816. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  91817. var engine = texture.getEngine();
  91818. engine._uploadDataToTextureDirectly(texture, imageData);
  91819. };
  91820. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91821. var image = pixel_data, colormap = palettes;
  91822. var width = header.width, height = header.height;
  91823. var color, i = 0, x, y;
  91824. var imageData = new Uint8Array(width * height * 4);
  91825. for (y = y_start; y !== y_end; y += y_step) {
  91826. for (x = x_start; x !== x_end; x += x_step, i++) {
  91827. color = image[i];
  91828. imageData[(x + width * y) * 4 + 3] = 255;
  91829. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  91830. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  91831. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  91832. }
  91833. }
  91834. return imageData;
  91835. };
  91836. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91837. var image = pixel_data;
  91838. var width = header.width, height = header.height;
  91839. var color, i = 0, x, y;
  91840. var imageData = new Uint8Array(width * height * 4);
  91841. for (y = y_start; y !== y_end; y += y_step) {
  91842. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  91843. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  91844. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  91845. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  91846. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  91847. imageData[(x + width * y) * 4 + 0] = r;
  91848. imageData[(x + width * y) * 4 + 1] = g;
  91849. imageData[(x + width * y) * 4 + 2] = b;
  91850. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  91851. }
  91852. }
  91853. return imageData;
  91854. };
  91855. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91856. var image = pixel_data;
  91857. var width = header.width, height = header.height;
  91858. var i = 0, x, y;
  91859. var imageData = new Uint8Array(width * height * 4);
  91860. for (y = y_start; y !== y_end; y += y_step) {
  91861. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  91862. imageData[(x + width * y) * 4 + 3] = 255;
  91863. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  91864. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  91865. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  91866. }
  91867. }
  91868. return imageData;
  91869. };
  91870. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91871. var image = pixel_data;
  91872. var width = header.width, height = header.height;
  91873. var i = 0, x, y;
  91874. var imageData = new Uint8Array(width * height * 4);
  91875. for (y = y_start; y !== y_end; y += y_step) {
  91876. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  91877. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  91878. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  91879. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  91880. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  91881. }
  91882. }
  91883. return imageData;
  91884. };
  91885. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91886. var image = pixel_data;
  91887. var width = header.width, height = header.height;
  91888. var color, i = 0, x, y;
  91889. var imageData = new Uint8Array(width * height * 4);
  91890. for (y = y_start; y !== y_end; y += y_step) {
  91891. for (x = x_start; x !== x_end; x += x_step, i++) {
  91892. color = image[i];
  91893. imageData[(x + width * y) * 4 + 0] = color;
  91894. imageData[(x + width * y) * 4 + 1] = color;
  91895. imageData[(x + width * y) * 4 + 2] = color;
  91896. imageData[(x + width * y) * 4 + 3] = 255;
  91897. }
  91898. }
  91899. return imageData;
  91900. };
  91901. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91902. var image = pixel_data;
  91903. var width = header.width, height = header.height;
  91904. var i = 0, x, y;
  91905. var imageData = new Uint8Array(width * height * 4);
  91906. for (y = y_start; y !== y_end; y += y_step) {
  91907. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  91908. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  91909. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  91910. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  91911. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  91912. }
  91913. }
  91914. return imageData;
  91915. };
  91916. //private static _TYPE_NO_DATA = 0;
  91917. TGATools._TYPE_INDEXED = 1;
  91918. TGATools._TYPE_RGB = 2;
  91919. TGATools._TYPE_GREY = 3;
  91920. TGATools._TYPE_RLE_INDEXED = 9;
  91921. TGATools._TYPE_RLE_RGB = 10;
  91922. TGATools._TYPE_RLE_GREY = 11;
  91923. TGATools._ORIGIN_MASK = 0x30;
  91924. TGATools._ORIGIN_SHIFT = 0x04;
  91925. TGATools._ORIGIN_BL = 0x00;
  91926. TGATools._ORIGIN_BR = 0x01;
  91927. TGATools._ORIGIN_UL = 0x02;
  91928. TGATools._ORIGIN_UR = 0x03;
  91929. return TGATools;
  91930. }());
  91931. BABYLON.TGATools = TGATools;
  91932. })(BABYLON || (BABYLON = {}));
  91933. //# sourceMappingURL=babylon.tga.js.map
  91934. var BABYLON;
  91935. (function (BABYLON) {
  91936. /**
  91937. * Implementation of the TGA Texture Loader.
  91938. */
  91939. var TGATextureLoader = /** @class */ (function () {
  91940. function TGATextureLoader() {
  91941. /**
  91942. * Defines wether the loader supports cascade loading the different faces.
  91943. */
  91944. this.supportCascades = false;
  91945. }
  91946. /**
  91947. * This returns if the loader support the current file information.
  91948. * @param extension defines the file extension of the file being loaded
  91949. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91950. * @param fallback defines the fallback internal texture if any
  91951. * @param isBase64 defines whether the texture is encoded as a base64
  91952. * @param isBuffer defines whether the texture data are stored as a buffer
  91953. * @returns true if the loader can load the specified file
  91954. */
  91955. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91956. return extension.indexOf(".tga") === 0;
  91957. };
  91958. /**
  91959. * Transform the url before loading if required.
  91960. * @param rootUrl the url of the texture
  91961. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91962. * @returns the transformed texture
  91963. */
  91964. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91965. return rootUrl;
  91966. };
  91967. /**
  91968. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91969. * @param rootUrl the url of the texture
  91970. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91971. * @returns the fallback texture
  91972. */
  91973. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91974. return null;
  91975. };
  91976. /**
  91977. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91978. * @param data contains the texture data
  91979. * @param texture defines the BabylonJS internal texture
  91980. * @param createPolynomials will be true if polynomials have been requested
  91981. * @param onLoad defines the callback to trigger once the texture is ready
  91982. * @param onError defines the callback to trigger in case of error
  91983. */
  91984. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  91985. throw ".env not supported in Cube.";
  91986. };
  91987. /**
  91988. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91989. * @param data contains the texture data
  91990. * @param texture defines the BabylonJS internal texture
  91991. * @param callback defines the method to call once ready to upload
  91992. */
  91993. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  91994. var uintData = new Uint8Array(data);
  91995. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  91996. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  91997. BABYLON.TGATools.UploadContent(texture, uintData);
  91998. });
  91999. };
  92000. return TGATextureLoader;
  92001. }());
  92002. // Register the loader.
  92003. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  92004. })(BABYLON || (BABYLON = {}));
  92005. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  92006. var BABYLON;
  92007. (function (BABYLON) {
  92008. /**
  92009. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  92010. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  92011. */
  92012. var KhronosTextureContainer = /** @class */ (function () {
  92013. /**
  92014. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  92015. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  92016. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  92017. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  92018. */
  92019. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  92020. this.arrayBuffer = arrayBuffer;
  92021. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  92022. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  92023. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  92024. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  92025. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  92026. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  92027. BABYLON.Tools.Error("texture missing KTX identifier");
  92028. return;
  92029. }
  92030. // load the reset of the header in native 32 bit int
  92031. var header = new Int32Array(this.arrayBuffer, 12, 13);
  92032. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  92033. var oppositeEndianess = header[0] === 0x01020304;
  92034. // read all the header elements in order they exist in the file, without modification (sans endainness)
  92035. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  92036. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  92037. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  92038. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  92039. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  92040. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  92041. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  92042. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  92043. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  92044. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  92045. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  92046. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  92047. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  92048. if (this.glType !== 0) {
  92049. BABYLON.Tools.Error("only compressed formats currently supported");
  92050. return;
  92051. }
  92052. else {
  92053. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  92054. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  92055. }
  92056. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  92057. BABYLON.Tools.Error("only 2D textures currently supported");
  92058. return;
  92059. }
  92060. if (this.numberOfArrayElements !== 0) {
  92061. BABYLON.Tools.Error("texture arrays not currently supported");
  92062. return;
  92063. }
  92064. if (this.numberOfFaces !== facesExpected) {
  92065. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  92066. return;
  92067. }
  92068. // we now have a completely validated file, so could use existence of loadType as success
  92069. // would need to make this more elaborate & adjust checks above to support more than one load type
  92070. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  92071. }
  92072. // not as fast hardware based, but will probably never need to use
  92073. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  92074. return ((val & 0xFF) << 24)
  92075. | ((val & 0xFF00) << 8)
  92076. | ((val >> 8) & 0xFF00)
  92077. | ((val >> 24) & 0xFF);
  92078. };
  92079. /**
  92080. * Uploads KTX content to a Babylon Texture.
  92081. * It is assumed that the texture has already been created & is currently bound
  92082. * @hidden
  92083. */
  92084. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  92085. switch (this.loadType) {
  92086. case KhronosTextureContainer.COMPRESSED_2D:
  92087. this._upload2DCompressedLevels(texture, loadMipmaps);
  92088. break;
  92089. case KhronosTextureContainer.TEX_2D:
  92090. case KhronosTextureContainer.COMPRESSED_3D:
  92091. case KhronosTextureContainer.TEX_3D:
  92092. }
  92093. };
  92094. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  92095. // initialize width & height for level 1
  92096. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  92097. var width = this.pixelWidth;
  92098. var height = this.pixelHeight;
  92099. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  92100. for (var level = 0; level < mipmapCount; level++) {
  92101. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  92102. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  92103. for (var face = 0; face < this.numberOfFaces; face++) {
  92104. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  92105. var engine = texture.getEngine();
  92106. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  92107. dataOffset += imageSize; // add size of the image for the next face/mipmap
  92108. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  92109. }
  92110. width = Math.max(1.0, width * 0.5);
  92111. height = Math.max(1.0, height * 0.5);
  92112. }
  92113. };
  92114. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  92115. // load types
  92116. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  92117. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  92118. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  92119. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  92120. return KhronosTextureContainer;
  92121. }());
  92122. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  92123. })(BABYLON || (BABYLON = {}));
  92124. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  92125. var BABYLON;
  92126. (function (BABYLON) {
  92127. /**
  92128. * Implementation of the KTX Texture Loader.
  92129. */
  92130. var KTXTextureLoader = /** @class */ (function () {
  92131. function KTXTextureLoader() {
  92132. /**
  92133. * Defines wether the loader supports cascade loading the different faces.
  92134. */
  92135. this.supportCascades = false;
  92136. }
  92137. /**
  92138. * This returns if the loader support the current file information.
  92139. * @param extension defines the file extension of the file being loaded
  92140. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92141. * @param fallback defines the fallback internal texture if any
  92142. * @param isBase64 defines whether the texture is encoded as a base64
  92143. * @param isBuffer defines whether the texture data are stored as a buffer
  92144. * @returns true if the loader can load the specified file
  92145. */
  92146. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  92147. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  92148. return true;
  92149. }
  92150. return false;
  92151. };
  92152. /**
  92153. * Transform the url before loading if required.
  92154. * @param rootUrl the url of the texture
  92155. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92156. * @returns the transformed texture
  92157. */
  92158. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  92159. var lastDot = rootUrl.lastIndexOf('.');
  92160. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  92161. };
  92162. /**
  92163. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  92164. * @param rootUrl the url of the texture
  92165. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92166. * @returns the fallback texture
  92167. */
  92168. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  92169. // remove the format appended to the rootUrl in the original createCubeTexture call.
  92170. var exp = new RegExp("" + textureFormatInUse + "$");
  92171. return rootUrl.replace(exp, "");
  92172. };
  92173. /**
  92174. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  92175. * @param data contains the texture data
  92176. * @param texture defines the BabylonJS internal texture
  92177. * @param createPolynomials will be true if polynomials have been requested
  92178. * @param onLoad defines the callback to trigger once the texture is ready
  92179. * @param onError defines the callback to trigger in case of error
  92180. */
  92181. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  92182. if (Array.isArray(data)) {
  92183. return;
  92184. }
  92185. var engine = texture.getEngine();
  92186. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  92187. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  92188. engine._unpackFlipY(true);
  92189. ktx.uploadLevels(texture, texture.generateMipMaps);
  92190. texture.width = ktx.pixelWidth;
  92191. texture.height = ktx.pixelHeight;
  92192. engine._setCubeMapTextureParams(loadMipmap);
  92193. texture.isReady = true;
  92194. };
  92195. /**
  92196. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  92197. * @param data contains the texture data
  92198. * @param texture defines the BabylonJS internal texture
  92199. * @param callback defines the method to call once ready to upload
  92200. */
  92201. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  92202. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  92203. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  92204. ktx.uploadLevels(texture, texture.generateMipMaps);
  92205. });
  92206. };
  92207. return KTXTextureLoader;
  92208. }());
  92209. // Register the loader.
  92210. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  92211. })(BABYLON || (BABYLON = {}));
  92212. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  92213. var BABYLON;
  92214. (function (BABYLON) {
  92215. /**
  92216. * Sets of helpers addressing the serialization and deserialization of environment texture
  92217. * stored in a BabylonJS env file.
  92218. * Those files are usually stored as .env files.
  92219. */
  92220. var EnvironmentTextureTools = /** @class */ (function () {
  92221. function EnvironmentTextureTools() {
  92222. }
  92223. /**
  92224. * Gets the environment info from an env file.
  92225. * @param data The array buffer containing the .env bytes.
  92226. * @returns the environment file info (the json header) if successfully parsed.
  92227. */
  92228. EnvironmentTextureTools.GetEnvInfo = function (data) {
  92229. var dataView = new DataView(data);
  92230. var pos = 0;
  92231. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  92232. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  92233. BABYLON.Tools.Error('Not a babylon environment map');
  92234. return null;
  92235. }
  92236. }
  92237. // Read json manifest - collect characters up to null terminator
  92238. var manifestString = '';
  92239. var charCode = 0x00;
  92240. while ((charCode = dataView.getUint8(pos++))) {
  92241. manifestString += String.fromCharCode(charCode);
  92242. }
  92243. var manifest = JSON.parse(manifestString);
  92244. if (manifest.specular) {
  92245. // Extend the header with the position of the payload.
  92246. manifest.specular.specularDataPosition = pos;
  92247. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  92248. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  92249. }
  92250. return manifest;
  92251. };
  92252. /**
  92253. * Creates an environment texture from a loaded cube texture.
  92254. * @param texture defines the cube texture to convert in env file
  92255. * @return a promise containing the environment data if succesfull.
  92256. */
  92257. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  92258. var _this = this;
  92259. var internalTexture = texture.getInternalTexture();
  92260. if (!internalTexture) {
  92261. return Promise.reject("The cube texture is invalid.");
  92262. }
  92263. if (!texture._prefiltered) {
  92264. return Promise.reject("The cube texture is invalid (not prefiltered).");
  92265. }
  92266. var engine = internalTexture.getEngine();
  92267. if (engine && engine.premultipliedAlpha) {
  92268. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  92269. }
  92270. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  92271. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  92272. }
  92273. var canvas = engine.getRenderingCanvas();
  92274. if (!canvas) {
  92275. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  92276. }
  92277. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  92278. if (!engine.getCaps().textureFloatRender) {
  92279. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92280. if (!engine.getCaps().textureHalfFloatRender) {
  92281. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  92282. }
  92283. }
  92284. var cubeWidth = internalTexture.width;
  92285. var hostingScene = new BABYLON.Scene(engine);
  92286. var specularTextures = {};
  92287. var promises = [];
  92288. // Read and collect all mipmaps data from the cube.
  92289. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  92290. mipmapsCount = Math.round(mipmapsCount);
  92291. var _loop_1 = function (i) {
  92292. var faceWidth = Math.pow(2, mipmapsCount - i);
  92293. var _loop_2 = function (face) {
  92294. var data = texture.readPixels(face, i);
  92295. // Creates a temp texture with the face data.
  92296. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  92297. // And rgbdEncode them.
  92298. var promise = new Promise(function (resolve, reject) {
  92299. 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);
  92300. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  92301. rgbdPostProcess.onApply = function (effect) {
  92302. effect._bindTexture("textureSampler", tempTexture);
  92303. };
  92304. // As the process needs to happen on the main canvas, keep track of the current size
  92305. var currentW = engine.getRenderWidth();
  92306. var currentH = engine.getRenderHeight();
  92307. // Set the desired size for the texture
  92308. engine.setSize(faceWidth, faceWidth);
  92309. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  92310. // Reading datas from WebGL
  92311. BABYLON.Tools.ToBlob(canvas, function (blob) {
  92312. var fileReader = new FileReader();
  92313. fileReader.onload = function (event) {
  92314. var arrayBuffer = event.target.result;
  92315. specularTextures[i * 6 + face] = arrayBuffer;
  92316. resolve();
  92317. };
  92318. fileReader.readAsArrayBuffer(blob);
  92319. });
  92320. // Reapply the previous canvas size
  92321. engine.setSize(currentW, currentH);
  92322. });
  92323. });
  92324. promises.push(promise);
  92325. };
  92326. // All faces of the cube.
  92327. for (var face = 0; face < 6; face++) {
  92328. _loop_2(face);
  92329. }
  92330. };
  92331. for (var i = 0; i <= mipmapsCount; i++) {
  92332. _loop_1(i);
  92333. }
  92334. // Once all the textures haves been collected as RGBD stored in PNGs
  92335. return Promise.all(promises).then(function () {
  92336. // We can delete the hosting scene keeping track of all the creation objects
  92337. hostingScene.dispose();
  92338. // Creates the json header for the env texture
  92339. var info = {
  92340. version: 1,
  92341. width: cubeWidth,
  92342. irradiance: _this._CreateEnvTextureIrradiance(texture),
  92343. specular: {
  92344. mipmaps: [],
  92345. lodGenerationScale: texture.lodGenerationScale
  92346. }
  92347. };
  92348. // Sets the specular image data information
  92349. var position = 0;
  92350. for (var i = 0; i <= mipmapsCount; i++) {
  92351. for (var face = 0; face < 6; face++) {
  92352. var byteLength = specularTextures[i * 6 + face].byteLength;
  92353. info.specular.mipmaps.push({
  92354. length: byteLength,
  92355. position: position
  92356. });
  92357. position += byteLength;
  92358. }
  92359. }
  92360. // Encode the JSON as an array buffer
  92361. var infoString = JSON.stringify(info);
  92362. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  92363. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  92364. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  92365. infoView[i] = infoString.charCodeAt(i);
  92366. }
  92367. // Ends up with a null terminator for easier parsing
  92368. infoView[infoString.length] = 0x00;
  92369. // Computes the final required size and creates the storage
  92370. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  92371. var finalBuffer = new ArrayBuffer(totalSize);
  92372. var finalBufferView = new Uint8Array(finalBuffer);
  92373. var dataView = new DataView(finalBuffer);
  92374. // Copy the magic bytes identifying the file in
  92375. var pos = 0;
  92376. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  92377. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  92378. }
  92379. // Add the json info
  92380. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  92381. pos += infoBuffer.byteLength;
  92382. // Finally inserts the texture data
  92383. for (var i = 0; i <= mipmapsCount; i++) {
  92384. for (var face = 0; face < 6; face++) {
  92385. var dataBuffer = specularTextures[i * 6 + face];
  92386. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  92387. pos += dataBuffer.byteLength;
  92388. }
  92389. }
  92390. // Voila
  92391. return finalBuffer;
  92392. });
  92393. };
  92394. /**
  92395. * Creates a JSON representation of the spherical data.
  92396. * @param texture defines the texture containing the polynomials
  92397. * @return the JSON representation of the spherical info
  92398. */
  92399. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  92400. var polynmials = texture.sphericalPolynomial;
  92401. if (polynmials == null) {
  92402. return null;
  92403. }
  92404. return {
  92405. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  92406. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  92407. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  92408. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  92409. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  92410. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  92411. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  92412. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  92413. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  92414. };
  92415. };
  92416. /**
  92417. * Uploads the texture info contained in the env file to the GPU.
  92418. * @param texture defines the internal texture to upload to
  92419. * @param arrayBuffer defines the buffer cotaining the data to load
  92420. * @param info defines the texture info retrieved through the GetEnvInfo method
  92421. * @returns a promise
  92422. */
  92423. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  92424. if (info.version !== 1) {
  92425. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  92426. }
  92427. var specularInfo = info.specular;
  92428. if (!specularInfo) {
  92429. // Nothing else parsed so far
  92430. return Promise.resolve();
  92431. }
  92432. // Double checks the enclosed info
  92433. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  92434. mipmapsCount = Math.round(mipmapsCount) + 1;
  92435. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  92436. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  92437. }
  92438. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  92439. var imageData = new Array(mipmapsCount);
  92440. for (var i = 0; i < mipmapsCount; i++) {
  92441. imageData[i] = new Array(6);
  92442. for (var face = 0; face < 6; face++) {
  92443. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  92444. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  92445. }
  92446. }
  92447. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  92448. };
  92449. /**
  92450. * Uploads the levels of image data to the GPU.
  92451. * @param texture defines the internal texture to upload to
  92452. * @param imageData defines the array buffer views of image data [mipmap][face]
  92453. * @returns a promise
  92454. */
  92455. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  92456. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  92457. throw new Error("Texture size must be a power of two");
  92458. }
  92459. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  92460. // Gets everything ready.
  92461. var engine = texture.getEngine();
  92462. var expandTexture = false;
  92463. var generateNonLODTextures = false;
  92464. var rgbdPostProcess = null;
  92465. var cubeRtt = null;
  92466. var lodTextures = null;
  92467. var caps = engine.getCaps();
  92468. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  92469. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92470. texture.generateMipMaps = true;
  92471. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  92472. // Add extra process if texture lod is not supported
  92473. if (!caps.textureLOD) {
  92474. expandTexture = false;
  92475. generateNonLODTextures = true;
  92476. lodTextures = {};
  92477. }
  92478. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  92479. else if (engine.webGLVersion < 2) {
  92480. expandTexture = false;
  92481. }
  92482. // If half float available we can uncompress the texture
  92483. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  92484. expandTexture = true;
  92485. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92486. }
  92487. // If full float available we can uncompress the texture
  92488. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  92489. expandTexture = true;
  92490. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  92491. }
  92492. // Expand the texture if possible
  92493. if (expandTexture) {
  92494. // Simply run through the decode PP
  92495. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  92496. texture._isRGBD = false;
  92497. texture.invertY = false;
  92498. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  92499. generateDepthBuffer: false,
  92500. generateMipMaps: true,
  92501. generateStencilBuffer: false,
  92502. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  92503. type: texture.type,
  92504. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  92505. });
  92506. }
  92507. else {
  92508. texture._isRGBD = true;
  92509. texture.invertY = true;
  92510. // In case of missing support, applies the same patch than DDS files.
  92511. if (generateNonLODTextures) {
  92512. var mipSlices = 3;
  92513. var scale = texture._lodGenerationScale;
  92514. var offset = texture._lodGenerationOffset;
  92515. for (var i = 0; i < mipSlices; i++) {
  92516. //compute LOD from even spacing in smoothness (matching shader calculation)
  92517. var smoothness = i / (mipSlices - 1);
  92518. var roughness = 1 - smoothness;
  92519. var minLODIndex = offset; // roughness = 0
  92520. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  92521. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  92522. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  92523. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  92524. glTextureFromLod.isCube = true;
  92525. glTextureFromLod.invertY = true;
  92526. glTextureFromLod.generateMipMaps = false;
  92527. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  92528. // Wrap in a base texture for easy binding.
  92529. var lodTexture = new BABYLON.BaseTexture(null);
  92530. lodTexture.isCube = true;
  92531. lodTexture._texture = glTextureFromLod;
  92532. lodTextures[mipmapIndex] = lodTexture;
  92533. switch (i) {
  92534. case 0:
  92535. texture._lodTextureLow = lodTexture;
  92536. break;
  92537. case 1:
  92538. texture._lodTextureMid = lodTexture;
  92539. break;
  92540. case 2:
  92541. texture._lodTextureHigh = lodTexture;
  92542. break;
  92543. }
  92544. }
  92545. }
  92546. }
  92547. var promises = [];
  92548. var _loop_3 = function (i) {
  92549. var _loop_4 = function (face) {
  92550. // Constructs an image element from image data
  92551. var bytes = imageData[i][face];
  92552. var blob = new Blob([bytes], { type: 'image/png' });
  92553. var url = URL.createObjectURL(blob);
  92554. var image = new Image();
  92555. image.src = url;
  92556. // Enqueue promise to upload to the texture.
  92557. var promise = new Promise(function (resolve, reject) {
  92558. image.onload = function () {
  92559. if (expandTexture) {
  92560. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  92561. reject(message);
  92562. }, image);
  92563. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  92564. // Uncompress the data to a RTT
  92565. rgbdPostProcess.onApply = function (effect) {
  92566. effect._bindTexture("textureSampler", tempTexture_1);
  92567. effect.setFloat2("scale", 1, 1);
  92568. };
  92569. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  92570. // Cleanup
  92571. engine.restoreDefaultFramebuffer();
  92572. tempTexture_1.dispose();
  92573. window.URL.revokeObjectURL(url);
  92574. resolve();
  92575. });
  92576. }
  92577. else {
  92578. engine._uploadImageToTexture(texture, image, face, i);
  92579. // Upload the face to the non lod texture support
  92580. if (generateNonLODTextures) {
  92581. var lodTexture = lodTextures[i];
  92582. if (lodTexture) {
  92583. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  92584. }
  92585. }
  92586. resolve();
  92587. }
  92588. };
  92589. image.onerror = function (error) {
  92590. reject(error);
  92591. };
  92592. });
  92593. promises.push(promise);
  92594. };
  92595. // All faces
  92596. for (var face = 0; face < 6; face++) {
  92597. _loop_4(face);
  92598. }
  92599. };
  92600. // All mipmaps up to provided number of images
  92601. for (var i = 0; i < imageData.length; i++) {
  92602. _loop_3(i);
  92603. }
  92604. // Fill remaining mipmaps with black textures.
  92605. if (imageData.length < mipmapsCount) {
  92606. var data = void 0;
  92607. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  92608. var dataLength = size * size * 4;
  92609. switch (texture.type) {
  92610. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  92611. data = new Uint8Array(dataLength);
  92612. break;
  92613. }
  92614. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  92615. data = new Uint16Array(dataLength);
  92616. break;
  92617. }
  92618. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  92619. data = new Float32Array(dataLength);
  92620. break;
  92621. }
  92622. }
  92623. for (var i = imageData.length; i < mipmapsCount; i++) {
  92624. for (var face = 0; face < 6; face++) {
  92625. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  92626. }
  92627. }
  92628. }
  92629. // Once all done, finishes the cleanup and return
  92630. return Promise.all(promises).then(function () {
  92631. // Release temp RTT.
  92632. if (cubeRtt) {
  92633. engine._releaseFramebufferObjects(cubeRtt);
  92634. cubeRtt._swapAndDie(texture);
  92635. }
  92636. // Release temp Post Process.
  92637. if (rgbdPostProcess) {
  92638. rgbdPostProcess.dispose();
  92639. }
  92640. // Flag internal texture as ready in case they are in use.
  92641. if (generateNonLODTextures) {
  92642. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  92643. texture._lodTextureHigh._texture.isReady = true;
  92644. }
  92645. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  92646. texture._lodTextureMid._texture.isReady = true;
  92647. }
  92648. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  92649. texture._lodTextureLow._texture.isReady = true;
  92650. }
  92651. }
  92652. });
  92653. };
  92654. /**
  92655. * Uploads spherical polynomials information to the texture.
  92656. * @param texture defines the texture we are trying to upload the information to
  92657. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  92658. */
  92659. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  92660. if (info.version !== 1) {
  92661. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  92662. }
  92663. var irradianceInfo = info.irradiance;
  92664. if (!irradianceInfo) {
  92665. return;
  92666. }
  92667. var sp = new BABYLON.SphericalPolynomial();
  92668. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  92669. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  92670. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  92671. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  92672. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  92673. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  92674. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  92675. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  92676. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  92677. texture._sphericalPolynomial = sp;
  92678. };
  92679. /**
  92680. * Magic number identifying the env file.
  92681. */
  92682. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  92683. return EnvironmentTextureTools;
  92684. }());
  92685. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  92686. })(BABYLON || (BABYLON = {}));
  92687. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  92688. var BABYLON;
  92689. (function (BABYLON) {
  92690. /**
  92691. * Implementation of the ENV Texture Loader.
  92692. */
  92693. var ENVTextureLoader = /** @class */ (function () {
  92694. function ENVTextureLoader() {
  92695. /**
  92696. * Defines wether the loader supports cascade loading the different faces.
  92697. */
  92698. this.supportCascades = false;
  92699. }
  92700. /**
  92701. * This returns if the loader support the current file information.
  92702. * @param extension defines the file extension of the file being loaded
  92703. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92704. * @param fallback defines the fallback internal texture if any
  92705. * @param isBase64 defines whether the texture is encoded as a base64
  92706. * @param isBuffer defines whether the texture data are stored as a buffer
  92707. * @returns true if the loader can load the specified file
  92708. */
  92709. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  92710. return extension.indexOf(".env") === 0;
  92711. };
  92712. /**
  92713. * Transform the url before loading if required.
  92714. * @param rootUrl the url of the texture
  92715. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92716. * @returns the transformed texture
  92717. */
  92718. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  92719. return rootUrl;
  92720. };
  92721. /**
  92722. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  92723. * @param rootUrl the url of the texture
  92724. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92725. * @returns the fallback texture
  92726. */
  92727. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  92728. return null;
  92729. };
  92730. /**
  92731. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  92732. * @param data contains the texture data
  92733. * @param texture defines the BabylonJS internal texture
  92734. * @param createPolynomials will be true if polynomials have been requested
  92735. * @param onLoad defines the callback to trigger once the texture is ready
  92736. * @param onError defines the callback to trigger in case of error
  92737. */
  92738. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  92739. if (Array.isArray(data)) {
  92740. return;
  92741. }
  92742. data = data;
  92743. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  92744. if (info) {
  92745. texture.width = info.width;
  92746. texture.height = info.width;
  92747. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  92748. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  92749. texture.isReady = true;
  92750. if (onLoad) {
  92751. onLoad();
  92752. }
  92753. });
  92754. }
  92755. else if (onError) {
  92756. onError("Can not parse the environment file", null);
  92757. }
  92758. };
  92759. /**
  92760. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  92761. * @param data contains the texture data
  92762. * @param texture defines the BabylonJS internal texture
  92763. * @param callback defines the method to call once ready to upload
  92764. */
  92765. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  92766. throw ".env not supported in 2d.";
  92767. };
  92768. return ENVTextureLoader;
  92769. }());
  92770. // Register the loader.
  92771. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  92772. })(BABYLON || (BABYLON = {}));
  92773. //# sourceMappingURL=babylon.envTextureLoader.js.map
  92774. var BABYLON;
  92775. (function (BABYLON) {
  92776. /**
  92777. * Renders a layer on top of an existing scene
  92778. */
  92779. var UtilityLayerRenderer = /** @class */ (function () {
  92780. /**
  92781. * Instantiates a UtilityLayerRenderer
  92782. * @param originalScene the original scene that will be rendered on top of
  92783. */
  92784. function UtilityLayerRenderer(
  92785. /** the original scene that will be rendered on top of */
  92786. originalScene) {
  92787. var _this = this;
  92788. this.originalScene = originalScene;
  92789. this._pointerCaptures = {};
  92790. this._lastPointerEvents = {};
  92791. /**
  92792. * If the utility layer should automatically be rendered on top of existing scene
  92793. */
  92794. this.shouldRender = true;
  92795. /**
  92796. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  92797. */
  92798. this.onlyCheckPointerDownEvents = true;
  92799. /**
  92800. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  92801. */
  92802. this.processAllEvents = false;
  92803. /**
  92804. * Observable raised when the pointer move from the utility layer scene to the main scene
  92805. */
  92806. this.onPointerOutObservable = new BABYLON.Observable();
  92807. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  92808. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  92809. this.utilityLayerScene._allowPostProcessClearColor = false;
  92810. originalScene.getEngine().scenes.pop();
  92811. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  92812. this.utilityLayerScene.detachControl();
  92813. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  92814. if (!_this.processAllEvents) {
  92815. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  92816. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  92817. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  92818. return;
  92819. }
  92820. }
  92821. var pointerEvent = (prePointerInfo.event);
  92822. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  92823. _this._pointerCaptures[pointerEvent.pointerId] = false;
  92824. return;
  92825. }
  92826. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  92827. if (!prePointerInfo.ray && utilityScenePick) {
  92828. prePointerInfo.ray = utilityScenePick.ray;
  92829. }
  92830. // always fire the prepointer oversvable
  92831. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  92832. // allow every non pointer down event to flow to the utility layer
  92833. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  92834. if (!prePointerInfo.skipOnPointerObservable) {
  92835. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  92836. }
  92837. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  92838. _this._pointerCaptures[pointerEvent.pointerId] = false;
  92839. }
  92840. return;
  92841. }
  92842. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  92843. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  92844. if (utilityScenePick && utilityScenePick.hit) {
  92845. if (!prePointerInfo.skipOnPointerObservable) {
  92846. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  92847. }
  92848. prePointerInfo.skipOnPointerObservable = true;
  92849. }
  92850. }
  92851. else {
  92852. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  92853. var pointerEvent_1 = (prePointerInfo.event);
  92854. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  92855. if (originalScenePick && utilityScenePick) {
  92856. // No pick in utility scene
  92857. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  92858. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  92859. // We touched an utility mesh present in the main scene
  92860. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  92861. prePointerInfo.skipOnPointerObservable = true;
  92862. }
  92863. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  92864. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  92865. }
  92866. }
  92867. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  92868. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  92869. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  92870. // If a previous utility layer set this, do not unset this
  92871. if (!prePointerInfo.skipOnPointerObservable) {
  92872. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  92873. }
  92874. }
  92875. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  92876. // We have a pick in both scenes but main is closer than utility
  92877. // We touched an utility mesh present in the main scene
  92878. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  92879. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  92880. prePointerInfo.skipOnPointerObservable = true;
  92881. }
  92882. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  92883. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  92884. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  92885. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  92886. }
  92887. }
  92888. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  92889. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  92890. }
  92891. }
  92892. }
  92893. });
  92894. // Render directly on top of existing scene without clearing
  92895. this.utilityLayerScene.autoClear = false;
  92896. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  92897. if (_this.shouldRender) {
  92898. _this.render();
  92899. }
  92900. });
  92901. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  92902. _this.dispose();
  92903. });
  92904. this._updateCamera();
  92905. }
  92906. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  92907. /**
  92908. * 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)
  92909. */
  92910. get: function () {
  92911. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  92912. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  92913. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  92914. UtilityLayerRenderer._DefaultUtilityLayer = null;
  92915. });
  92916. }
  92917. return UtilityLayerRenderer._DefaultUtilityLayer;
  92918. },
  92919. enumerable: true,
  92920. configurable: true
  92921. });
  92922. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  92923. /**
  92924. * 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)
  92925. */
  92926. get: function () {
  92927. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  92928. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  92929. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  92930. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  92931. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  92932. });
  92933. }
  92934. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  92935. },
  92936. enumerable: true,
  92937. configurable: true
  92938. });
  92939. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  92940. if (!prePointerInfo.skipOnPointerObservable) {
  92941. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  92942. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  92943. }
  92944. };
  92945. /**
  92946. * Renders the utility layers scene on top of the original scene
  92947. */
  92948. UtilityLayerRenderer.prototype.render = function () {
  92949. this._updateCamera();
  92950. if (this.utilityLayerScene.activeCamera) {
  92951. // Set the camera's scene to utility layers scene
  92952. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  92953. var camera = this.utilityLayerScene.activeCamera;
  92954. camera._scene = this.utilityLayerScene;
  92955. if (camera.leftCamera) {
  92956. camera.leftCamera._scene = this.utilityLayerScene;
  92957. }
  92958. if (camera.rightCamera) {
  92959. camera.rightCamera._scene = this.utilityLayerScene;
  92960. }
  92961. this.utilityLayerScene.render(false);
  92962. // Reset camera's scene back to original
  92963. camera._scene = oldScene;
  92964. if (camera.leftCamera) {
  92965. camera.leftCamera._scene = oldScene;
  92966. }
  92967. if (camera.rightCamera) {
  92968. camera.rightCamera._scene = oldScene;
  92969. }
  92970. }
  92971. };
  92972. /**
  92973. * Disposes of the renderer
  92974. */
  92975. UtilityLayerRenderer.prototype.dispose = function () {
  92976. this.onPointerOutObservable.clear();
  92977. if (this._afterRenderObserver) {
  92978. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  92979. }
  92980. if (this._sceneDisposeObserver) {
  92981. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  92982. }
  92983. if (this._originalPointerObserver) {
  92984. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  92985. }
  92986. this.utilityLayerScene.dispose();
  92987. };
  92988. UtilityLayerRenderer.prototype._updateCamera = function () {
  92989. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  92990. };
  92991. UtilityLayerRenderer._DefaultUtilityLayer = null;
  92992. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  92993. return UtilityLayerRenderer;
  92994. }());
  92995. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  92996. })(BABYLON || (BABYLON = {}));
  92997. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  92998. //# sourceMappingURL=babylon.behavior.js.map
  92999. var BABYLON;
  93000. (function (BABYLON) {
  93001. /**
  93002. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  93003. */
  93004. var PointerDragBehavior = /** @class */ (function () {
  93005. /**
  93006. * Creates a pointer drag behavior that can be attached to a mesh
  93007. * @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)
  93008. */
  93009. function PointerDragBehavior(options) {
  93010. /**
  93011. * 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)
  93012. */
  93013. this.maxDragAngle = 0;
  93014. /**
  93015. * @hidden
  93016. */
  93017. this._useAlternatePickedPointAboveMaxDragAngle = false;
  93018. /**
  93019. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  93020. */
  93021. this.currentDraggingPointerID = -1;
  93022. /**
  93023. * If the behavior is currently in a dragging state
  93024. */
  93025. this.dragging = false;
  93026. /**
  93027. * 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)
  93028. */
  93029. this.dragDeltaRatio = 0.2;
  93030. /**
  93031. * If the drag plane orientation should be updated during the dragging (Default: true)
  93032. */
  93033. this.updateDragPlane = true;
  93034. // Debug mode will display drag planes to help visualize behavior
  93035. this._debugMode = false;
  93036. this._moving = false;
  93037. /**
  93038. * Fires each time the attached mesh is dragged with the pointer
  93039. * * delta between last drag position and current drag position in world space
  93040. * * dragDistance along the drag axis
  93041. * * dragPlaneNormal normal of the current drag plane used during the drag
  93042. * * dragPlanePoint in world space where the drag intersects the drag plane
  93043. */
  93044. this.onDragObservable = new BABYLON.Observable();
  93045. /**
  93046. * Fires each time a drag begins (eg. mouse down on mesh)
  93047. */
  93048. this.onDragStartObservable = new BABYLON.Observable();
  93049. /**
  93050. * Fires each time a drag ends (eg. mouse release after drag)
  93051. */
  93052. this.onDragEndObservable = new BABYLON.Observable();
  93053. /**
  93054. * If the attached mesh should be moved when dragged
  93055. */
  93056. this.moveAttached = true;
  93057. /**
  93058. * If the drag behavior will react to drag events (Default: true)
  93059. */
  93060. this.enabled = true;
  93061. /**
  93062. * If camera controls should be detached during the drag
  93063. */
  93064. this.detachCameraControls = true;
  93065. /**
  93066. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  93067. */
  93068. this.useObjectOrienationForDragging = true;
  93069. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  93070. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  93071. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  93072. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  93073. this._attachedElement = null;
  93074. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  93075. this._lastPointerRay = {};
  93076. this._dragDelta = new BABYLON.Vector3();
  93077. // Variables to avoid instantiation in the below method
  93078. this._pointA = new BABYLON.Vector3(0, 0, 0);
  93079. this._pointB = new BABYLON.Vector3(0, 0, 0);
  93080. this._pointC = new BABYLON.Vector3(0, 0, 0);
  93081. this._lineA = new BABYLON.Vector3(0, 0, 0);
  93082. this._lineB = new BABYLON.Vector3(0, 0, 0);
  93083. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  93084. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  93085. this._options = options ? options : {};
  93086. var optionCount = 0;
  93087. if (this._options.dragAxis) {
  93088. optionCount++;
  93089. }
  93090. if (this._options.dragPlaneNormal) {
  93091. optionCount++;
  93092. }
  93093. if (optionCount > 1) {
  93094. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  93095. }
  93096. }
  93097. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  93098. /**
  93099. * The name of the behavior
  93100. */
  93101. get: function () {
  93102. return "PointerDrag";
  93103. },
  93104. enumerable: true,
  93105. configurable: true
  93106. });
  93107. /**
  93108. * Initializes the behavior
  93109. */
  93110. PointerDragBehavior.prototype.init = function () { };
  93111. /**
  93112. * Attaches the drag behavior the passed in mesh
  93113. * @param ownerNode The mesh that will be dragged around once attached
  93114. */
  93115. PointerDragBehavior.prototype.attach = function (ownerNode) {
  93116. var _this = this;
  93117. this._scene = ownerNode.getScene();
  93118. this._attachedNode = ownerNode;
  93119. // Initialize drag plane to not interfere with existing scene
  93120. if (!PointerDragBehavior._planeScene) {
  93121. if (this._debugMode) {
  93122. PointerDragBehavior._planeScene = this._scene;
  93123. }
  93124. else {
  93125. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  93126. PointerDragBehavior._planeScene.detachControl();
  93127. this._scene.getEngine().scenes.pop();
  93128. this._scene.onDisposeObservable.addOnce(function () {
  93129. PointerDragBehavior._planeScene.dispose();
  93130. PointerDragBehavior._planeScene = null;
  93131. });
  93132. }
  93133. }
  93134. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  93135. // State of the drag
  93136. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  93137. var pickPredicate = function (m) {
  93138. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  93139. };
  93140. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  93141. if (!_this.enabled) {
  93142. return;
  93143. }
  93144. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  93145. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  93146. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  93147. }
  93148. }
  93149. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  93150. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  93151. _this.releaseDrag();
  93152. }
  93153. }
  93154. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  93155. var pointerId = pointerInfo.event.pointerId;
  93156. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  93157. if (!_this._lastPointerRay[pointerId]) {
  93158. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  93159. }
  93160. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  93161. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  93162. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  93163. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  93164. _this._moveDrag(pointerInfo.pickInfo.ray);
  93165. }
  93166. }
  93167. }
  93168. });
  93169. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  93170. if (_this._moving && _this.moveAttached) {
  93171. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  93172. // Slowly move mesh to avoid jitter
  93173. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  93174. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  93175. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  93176. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  93177. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  93178. }
  93179. });
  93180. };
  93181. PointerDragBehavior.prototype.releaseDrag = function () {
  93182. this.dragging = false;
  93183. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  93184. this.currentDraggingPointerID = -1;
  93185. this._moving = false;
  93186. // Reattach camera controls
  93187. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  93188. this._scene.activeCamera.attachControl(this._attachedElement, true);
  93189. }
  93190. };
  93191. /**
  93192. * Simulates the start of a pointer drag event on the behavior
  93193. * @param pointerId pointerID of the pointer that should be simulated (Default: 1 for mouse pointer)
  93194. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  93195. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  93196. */
  93197. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  93198. if (pointerId === void 0) { pointerId = 1; }
  93199. this._startDrag(pointerId, fromRay, startPickedPoint);
  93200. if (this._lastPointerRay[pointerId]) {
  93201. // if there was a last pointer ray drag the object there
  93202. this._moveDrag(this._lastPointerRay[pointerId]);
  93203. }
  93204. };
  93205. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  93206. if (pointerId === void 0) { pointerId = 1; }
  93207. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  93208. return;
  93209. }
  93210. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  93211. // Create start ray from the camera to the object
  93212. if (fromRay) {
  93213. this._startDragRay.direction.copyFrom(fromRay.direction);
  93214. this._startDragRay.origin.copyFrom(fromRay.origin);
  93215. }
  93216. else {
  93217. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  93218. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  93219. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  93220. }
  93221. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  93222. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  93223. if (pickedPoint) {
  93224. this.dragging = true;
  93225. this.currentDraggingPointerID = pointerId;
  93226. this.lastDragPosition.copyFrom(pickedPoint);
  93227. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  93228. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  93229. // Detatch camera controls
  93230. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  93231. if (this._scene.activeCamera.inputs.attachedElement) {
  93232. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  93233. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  93234. }
  93235. else {
  93236. this._attachedElement = null;
  93237. }
  93238. }
  93239. }
  93240. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  93241. };
  93242. PointerDragBehavior.prototype._moveDrag = function (ray) {
  93243. this._moving = true;
  93244. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  93245. if (pickedPoint) {
  93246. if (this.updateDragPlane) {
  93247. this._updateDragPlanePosition(ray, pickedPoint);
  93248. }
  93249. var dragLength = 0;
  93250. // depending on the drag mode option drag accordingly
  93251. if (this._options.dragAxis) {
  93252. // Convert local drag axis to world
  93253. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  93254. // Project delta drag from the drag plane onto the drag axis
  93255. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  93256. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  93257. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  93258. }
  93259. else {
  93260. dragLength = this._dragDelta.length();
  93261. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  93262. }
  93263. this._targetPosition.addInPlace(this._dragDelta);
  93264. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  93265. this.lastDragPosition.copyFrom(pickedPoint);
  93266. }
  93267. };
  93268. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  93269. var _this = this;
  93270. if (!ray) {
  93271. return null;
  93272. }
  93273. // Calculate angle between plane normal and ray
  93274. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  93275. // Correct if ray is casted from oposite side
  93276. if (angle > Math.PI / 2) {
  93277. angle = Math.PI - angle;
  93278. }
  93279. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  93280. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  93281. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  93282. // Invert ray direction along the towards object axis
  93283. this._tmpVector.copyFrom(ray.direction);
  93284. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  93285. this._alternatePickedPoint.normalize();
  93286. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  93287. this._tmpVector.addInPlace(this._alternatePickedPoint);
  93288. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  93289. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  93290. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  93291. this._alternatePickedPoint.addInPlace(this._tmpVector);
  93292. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  93293. return this._alternatePickedPoint;
  93294. }
  93295. else {
  93296. return null;
  93297. }
  93298. }
  93299. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  93300. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  93301. return pickResult.pickedPoint;
  93302. }
  93303. else {
  93304. return null;
  93305. }
  93306. };
  93307. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  93308. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  93309. this._pointA.copyFrom(dragPlanePosition);
  93310. if (this._options.dragAxis) {
  93311. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  93312. // Calculate plane normal in direction of camera but perpendicular to drag axis
  93313. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  93314. ray.origin.subtractToRef(this._pointA, this._pointC);
  93315. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  93316. // Get perpendicular line from direction to camera and drag axis
  93317. this._pointB.subtractToRef(this._pointA, this._lineA);
  93318. this._pointC.subtractToRef(this._pointA, this._lineB);
  93319. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  93320. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  93321. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  93322. this._lookAt.normalize();
  93323. this._dragPlane.position.copyFrom(this._pointA);
  93324. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  93325. this._dragPlane.lookAt(this._lookAt);
  93326. }
  93327. else if (this._options.dragPlaneNormal) {
  93328. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  93329. this._dragPlane.position.copyFrom(this._pointA);
  93330. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  93331. this._dragPlane.lookAt(this._lookAt);
  93332. }
  93333. else {
  93334. this._dragPlane.position.copyFrom(this._pointA);
  93335. this._dragPlane.lookAt(ray.origin);
  93336. }
  93337. this._dragPlane.computeWorldMatrix(true);
  93338. };
  93339. /**
  93340. * Detaches the behavior from the mesh
  93341. */
  93342. PointerDragBehavior.prototype.detach = function () {
  93343. if (this._pointerObserver) {
  93344. this._scene.onPointerObservable.remove(this._pointerObserver);
  93345. }
  93346. if (this._beforeRenderObserver) {
  93347. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  93348. }
  93349. };
  93350. return PointerDragBehavior;
  93351. }());
  93352. BABYLON.PointerDragBehavior = PointerDragBehavior;
  93353. })(BABYLON || (BABYLON = {}));
  93354. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  93355. var BABYLON;
  93356. (function (BABYLON) {
  93357. /**
  93358. * A behavior that when attached to a mesh will allow the mesh to be scaled
  93359. */
  93360. var MultiPointerScaleBehavior = /** @class */ (function () {
  93361. function MultiPointerScaleBehavior() {
  93362. this._startDistance = 0;
  93363. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  93364. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  93365. this._sceneRenderObserver = null;
  93366. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  93367. this._dragBehaviorA.moveAttached = false;
  93368. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  93369. this._dragBehaviorB.moveAttached = false;
  93370. }
  93371. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  93372. /**
  93373. * The name of the behavior
  93374. */
  93375. get: function () {
  93376. return "MultiPointerScale";
  93377. },
  93378. enumerable: true,
  93379. configurable: true
  93380. });
  93381. /**
  93382. * Initializes the behavior
  93383. */
  93384. MultiPointerScaleBehavior.prototype.init = function () { };
  93385. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  93386. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  93387. };
  93388. /**
  93389. * Attaches the scale behavior the passed in mesh
  93390. * @param ownerNode The mesh that will be scaled around once attached
  93391. */
  93392. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  93393. var _this = this;
  93394. this._ownerNode = ownerNode;
  93395. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  93396. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  93397. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  93398. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  93399. _this._dragBehaviorA.releaseDrag();
  93400. }
  93401. else {
  93402. _this._initialScale.copyFrom(ownerNode.scaling);
  93403. _this._startDistance = _this._getCurrentDistance();
  93404. }
  93405. }
  93406. });
  93407. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  93408. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  93409. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  93410. _this._dragBehaviorB.releaseDrag();
  93411. }
  93412. else {
  93413. _this._initialScale.copyFrom(ownerNode.scaling);
  93414. _this._startDistance = _this._getCurrentDistance();
  93415. }
  93416. }
  93417. });
  93418. // Once both drag behaviors are active scale based on the distance between the two pointers
  93419. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  93420. behavior.onDragObservable.add(function () {
  93421. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  93422. var ratio = _this._getCurrentDistance() / _this._startDistance;
  93423. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  93424. }
  93425. });
  93426. });
  93427. ownerNode.addBehavior(this._dragBehaviorA);
  93428. ownerNode.addBehavior(this._dragBehaviorB);
  93429. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  93430. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  93431. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  93432. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  93433. if (change.length() > 0.01) {
  93434. ownerNode.scaling.addInPlace(change);
  93435. }
  93436. }
  93437. });
  93438. };
  93439. /**
  93440. * Detaches the behavior from the mesh
  93441. */
  93442. MultiPointerScaleBehavior.prototype.detach = function () {
  93443. var _this = this;
  93444. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  93445. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  93446. behavior.onDragStartObservable.clear();
  93447. behavior.onDragObservable.clear();
  93448. _this._ownerNode.removeBehavior(behavior);
  93449. });
  93450. };
  93451. return MultiPointerScaleBehavior;
  93452. }());
  93453. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  93454. })(BABYLON || (BABYLON = {}));
  93455. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  93456. var BABYLON;
  93457. (function (BABYLON) {
  93458. /**
  93459. * 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
  93460. */
  93461. var SixDofDragBehavior = /** @class */ (function () {
  93462. function SixDofDragBehavior() {
  93463. this._sceneRenderObserver = null;
  93464. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  93465. this._moving = false;
  93466. this._startingOrientation = new BABYLON.Quaternion();
  93467. /**
  93468. * 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)
  93469. */
  93470. this.zDragFactor = 3;
  93471. /**
  93472. * If the behavior is currently in a dragging state
  93473. */
  93474. this.dragging = false;
  93475. /**
  93476. * 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)
  93477. */
  93478. this.dragDeltaRatio = 0.2;
  93479. /**
  93480. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  93481. */
  93482. this.currentDraggingPointerID = -1;
  93483. /**
  93484. * If camera controls should be detached during the drag
  93485. */
  93486. this.detachCameraControls = true;
  93487. }
  93488. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  93489. /**
  93490. * The name of the behavior
  93491. */
  93492. get: function () {
  93493. return "SixDofDrag";
  93494. },
  93495. enumerable: true,
  93496. configurable: true
  93497. });
  93498. /**
  93499. * Initializes the behavior
  93500. */
  93501. SixDofDragBehavior.prototype.init = function () { };
  93502. /**
  93503. * Attaches the scale behavior the passed in mesh
  93504. * @param ownerNode The mesh that will be scaled around once attached
  93505. */
  93506. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  93507. var _this = this;
  93508. this._ownerNode = ownerNode;
  93509. this._scene = this._ownerNode.getScene();
  93510. if (!SixDofDragBehavior._virtualScene) {
  93511. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  93512. this._scene.getEngine().scenes.pop();
  93513. }
  93514. var pickedMesh = null;
  93515. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  93516. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  93517. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  93518. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  93519. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  93520. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  93521. var pickPredicate = function (m) {
  93522. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  93523. };
  93524. var attachedElement = null;
  93525. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  93526. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  93527. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  93528. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  93529. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  93530. }
  93531. pickedMesh = _this._ownerNode;
  93532. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  93533. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  93534. // Set position and orientation of the controller
  93535. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  93536. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  93537. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  93538. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93539. pickedMesh.computeWorldMatrix();
  93540. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  93541. if (!pickedMesh.rotationQuaternion) {
  93542. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  93543. }
  93544. var oldParent = pickedMesh.parent;
  93545. pickedMesh.setParent(null);
  93546. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  93547. pickedMesh.setParent(oldParent);
  93548. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  93549. // Update state
  93550. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  93551. _this.dragging = true;
  93552. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  93553. // Detatch camera controls
  93554. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  93555. if (_this._scene.activeCamera.inputs.attachedElement) {
  93556. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  93557. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  93558. }
  93559. else {
  93560. attachedElement = null;
  93561. }
  93562. }
  93563. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  93564. }
  93565. }
  93566. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  93567. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  93568. _this.dragging = false;
  93569. _this._moving = false;
  93570. _this.currentDraggingPointerID = -1;
  93571. pickedMesh = null;
  93572. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93573. // Reattach camera controls
  93574. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  93575. _this._scene.activeCamera.attachControl(attachedElement, true);
  93576. }
  93577. }
  93578. }
  93579. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  93580. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  93581. var zDragFactor = _this.zDragFactor;
  93582. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  93583. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  93584. zDragFactor = 0;
  93585. }
  93586. // Calculate controller drag distance in controller space
  93587. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  93588. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  93589. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  93590. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  93591. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  93592. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  93593. if (_this._virtualDragMesh.position.z < 0) {
  93594. _this._virtualDragMesh.position.z = 0;
  93595. }
  93596. // Update the controller position
  93597. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  93598. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  93599. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93600. // Move the virtualObjectsPosition into the picked mesh's space if needed
  93601. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  93602. if (pickedMesh.parent) {
  93603. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  93604. }
  93605. if (!_this._moving) {
  93606. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  93607. }
  93608. _this._moving = true;
  93609. }
  93610. }
  93611. });
  93612. var tmpQuaternion = new BABYLON.Quaternion();
  93613. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  93614. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  93615. if (_this.dragging && _this._moving && pickedMesh) {
  93616. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  93617. // Slowly move mesh to avoid jitter
  93618. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  93619. // Get change in rotation
  93620. tmpQuaternion.copyFrom(_this._startingOrientation);
  93621. tmpQuaternion.x = -tmpQuaternion.x;
  93622. tmpQuaternion.y = -tmpQuaternion.y;
  93623. tmpQuaternion.z = -tmpQuaternion.z;
  93624. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  93625. // Convert change in rotation to only y axis rotation
  93626. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  93627. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  93628. // Slowly move mesh to avoid jitter
  93629. var oldParent = pickedMesh.parent;
  93630. pickedMesh.setParent(null);
  93631. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  93632. pickedMesh.setParent(oldParent);
  93633. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  93634. }
  93635. });
  93636. };
  93637. /**
  93638. * Detaches the behavior from the mesh
  93639. */
  93640. SixDofDragBehavior.prototype.detach = function () {
  93641. if (this._scene) {
  93642. this._scene.onPointerObservable.remove(this._pointerObserver);
  93643. }
  93644. if (this._ownerNode) {
  93645. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  93646. }
  93647. if (this._virtualOriginMesh) {
  93648. this._virtualOriginMesh.dispose();
  93649. }
  93650. if (this._virtualDragMesh) {
  93651. this._virtualDragMesh.dispose();
  93652. }
  93653. };
  93654. return SixDofDragBehavior;
  93655. }());
  93656. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  93657. })(BABYLON || (BABYLON = {}));
  93658. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  93659. var BABYLON;
  93660. (function (BABYLON) {
  93661. /**
  93662. * @hidden
  93663. */
  93664. var FaceDirectionInfo = /** @class */ (function () {
  93665. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  93666. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  93667. if (diff === void 0) { diff = 0; }
  93668. if (ignore === void 0) { ignore = false; }
  93669. this.direction = direction;
  93670. this.rotatedDirection = rotatedDirection;
  93671. this.diff = diff;
  93672. this.ignore = ignore;
  93673. }
  93674. return FaceDirectionInfo;
  93675. }());
  93676. /**
  93677. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  93678. */
  93679. var AttachToBoxBehavior = /** @class */ (function () {
  93680. /**
  93681. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  93682. * @param ui The transform node that should be attched to the mesh
  93683. */
  93684. function AttachToBoxBehavior(ui) {
  93685. this.ui = ui;
  93686. /**
  93687. * The name of the behavior
  93688. */
  93689. this.name = "AttachToBoxBehavior";
  93690. /**
  93691. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  93692. */
  93693. this.distanceAwayFromFace = 0.15;
  93694. /**
  93695. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  93696. */
  93697. this.distanceAwayFromBottomOfFace = 0.15;
  93698. 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))];
  93699. this._tmpMatrix = new BABYLON.Matrix();
  93700. this._tmpVector = new BABYLON.Vector3();
  93701. this._zeroVector = BABYLON.Vector3.Zero();
  93702. this._lookAtTmpMatrix = new BABYLON.Matrix();
  93703. /* Does nothing */
  93704. }
  93705. /**
  93706. * Initializes the behavior
  93707. */
  93708. AttachToBoxBehavior.prototype.init = function () {
  93709. /* Does nothing */
  93710. };
  93711. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  93712. var _this = this;
  93713. // Go over each face and calculate the angle between the face's normal and targetDirection
  93714. this._faceVectors.forEach(function (v) {
  93715. if (!_this._target.rotationQuaternion) {
  93716. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  93717. }
  93718. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  93719. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  93720. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  93721. });
  93722. // Return the face information of the one with the normal closeset to target direction
  93723. return this._faceVectors.reduce(function (min, p) {
  93724. if (min.ignore) {
  93725. return p;
  93726. }
  93727. else if (p.ignore) {
  93728. return min;
  93729. }
  93730. else {
  93731. return min.diff < p.diff ? min : p;
  93732. }
  93733. }, this._faceVectors[0]);
  93734. };
  93735. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  93736. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  93737. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  93738. this._lookAtTmpMatrix.invert();
  93739. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  93740. };
  93741. /**
  93742. * Attaches the AttachToBoxBehavior to the passed in mesh
  93743. * @param target The mesh that the specified node will be attached to
  93744. */
  93745. AttachToBoxBehavior.prototype.attach = function (target) {
  93746. var _this = this;
  93747. this._target = target;
  93748. this._scene = this._target.getScene();
  93749. // Every frame, update the app bars position
  93750. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  93751. if (!_this._scene.activeCamera) {
  93752. return;
  93753. }
  93754. // Find the face closest to the cameras position
  93755. var cameraPos = _this._scene.activeCamera.position;
  93756. if (_this._scene.activeCamera.devicePosition) {
  93757. cameraPos = _this._scene.activeCamera.devicePosition;
  93758. }
  93759. var facing = _this._closestFace(cameraPos.subtract(target.position));
  93760. if (_this._scene.activeCamera.leftCamera) {
  93761. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  93762. }
  93763. else {
  93764. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  93765. }
  93766. // Get camera up direction
  93767. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  93768. // Ignore faces to not select a parrelel face for the up vector of the UI
  93769. _this._faceVectors.forEach(function (v) {
  93770. if (facing.direction.x && v.direction.x) {
  93771. v.ignore = true;
  93772. }
  93773. if (facing.direction.y && v.direction.y) {
  93774. v.ignore = true;
  93775. }
  93776. if (facing.direction.z && v.direction.z) {
  93777. v.ignore = true;
  93778. }
  93779. });
  93780. var facingUp = _this._closestFace(_this._tmpVector);
  93781. // Unignore faces
  93782. _this._faceVectors.forEach(function (v) {
  93783. v.ignore = false;
  93784. });
  93785. // Position the app bar on that face
  93786. _this.ui.position.copyFrom(target.position);
  93787. if (facing.direction.x) {
  93788. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  93789. _this.ui.position.addInPlace(_this._tmpVector);
  93790. }
  93791. if (facing.direction.y) {
  93792. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  93793. _this.ui.position.addInPlace(_this._tmpVector);
  93794. }
  93795. if (facing.direction.z) {
  93796. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  93797. _this.ui.position.addInPlace(_this._tmpVector);
  93798. }
  93799. // Rotate to be oriented properly to the camera
  93800. if (!_this.ui.rotationQuaternion) {
  93801. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  93802. }
  93803. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  93804. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  93805. // Place ui the correct distance from the bottom of the mesh
  93806. if (facingUp.direction.x) {
  93807. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  93808. }
  93809. if (facingUp.direction.y) {
  93810. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  93811. }
  93812. if (facingUp.direction.z) {
  93813. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  93814. }
  93815. _this.ui.position.addInPlace(_this._tmpVector);
  93816. });
  93817. };
  93818. /**
  93819. * Detaches the behavior from the mesh
  93820. */
  93821. AttachToBoxBehavior.prototype.detach = function () {
  93822. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  93823. };
  93824. return AttachToBoxBehavior;
  93825. }());
  93826. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  93827. })(BABYLON || (BABYLON = {}));
  93828. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  93829. var BABYLON;
  93830. (function (BABYLON) {
  93831. /**
  93832. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  93833. */
  93834. var FadeInOutBehavior = /** @class */ (function () {
  93835. /**
  93836. * Instatiates the FadeInOutBehavior
  93837. */
  93838. function FadeInOutBehavior() {
  93839. var _this = this;
  93840. /**
  93841. * Time in milliseconds to delay before fading in (Default: 0)
  93842. */
  93843. this.delay = 0;
  93844. /**
  93845. * Time in milliseconds for the mesh to fade in (Default: 300)
  93846. */
  93847. this.fadeInTime = 300;
  93848. this._millisecondsPerFrame = 1000 / 60;
  93849. this._hovered = false;
  93850. this._hoverValue = 0;
  93851. this._ownerNode = null;
  93852. this._update = function () {
  93853. if (_this._ownerNode) {
  93854. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  93855. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  93856. if (_this._ownerNode.visibility > 1) {
  93857. _this._setAllVisibility(_this._ownerNode, 1);
  93858. _this._hoverValue = _this.fadeInTime + _this.delay;
  93859. return;
  93860. }
  93861. else if (_this._ownerNode.visibility < 0) {
  93862. _this._setAllVisibility(_this._ownerNode, 0);
  93863. if (_this._hoverValue < 0) {
  93864. _this._hoverValue = 0;
  93865. return;
  93866. }
  93867. }
  93868. setTimeout(_this._update, _this._millisecondsPerFrame);
  93869. }
  93870. };
  93871. }
  93872. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  93873. /**
  93874. * The name of the behavior
  93875. */
  93876. get: function () {
  93877. return "FadeInOut";
  93878. },
  93879. enumerable: true,
  93880. configurable: true
  93881. });
  93882. /**
  93883. * Initializes the behavior
  93884. */
  93885. FadeInOutBehavior.prototype.init = function () {
  93886. };
  93887. /**
  93888. * Attaches the fade behavior on the passed in mesh
  93889. * @param ownerNode The mesh that will be faded in/out once attached
  93890. */
  93891. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  93892. this._ownerNode = ownerNode;
  93893. this._setAllVisibility(this._ownerNode, 0);
  93894. };
  93895. /**
  93896. * Detaches the behavior from the mesh
  93897. */
  93898. FadeInOutBehavior.prototype.detach = function () {
  93899. this._ownerNode = null;
  93900. };
  93901. /**
  93902. * Triggers the mesh to begin fading in or out
  93903. * @param value if the object should fade in or out (true to fade in)
  93904. */
  93905. FadeInOutBehavior.prototype.fadeIn = function (value) {
  93906. this._hovered = value;
  93907. this._update();
  93908. };
  93909. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  93910. var _this = this;
  93911. mesh.visibility = value;
  93912. mesh.getChildMeshes().forEach(function (c) {
  93913. _this._setAllVisibility(c, value);
  93914. });
  93915. };
  93916. return FadeInOutBehavior;
  93917. }());
  93918. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  93919. })(BABYLON || (BABYLON = {}));
  93920. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  93921. var BABYLON;
  93922. (function (BABYLON) {
  93923. /**
  93924. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  93925. */
  93926. var Gizmo = /** @class */ (function () {
  93927. /**
  93928. * Creates a gizmo
  93929. * @param gizmoLayer The utility layer the gizmo will be added to
  93930. */
  93931. function Gizmo(
  93932. /** The utility layer the gizmo will be added to */
  93933. gizmoLayer) {
  93934. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93935. var _this = this;
  93936. this.gizmoLayer = gizmoLayer;
  93937. /**
  93938. * Ratio for the scale of the gizmo (Default: 1)
  93939. */
  93940. this.scaleRatio = 1;
  93941. this._tmpMatrix = new BABYLON.Matrix();
  93942. /**
  93943. * If a custom mesh has been set (Default: false)
  93944. */
  93945. this._customMeshSet = false;
  93946. /**
  93947. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  93948. */
  93949. this.updateGizmoRotationToMatchAttachedMesh = true;
  93950. /**
  93951. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  93952. */
  93953. this.updateGizmoPositionToMatchAttachedMesh = true;
  93954. /**
  93955. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  93956. */
  93957. this._updateScale = true;
  93958. this._interactionsEnabled = true;
  93959. this._tempVector = new BABYLON.Vector3();
  93960. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  93961. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  93962. _this._update();
  93963. });
  93964. this.attachedMesh = null;
  93965. }
  93966. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  93967. /**
  93968. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  93969. * * When set, interactions will be enabled
  93970. */
  93971. get: function () {
  93972. return this._attachedMesh;
  93973. },
  93974. set: function (value) {
  93975. this._attachedMesh = value;
  93976. this._rootMesh.setEnabled(value ? true : false);
  93977. this._attachedMeshChanged(value);
  93978. },
  93979. enumerable: true,
  93980. configurable: true
  93981. });
  93982. /**
  93983. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  93984. * @param mesh The mesh to replace the default mesh of the gizmo
  93985. */
  93986. Gizmo.prototype.setCustomMesh = function (mesh) {
  93987. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  93988. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  93989. }
  93990. this._rootMesh.getChildMeshes().forEach(function (c) {
  93991. c.dispose();
  93992. });
  93993. mesh.parent = this._rootMesh;
  93994. this._customMeshSet = true;
  93995. };
  93996. Gizmo.prototype._attachedMeshChanged = function (value) {
  93997. };
  93998. /**
  93999. * @hidden
  94000. * Updates the gizmo to match the attached mesh's position/rotation
  94001. */
  94002. Gizmo.prototype._update = function () {
  94003. if (this.attachedMesh) {
  94004. if (this.updateGizmoRotationToMatchAttachedMesh) {
  94005. if (!this._rootMesh.rotationQuaternion) {
  94006. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  94007. }
  94008. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  94009. this._tempVector.copyFrom(this.attachedMesh.scaling);
  94010. if (this.attachedMesh.scaling.x < 0) {
  94011. this.attachedMesh.scaling.x *= -1;
  94012. }
  94013. if (this.attachedMesh.scaling.y < 0) {
  94014. this.attachedMesh.scaling.y *= -1;
  94015. }
  94016. if (this.attachedMesh.scaling.z < 0) {
  94017. this.attachedMesh.scaling.z *= -1;
  94018. }
  94019. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  94020. this.attachedMesh.scaling.copyFrom(this._tempVector);
  94021. this.attachedMesh.computeWorldMatrix();
  94022. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  94023. }
  94024. else if (this._rootMesh.rotationQuaternion) {
  94025. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  94026. }
  94027. if (this.updateGizmoPositionToMatchAttachedMesh) {
  94028. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  94029. }
  94030. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  94031. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  94032. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  94033. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  94034. }
  94035. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  94036. var dist = this._tempVector.length() * this.scaleRatio;
  94037. this._rootMesh.scaling.set(dist, dist, dist);
  94038. }
  94039. }
  94040. };
  94041. /**
  94042. * Disposes of the gizmo
  94043. */
  94044. Gizmo.prototype.dispose = function () {
  94045. this._rootMesh.dispose();
  94046. if (this._beforeRenderObserver) {
  94047. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  94048. }
  94049. };
  94050. return Gizmo;
  94051. }());
  94052. BABYLON.Gizmo = Gizmo;
  94053. })(BABYLON || (BABYLON = {}));
  94054. //# sourceMappingURL=babylon.gizmo.js.map
  94055. var BABYLON;
  94056. (function (BABYLON) {
  94057. /**
  94058. * Single axis drag gizmo
  94059. */
  94060. var AxisDragGizmo = /** @class */ (function (_super) {
  94061. __extends(AxisDragGizmo, _super);
  94062. /**
  94063. * Creates an AxisDragGizmo
  94064. * @param gizmoLayer The utility layer the gizmo will be added to
  94065. * @param dragAxis The axis which the gizmo will be able to drag on
  94066. * @param color The color of the gizmo
  94067. */
  94068. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  94069. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  94070. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94071. var _this = _super.call(this, gizmoLayer) || this;
  94072. _this._pointerObserver = null;
  94073. /**
  94074. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94075. */
  94076. _this.snapDistance = 0;
  94077. /**
  94078. * Event that fires each time the gizmo snaps to a new location.
  94079. * * snapDistance is the the change in distance
  94080. */
  94081. _this.onSnapObservable = new BABYLON.Observable();
  94082. // Create Material
  94083. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94084. coloredMaterial.disableLighting = true;
  94085. coloredMaterial.emissiveColor = color;
  94086. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94087. hoverMaterial.disableLighting = true;
  94088. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  94089. // Build mesh on root node
  94090. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94091. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  94092. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  94093. arrowTail.color = coloredMaterial.emissiveColor;
  94094. arrow.addChild(arrowMesh);
  94095. arrow.addChild(arrowTail);
  94096. // Position arrow pointing in its drag axis
  94097. arrowMesh.scaling.scaleInPlace(0.05);
  94098. arrowMesh.material = coloredMaterial;
  94099. arrowMesh.rotation.x = Math.PI / 2;
  94100. arrowMesh.position.z += 0.3;
  94101. arrowTail.scaling.scaleInPlace(0.26);
  94102. arrowTail.rotation.x = Math.PI / 2;
  94103. arrowTail.material = coloredMaterial;
  94104. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  94105. arrow.scaling.scaleInPlace(1 / 3);
  94106. _this._rootMesh.addChild(arrow);
  94107. var currentSnapDragDistance = 0;
  94108. var tmpVector = new BABYLON.Vector3();
  94109. var tmpSnapEvent = { snapDistance: 0 };
  94110. // Add drag behavior to handle events when the gizmo is dragged
  94111. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  94112. _this.dragBehavior.moveAttached = false;
  94113. _this._rootMesh.addBehavior(_this.dragBehavior);
  94114. var localDelta = new BABYLON.Vector3();
  94115. var tmpMatrix = new BABYLON.Matrix();
  94116. _this.dragBehavior.onDragObservable.add(function (event) {
  94117. if (_this.attachedMesh) {
  94118. // Convert delta to local translation if it has a parent
  94119. if (_this.attachedMesh.parent) {
  94120. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  94121. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  94122. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  94123. }
  94124. else {
  94125. localDelta.copyFrom(event.delta);
  94126. }
  94127. // Snapping logic
  94128. if (_this.snapDistance == 0) {
  94129. _this.attachedMesh.position.addInPlace(localDelta);
  94130. }
  94131. else {
  94132. currentSnapDragDistance += event.dragDistance;
  94133. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  94134. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  94135. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  94136. localDelta.normalizeToRef(tmpVector);
  94137. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  94138. _this.attachedMesh.position.addInPlace(tmpVector);
  94139. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  94140. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  94141. }
  94142. }
  94143. }
  94144. });
  94145. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  94146. if (_this._customMeshSet) {
  94147. return;
  94148. }
  94149. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  94150. var material = isHovered ? hoverMaterial : coloredMaterial;
  94151. _this._rootMesh.getChildMeshes().forEach(function (m) {
  94152. m.material = material;
  94153. if (m.color) {
  94154. m.color = material.emissiveColor;
  94155. }
  94156. });
  94157. });
  94158. return _this;
  94159. }
  94160. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  94161. if (this.dragBehavior) {
  94162. this.dragBehavior.enabled = value ? true : false;
  94163. }
  94164. };
  94165. /**
  94166. * Disposes of the gizmo
  94167. */
  94168. AxisDragGizmo.prototype.dispose = function () {
  94169. this.onSnapObservable.clear();
  94170. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  94171. this.dragBehavior.detach();
  94172. _super.prototype.dispose.call(this);
  94173. };
  94174. return AxisDragGizmo;
  94175. }(BABYLON.Gizmo));
  94176. BABYLON.AxisDragGizmo = AxisDragGizmo;
  94177. })(BABYLON || (BABYLON = {}));
  94178. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  94179. var BABYLON;
  94180. (function (BABYLON) {
  94181. /**
  94182. * Single axis scale gizmo
  94183. */
  94184. var AxisScaleGizmo = /** @class */ (function (_super) {
  94185. __extends(AxisScaleGizmo, _super);
  94186. /**
  94187. * Creates an AxisScaleGizmo
  94188. * @param gizmoLayer The utility layer the gizmo will be added to
  94189. * @param dragAxis The axis which the gizmo will be able to scale on
  94190. * @param color The color of the gizmo
  94191. */
  94192. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  94193. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  94194. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94195. var _this = _super.call(this, gizmoLayer) || this;
  94196. _this._pointerObserver = null;
  94197. /**
  94198. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94199. */
  94200. _this.snapDistance = 0;
  94201. /**
  94202. * Event that fires each time the gizmo snaps to a new location.
  94203. * * snapDistance is the the change in distance
  94204. */
  94205. _this.onSnapObservable = new BABYLON.Observable();
  94206. /**
  94207. * If the scaling operation should be done on all axis (default: false)
  94208. */
  94209. _this.uniformScaling = false;
  94210. // Create Material
  94211. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94212. _this._coloredMaterial.disableLighting = true;
  94213. _this._coloredMaterial.emissiveColor = color;
  94214. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94215. hoverMaterial.disableLighting = true;
  94216. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  94217. // Build mesh on root node
  94218. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94219. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  94220. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  94221. arrowTail.color = _this._coloredMaterial.emissiveColor;
  94222. arrow.addChild(arrowMesh);
  94223. arrow.addChild(arrowTail);
  94224. // Position arrow pointing in its drag axis
  94225. arrowMesh.scaling.scaleInPlace(0.1);
  94226. arrowMesh.material = _this._coloredMaterial;
  94227. arrowMesh.rotation.x = Math.PI / 2;
  94228. arrowMesh.position.z += 0.3;
  94229. arrowTail.scaling.scaleInPlace(0.26);
  94230. arrowTail.rotation.x = Math.PI / 2;
  94231. arrowTail.material = _this._coloredMaterial;
  94232. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  94233. _this._rootMesh.addChild(arrow);
  94234. arrow.scaling.scaleInPlace(1 / 3);
  94235. // Add drag behavior to handle events when the gizmo is dragged
  94236. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  94237. _this.dragBehavior.moveAttached = false;
  94238. _this._rootMesh.addBehavior(_this.dragBehavior);
  94239. var currentSnapDragDistance = 0;
  94240. var tmpVector = new BABYLON.Vector3();
  94241. var tmpSnapEvent = { snapDistance: 0 };
  94242. _this.dragBehavior.onDragObservable.add(function (event) {
  94243. if (_this.attachedMesh) {
  94244. // Snapping logic
  94245. var snapped = false;
  94246. var dragSteps = 0;
  94247. if (_this.uniformScaling) {
  94248. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  94249. if (tmpVector.y < 0) {
  94250. tmpVector.scaleInPlace(-1);
  94251. }
  94252. }
  94253. else {
  94254. tmpVector.copyFrom(dragAxis);
  94255. }
  94256. if (_this.snapDistance == 0) {
  94257. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  94258. }
  94259. else {
  94260. currentSnapDragDistance += event.dragDistance;
  94261. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  94262. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  94263. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  94264. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  94265. snapped = true;
  94266. }
  94267. else {
  94268. tmpVector.scaleInPlace(0);
  94269. }
  94270. }
  94271. _this.attachedMesh.scaling.addInPlace(tmpVector);
  94272. if (snapped) {
  94273. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  94274. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  94275. }
  94276. }
  94277. });
  94278. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  94279. if (_this._customMeshSet) {
  94280. return;
  94281. }
  94282. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  94283. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  94284. _this._rootMesh.getChildMeshes().forEach(function (m) {
  94285. m.material = material;
  94286. if (m.color) {
  94287. m.color = material.emissiveColor;
  94288. }
  94289. });
  94290. });
  94291. return _this;
  94292. }
  94293. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  94294. if (this.dragBehavior) {
  94295. this.dragBehavior.enabled = value ? true : false;
  94296. }
  94297. };
  94298. /**
  94299. * Disposes of the gizmo
  94300. */
  94301. AxisScaleGizmo.prototype.dispose = function () {
  94302. this.onSnapObservable.clear();
  94303. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  94304. this.dragBehavior.detach();
  94305. _super.prototype.dispose.call(this);
  94306. };
  94307. /**
  94308. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  94309. * @param mesh The mesh to replace the default mesh of the gizmo
  94310. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  94311. */
  94312. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  94313. var _this = this;
  94314. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  94315. _super.prototype.setCustomMesh.call(this, mesh);
  94316. if (useGizmoMaterial) {
  94317. this._rootMesh.getChildMeshes().forEach(function (m) {
  94318. m.material = _this._coloredMaterial;
  94319. if (m.color) {
  94320. m.color = _this._coloredMaterial.emissiveColor;
  94321. }
  94322. });
  94323. this._customMeshSet = false;
  94324. }
  94325. };
  94326. return AxisScaleGizmo;
  94327. }(BABYLON.Gizmo));
  94328. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  94329. })(BABYLON || (BABYLON = {}));
  94330. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  94331. var BABYLON;
  94332. (function (BABYLON) {
  94333. /**
  94334. * Single plane rotation gizmo
  94335. */
  94336. var PlaneRotationGizmo = /** @class */ (function (_super) {
  94337. __extends(PlaneRotationGizmo, _super);
  94338. /**
  94339. * Creates a PlaneRotationGizmo
  94340. * @param gizmoLayer The utility layer the gizmo will be added to
  94341. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  94342. * @param color The color of the gizmo
  94343. */
  94344. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  94345. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  94346. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94347. var _this = _super.call(this, gizmoLayer) || this;
  94348. _this._pointerObserver = null;
  94349. /**
  94350. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  94351. */
  94352. _this.snapDistance = 0;
  94353. /**
  94354. * Event that fires each time the gizmo snaps to a new location.
  94355. * * snapDistance is the the change in distance
  94356. */
  94357. _this.onSnapObservable = new BABYLON.Observable();
  94358. // Create Material
  94359. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94360. coloredMaterial.disableLighting = true;
  94361. coloredMaterial.emissiveColor = color;
  94362. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94363. hoverMaterial.disableLighting = true;
  94364. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  94365. // Build mesh on root node
  94366. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94367. // Create circle out of lines
  94368. var tessellation = 20;
  94369. var radius = 0.8;
  94370. var points = new Array();
  94371. for (var i = 0; i < tessellation; i++) {
  94372. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  94373. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  94374. }
  94375. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  94376. rotationMesh.color = coloredMaterial.emissiveColor;
  94377. // Position arrow pointing in its drag axis
  94378. rotationMesh.scaling.scaleInPlace(0.26);
  94379. rotationMesh.material = coloredMaterial;
  94380. rotationMesh.rotation.x = Math.PI / 2;
  94381. parentMesh.addChild(rotationMesh);
  94382. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  94383. _this._rootMesh.addChild(parentMesh);
  94384. parentMesh.scaling.scaleInPlace(1 / 3);
  94385. // Add drag behavior to handle events when the gizmo is dragged
  94386. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  94387. _this.dragBehavior.moveAttached = false;
  94388. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  94389. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  94390. _this._rootMesh.addBehavior(_this.dragBehavior);
  94391. var lastDragPosition = new BABYLON.Vector3();
  94392. _this.dragBehavior.onDragStartObservable.add(function (e) {
  94393. if (_this.attachedMesh) {
  94394. lastDragPosition.copyFrom(e.dragPlanePoint);
  94395. }
  94396. });
  94397. var rotationMatrix = new BABYLON.Matrix();
  94398. var planeNormalTowardsCamera = new BABYLON.Vector3();
  94399. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  94400. var tmpSnapEvent = { snapDistance: 0 };
  94401. var currentSnapDragDistance = 0;
  94402. var tmpMatrix = new BABYLON.Matrix();
  94403. var tmpVector = new BABYLON.Vector3();
  94404. var amountToRotate = new BABYLON.Quaternion();
  94405. _this.dragBehavior.onDragObservable.add(function (event) {
  94406. if (_this.attachedMesh) {
  94407. if (!_this.attachedMesh.rotationQuaternion) {
  94408. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  94409. }
  94410. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  94411. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  94412. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  94413. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  94414. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  94415. var angle = Math.atan2(cross.length(), dot);
  94416. planeNormalTowardsCamera.copyFrom(planeNormal);
  94417. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  94418. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  94419. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  94420. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  94421. }
  94422. // Flip up vector depending on which side the camera is on
  94423. if (gizmoLayer.utilityLayerScene.activeCamera) {
  94424. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  94425. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  94426. planeNormalTowardsCamera.scaleInPlace(-1);
  94427. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  94428. }
  94429. }
  94430. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  94431. if (halfCircleSide)
  94432. angle = -angle;
  94433. // Snapping logic
  94434. var snapped = false;
  94435. if (_this.snapDistance != 0) {
  94436. currentSnapDragDistance += angle;
  94437. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  94438. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  94439. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  94440. angle = _this.snapDistance * dragSteps;
  94441. snapped = true;
  94442. }
  94443. else {
  94444. angle = 0;
  94445. }
  94446. }
  94447. // If the mesh has a parent, convert needed world rotation to local rotation
  94448. tmpMatrix.reset();
  94449. if (_this.attachedMesh.parent) {
  94450. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  94451. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  94452. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  94453. }
  94454. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  94455. var quaternionCoefficient = Math.sin(angle / 2);
  94456. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  94457. // 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
  94458. if (tmpMatrix.determinant() > 0) {
  94459. amountToRotate.toEulerAnglesToRef(tmpVector);
  94460. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  94461. }
  94462. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  94463. // Rotate selected mesh quaternion over fixed axis
  94464. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  94465. }
  94466. else {
  94467. // Rotate selected mesh quaternion over rotated axis
  94468. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  94469. }
  94470. lastDragPosition.copyFrom(event.dragPlanePoint);
  94471. if (snapped) {
  94472. tmpSnapEvent.snapDistance = angle;
  94473. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  94474. }
  94475. }
  94476. });
  94477. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  94478. if (_this._customMeshSet) {
  94479. return;
  94480. }
  94481. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  94482. var material = isHovered ? hoverMaterial : coloredMaterial;
  94483. _this._rootMesh.getChildMeshes().forEach(function (m) {
  94484. m.material = material;
  94485. if (m.color) {
  94486. m.color = material.emissiveColor;
  94487. }
  94488. });
  94489. });
  94490. return _this;
  94491. }
  94492. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  94493. if (this.dragBehavior) {
  94494. this.dragBehavior.enabled = value ? true : false;
  94495. }
  94496. };
  94497. /**
  94498. * Disposes of the gizmo
  94499. */
  94500. PlaneRotationGizmo.prototype.dispose = function () {
  94501. this.onSnapObservable.clear();
  94502. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  94503. this.dragBehavior.detach();
  94504. _super.prototype.dispose.call(this);
  94505. };
  94506. return PlaneRotationGizmo;
  94507. }(BABYLON.Gizmo));
  94508. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  94509. })(BABYLON || (BABYLON = {}));
  94510. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  94511. var BABYLON;
  94512. (function (BABYLON) {
  94513. /**
  94514. * Gizmo that enables dragging a mesh along 3 axis
  94515. */
  94516. var PositionGizmo = /** @class */ (function (_super) {
  94517. __extends(PositionGizmo, _super);
  94518. /**
  94519. * Creates a PositionGizmo
  94520. * @param gizmoLayer The utility layer the gizmo will be added to
  94521. */
  94522. function PositionGizmo(gizmoLayer) {
  94523. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94524. var _this = _super.call(this, gizmoLayer) || this;
  94525. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  94526. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  94527. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  94528. _this.attachedMesh = null;
  94529. return _this;
  94530. }
  94531. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  94532. set: function (mesh) {
  94533. if (this.xGizmo) {
  94534. this.xGizmo.attachedMesh = mesh;
  94535. this.yGizmo.attachedMesh = mesh;
  94536. this.zGizmo.attachedMesh = mesh;
  94537. }
  94538. },
  94539. enumerable: true,
  94540. configurable: true
  94541. });
  94542. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94543. get: function () {
  94544. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94545. },
  94546. set: function (value) {
  94547. if (this.xGizmo) {
  94548. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94549. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94550. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94551. }
  94552. },
  94553. enumerable: true,
  94554. configurable: true
  94555. });
  94556. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  94557. get: function () {
  94558. return this.xGizmo.snapDistance;
  94559. },
  94560. /**
  94561. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94562. */
  94563. set: function (value) {
  94564. if (this.xGizmo) {
  94565. this.xGizmo.snapDistance = value;
  94566. this.yGizmo.snapDistance = value;
  94567. this.zGizmo.snapDistance = value;
  94568. }
  94569. },
  94570. enumerable: true,
  94571. configurable: true
  94572. });
  94573. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  94574. get: function () {
  94575. return this.xGizmo.scaleRatio;
  94576. },
  94577. /**
  94578. * Ratio for the scale of the gizmo (Default: 1)
  94579. */
  94580. set: function (value) {
  94581. if (this.xGizmo) {
  94582. this.xGizmo.scaleRatio = value;
  94583. this.yGizmo.scaleRatio = value;
  94584. this.zGizmo.scaleRatio = value;
  94585. }
  94586. },
  94587. enumerable: true,
  94588. configurable: true
  94589. });
  94590. /**
  94591. * Disposes of the gizmo
  94592. */
  94593. PositionGizmo.prototype.dispose = function () {
  94594. this.xGizmo.dispose();
  94595. this.yGizmo.dispose();
  94596. this.zGizmo.dispose();
  94597. };
  94598. /**
  94599. * CustomMeshes are not supported by this gizmo
  94600. * @param mesh The mesh to replace the default mesh of the gizmo
  94601. */
  94602. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  94603. 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)");
  94604. };
  94605. return PositionGizmo;
  94606. }(BABYLON.Gizmo));
  94607. BABYLON.PositionGizmo = PositionGizmo;
  94608. })(BABYLON || (BABYLON = {}));
  94609. //# sourceMappingURL=babylon.positionGizmo.js.map
  94610. var BABYLON;
  94611. (function (BABYLON) {
  94612. /**
  94613. * Gizmo that enables rotating a mesh along 3 axis
  94614. */
  94615. var RotationGizmo = /** @class */ (function (_super) {
  94616. __extends(RotationGizmo, _super);
  94617. /**
  94618. * Creates a RotationGizmo
  94619. * @param gizmoLayer The utility layer the gizmo will be added to
  94620. */
  94621. function RotationGizmo(gizmoLayer) {
  94622. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94623. var _this = _super.call(this, gizmoLayer) || this;
  94624. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  94625. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  94626. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  94627. _this.attachedMesh = null;
  94628. return _this;
  94629. }
  94630. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  94631. set: function (mesh) {
  94632. if (this.xGizmo) {
  94633. this.xGizmo.attachedMesh = mesh;
  94634. this.yGizmo.attachedMesh = mesh;
  94635. this.zGizmo.attachedMesh = mesh;
  94636. }
  94637. },
  94638. enumerable: true,
  94639. configurable: true
  94640. });
  94641. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94642. get: function () {
  94643. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94644. },
  94645. set: function (value) {
  94646. if (this.xGizmo) {
  94647. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94648. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94649. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94650. }
  94651. },
  94652. enumerable: true,
  94653. configurable: true
  94654. });
  94655. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  94656. get: function () {
  94657. return this.xGizmo.snapDistance;
  94658. },
  94659. /**
  94660. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94661. */
  94662. set: function (value) {
  94663. if (this.xGizmo) {
  94664. this.xGizmo.snapDistance = value;
  94665. this.yGizmo.snapDistance = value;
  94666. this.zGizmo.snapDistance = value;
  94667. }
  94668. },
  94669. enumerable: true,
  94670. configurable: true
  94671. });
  94672. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  94673. get: function () {
  94674. return this.xGizmo.scaleRatio;
  94675. },
  94676. /**
  94677. * Ratio for the scale of the gizmo (Default: 1)
  94678. */
  94679. set: function (value) {
  94680. if (this.xGizmo) {
  94681. this.xGizmo.scaleRatio = value;
  94682. this.yGizmo.scaleRatio = value;
  94683. this.zGizmo.scaleRatio = value;
  94684. }
  94685. },
  94686. enumerable: true,
  94687. configurable: true
  94688. });
  94689. /**
  94690. * Disposes of the gizmo
  94691. */
  94692. RotationGizmo.prototype.dispose = function () {
  94693. this.xGizmo.dispose();
  94694. this.yGizmo.dispose();
  94695. this.zGizmo.dispose();
  94696. };
  94697. /**
  94698. * CustomMeshes are not supported by this gizmo
  94699. * @param mesh The mesh to replace the default mesh of the gizmo
  94700. */
  94701. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  94702. 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)");
  94703. };
  94704. return RotationGizmo;
  94705. }(BABYLON.Gizmo));
  94706. BABYLON.RotationGizmo = RotationGizmo;
  94707. })(BABYLON || (BABYLON = {}));
  94708. //# sourceMappingURL=babylon.rotationGizmo.js.map
  94709. var BABYLON;
  94710. (function (BABYLON) {
  94711. /**
  94712. * Gizmo that enables scaling a mesh along 3 axis
  94713. */
  94714. var ScaleGizmo = /** @class */ (function (_super) {
  94715. __extends(ScaleGizmo, _super);
  94716. /**
  94717. * Creates a ScaleGizmo
  94718. * @param gizmoLayer The utility layer the gizmo will be added to
  94719. */
  94720. function ScaleGizmo(gizmoLayer) {
  94721. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94722. var _this = _super.call(this, gizmoLayer) || this;
  94723. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  94724. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  94725. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  94726. // Create uniform scale gizmo
  94727. _this._uniformGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  94728. _this._uniformGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  94729. _this._uniformGizmo.uniformScaling = true;
  94730. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this._uniformGizmo.gizmoLayer.utilityLayerScene);
  94731. octahedron.scaling.scaleInPlace(0.007);
  94732. _this._uniformGizmo.setCustomMesh(octahedron, true);
  94733. _this.attachedMesh = null;
  94734. return _this;
  94735. }
  94736. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  94737. set: function (mesh) {
  94738. if (this.xGizmo) {
  94739. this.xGizmo.attachedMesh = mesh;
  94740. this.yGizmo.attachedMesh = mesh;
  94741. this.zGizmo.attachedMesh = mesh;
  94742. this._uniformGizmo.attachedMesh = mesh;
  94743. }
  94744. },
  94745. enumerable: true,
  94746. configurable: true
  94747. });
  94748. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94749. get: function () {
  94750. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94751. },
  94752. set: function (value) {
  94753. if (this.xGizmo) {
  94754. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94755. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94756. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94757. }
  94758. },
  94759. enumerable: true,
  94760. configurable: true
  94761. });
  94762. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  94763. get: function () {
  94764. return this.xGizmo.snapDistance;
  94765. },
  94766. /**
  94767. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94768. */
  94769. set: function (value) {
  94770. if (this.xGizmo) {
  94771. this.xGizmo.snapDistance = value;
  94772. this.yGizmo.snapDistance = value;
  94773. this.zGizmo.snapDistance = value;
  94774. this._uniformGizmo.snapDistance = value;
  94775. }
  94776. },
  94777. enumerable: true,
  94778. configurable: true
  94779. });
  94780. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  94781. get: function () {
  94782. return this.xGizmo.scaleRatio;
  94783. },
  94784. /**
  94785. * Ratio for the scale of the gizmo (Default: 1)
  94786. */
  94787. set: function (value) {
  94788. if (this.xGizmo) {
  94789. this.xGizmo.scaleRatio = value;
  94790. this.yGizmo.scaleRatio = value;
  94791. this.zGizmo.scaleRatio = value;
  94792. this._uniformGizmo.scaleRatio = value;
  94793. }
  94794. },
  94795. enumerable: true,
  94796. configurable: true
  94797. });
  94798. /**
  94799. * Disposes of the gizmo
  94800. */
  94801. ScaleGizmo.prototype.dispose = function () {
  94802. this.xGizmo.dispose();
  94803. this.yGizmo.dispose();
  94804. this.zGizmo.dispose();
  94805. this._uniformGizmo.dispose();
  94806. };
  94807. return ScaleGizmo;
  94808. }(BABYLON.Gizmo));
  94809. BABYLON.ScaleGizmo = ScaleGizmo;
  94810. })(BABYLON || (BABYLON = {}));
  94811. //# sourceMappingURL=babylon.scaleGizmo.js.map
  94812. var BABYLON;
  94813. (function (BABYLON) {
  94814. /**
  94815. * Bounding box gizmo
  94816. */
  94817. var BoundingBoxGizmo = /** @class */ (function (_super) {
  94818. __extends(BoundingBoxGizmo, _super);
  94819. /**
  94820. * Creates an BoundingBoxGizmo
  94821. * @param gizmoLayer The utility layer the gizmo will be added to
  94822. * @param color The color of the gizmo
  94823. */
  94824. function BoundingBoxGizmo(color, gizmoLayer) {
  94825. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  94826. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  94827. var _this = _super.call(this, gizmoLayer) || this;
  94828. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  94829. _this._renderObserver = null;
  94830. _this._pointerObserver = null;
  94831. _this._scaleDragSpeed = 0.2;
  94832. _this._tmpQuaternion = new BABYLON.Quaternion();
  94833. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  94834. _this._tmpRotationMatrix = new BABYLON.Matrix();
  94835. /**
  94836. * 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)
  94837. */
  94838. _this.ignoreChildren = false;
  94839. /**
  94840. * 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)
  94841. */
  94842. _this.includeChildPredicate = null;
  94843. /**
  94844. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  94845. */
  94846. _this.rotationSphereSize = 0.1;
  94847. /**
  94848. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  94849. */
  94850. _this.scaleBoxSize = 0.1;
  94851. /**
  94852. * 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)
  94853. */
  94854. _this.fixedDragMeshScreenSize = false;
  94855. /**
  94856. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  94857. */
  94858. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  94859. /**
  94860. * Fired when a rotation sphere or scale box is dragged
  94861. */
  94862. _this.onDragStartObservable = new BABYLON.Observable();
  94863. /**
  94864. * Fired when a scale box is dragged
  94865. */
  94866. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  94867. /**
  94868. * Fired when a scale box drag is ended
  94869. */
  94870. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  94871. /**
  94872. * Fired when a rotation sphere is dragged
  94873. */
  94874. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  94875. /**
  94876. * Fired when a rotation sphere drag is ended
  94877. */
  94878. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  94879. /**
  94880. * 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)
  94881. */
  94882. _this.scalePivot = null;
  94883. _this._existingMeshScale = new BABYLON.Vector3();
  94884. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  94885. _this._updateScale = false;
  94886. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  94887. // Create Materials
  94888. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94889. coloredMaterial.disableLighting = true;
  94890. coloredMaterial.emissiveColor = color;
  94891. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94892. hoverColoredMaterial.disableLighting = true;
  94893. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  94894. // Build bounding box out of lines
  94895. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94896. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  94897. var lines = [];
  94898. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  94899. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  94900. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94901. 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));
  94902. 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));
  94903. 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));
  94904. 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));
  94905. 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));
  94906. 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));
  94907. 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));
  94908. 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));
  94909. 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));
  94910. lines.forEach(function (l) {
  94911. l.color = color;
  94912. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  94913. l.isPickable = false;
  94914. _this._lineBoundingBox.addChild(l);
  94915. });
  94916. _this._rootMesh.addChild(_this._lineBoundingBox);
  94917. // Create rotation spheres
  94918. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94919. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  94920. var _loop_1 = function (i_1) {
  94921. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  94922. sphere.rotationQuaternion = new BABYLON.Quaternion();
  94923. sphere.material = coloredMaterial;
  94924. // Drag behavior
  94925. _dragBehavior = new BABYLON.PointerDragBehavior({});
  94926. _dragBehavior.moveAttached = false;
  94927. _dragBehavior.updateDragPlane = false;
  94928. sphere.addBehavior(_dragBehavior);
  94929. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  94930. var totalTurnAmountOfDrag = 0;
  94931. _dragBehavior.onDragStartObservable.add(function (event) {
  94932. startingTurnDirection.copyFrom(sphere.forward);
  94933. totalTurnAmountOfDrag = 0;
  94934. });
  94935. _dragBehavior.onDragObservable.add(function (event) {
  94936. _this.onRotationSphereDragObservable.notifyObservers({});
  94937. if (_this.attachedMesh) {
  94938. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  94939. var worldDragDirection = startingTurnDirection;
  94940. // Project the world right on to the drag plane
  94941. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  94942. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  94943. // project drag delta on to the resulting drag axis and rotate based on that
  94944. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  94945. // Make rotation relative to size of mesh.
  94946. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  94947. // Rotate based on axis
  94948. if (!_this.attachedMesh.rotationQuaternion) {
  94949. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  94950. }
  94951. if (!_this._anchorMesh.rotationQuaternion) {
  94952. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  94953. }
  94954. // Do not allow the object to turn more than a full circle
  94955. totalTurnAmountOfDrag += projectDist;
  94956. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  94957. if (i_1 >= 8) {
  94958. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  94959. }
  94960. else if (i_1 >= 4) {
  94961. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  94962. }
  94963. else {
  94964. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  94965. }
  94966. // Rotate around center of bounding box
  94967. _this._anchorMesh.addChild(_this.attachedMesh);
  94968. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  94969. _this._anchorMesh.removeChild(_this.attachedMesh);
  94970. }
  94971. _this.updateBoundingBox();
  94972. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  94973. }
  94974. });
  94975. // Selection/deselection
  94976. _dragBehavior.onDragStartObservable.add(function () {
  94977. _this.onDragStartObservable.notifyObservers({});
  94978. _this._selectNode(sphere);
  94979. });
  94980. _dragBehavior.onDragEndObservable.add(function () {
  94981. _this.onRotationSphereDragEndObservable.notifyObservers({});
  94982. _this._selectNode(null);
  94983. });
  94984. this_1._rotateSpheresParent.addChild(sphere);
  94985. };
  94986. var this_1 = this, _dragBehavior;
  94987. for (var i_1 = 0; i_1 < 12; i_1++) {
  94988. _loop_1(i_1);
  94989. }
  94990. _this._rootMesh.addChild(_this._rotateSpheresParent);
  94991. // Create scale cubes
  94992. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94993. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  94994. for (var i = 0; i < 2; i++) {
  94995. for (var j = 0; j < 2; j++) {
  94996. var _loop_2 = function () {
  94997. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  94998. box.material = coloredMaterial;
  94999. // Dragging logic
  95000. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  95001. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  95002. _dragBehavior.moveAttached = false;
  95003. box.addBehavior(_dragBehavior);
  95004. _dragBehavior.onDragObservable.add(function (event) {
  95005. _this.onScaleBoxDragObservable.notifyObservers({});
  95006. if (_this.attachedMesh) {
  95007. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  95008. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  95009. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  95010. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  95011. _this.updateBoundingBox();
  95012. if (_this.scalePivot) {
  95013. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  95014. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  95015. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  95016. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  95017. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  95018. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  95019. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  95020. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  95021. }
  95022. else {
  95023. // Scale from the position of the opposite corner
  95024. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  95025. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  95026. }
  95027. _this._anchorMesh.addChild(_this.attachedMesh);
  95028. _this._anchorMesh.scaling.addInPlace(deltaScale);
  95029. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  95030. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  95031. }
  95032. _this._anchorMesh.removeChild(_this.attachedMesh);
  95033. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  95034. }
  95035. });
  95036. // Selection/deselection
  95037. _dragBehavior.onDragStartObservable.add(function () {
  95038. _this.onDragStartObservable.notifyObservers({});
  95039. _this._selectNode(box);
  95040. });
  95041. _dragBehavior.onDragEndObservable.add(function () {
  95042. _this.onScaleBoxDragEndObservable.notifyObservers({});
  95043. _this._selectNode(null);
  95044. });
  95045. this_2._scaleBoxesParent.addChild(box);
  95046. };
  95047. var this_2 = this, _dragBehavior;
  95048. for (var k = 0; k < 2; k++) {
  95049. _loop_2();
  95050. }
  95051. }
  95052. }
  95053. _this._rootMesh.addChild(_this._scaleBoxesParent);
  95054. // Hover color change
  95055. var pointerIds = new Array();
  95056. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  95057. if (!pointerIds[pointerInfo.event.pointerId]) {
  95058. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  95059. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  95060. pointerIds[pointerInfo.event.pointerId] = mesh;
  95061. mesh.material = hoverColoredMaterial;
  95062. }
  95063. });
  95064. }
  95065. else {
  95066. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  95067. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  95068. delete pointerIds[pointerInfo.event.pointerId];
  95069. }
  95070. }
  95071. });
  95072. // Update bounding box positions
  95073. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  95074. // Only update the bouding box if scaling has changed
  95075. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  95076. _this.updateBoundingBox();
  95077. }
  95078. });
  95079. _this.updateBoundingBox();
  95080. return _this;
  95081. }
  95082. /** @hidden */
  95083. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  95084. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  95085. // Save old pivot and set pivot to 0,0,0
  95086. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  95087. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  95088. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  95089. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  95090. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  95091. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  95092. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  95093. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  95094. }
  95095. }
  95096. BoundingBoxGizmo._PivotCached++;
  95097. };
  95098. /** @hidden */
  95099. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  95100. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  95101. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  95102. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  95103. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  95104. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  95105. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  95106. }
  95107. this._PivotCached--;
  95108. };
  95109. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  95110. if (value) {
  95111. // Reset anchor mesh to match attached mesh's scale
  95112. // This is needed to avoid invalid box/sphere position on first drag
  95113. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  95114. this._anchorMesh.addChild(value);
  95115. this._anchorMesh.removeChild(value);
  95116. BoundingBoxGizmo._RestorePivotPoint(value);
  95117. this.updateBoundingBox();
  95118. }
  95119. };
  95120. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  95121. this._rotateSpheresParent.getChildMeshes()
  95122. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  95123. m.isVisible = (!selectedMesh || m == selectedMesh);
  95124. });
  95125. };
  95126. /**
  95127. * Updates the bounding box information for the Gizmo
  95128. */
  95129. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  95130. if (this.attachedMesh) {
  95131. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  95132. this._update();
  95133. // Rotate based on axis
  95134. if (!this.attachedMesh.rotationQuaternion) {
  95135. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  95136. }
  95137. if (!this._anchorMesh.rotationQuaternion) {
  95138. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  95139. }
  95140. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  95141. // Store original position and reset mesh to origin before computing the bounding box
  95142. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  95143. this._tmpVector.copyFrom(this.attachedMesh.position);
  95144. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  95145. this.attachedMesh.position.set(0, 0, 0);
  95146. // Update bounding dimensions/positions
  95147. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  95148. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  95149. // Update gizmo to match bounding box scaling and rotation
  95150. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  95151. 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);
  95152. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  95153. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  95154. this._lineBoundingBox.computeWorldMatrix();
  95155. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  95156. // restore position/rotation values
  95157. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  95158. this.attachedMesh.position.copyFrom(this._tmpVector);
  95159. }
  95160. // Update rotation sphere locations
  95161. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  95162. for (var i = 0; i < 3; i++) {
  95163. for (var j = 0; j < 2; j++) {
  95164. for (var k = 0; k < 2; k++) {
  95165. var index = ((i * 4) + (j * 2)) + k;
  95166. if (i == 0) {
  95167. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  95168. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  95169. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  95170. }
  95171. if (i == 1) {
  95172. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  95173. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  95174. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  95175. }
  95176. if (i == 2) {
  95177. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  95178. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  95179. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  95180. }
  95181. if (this.fixedDragMeshScreenSize) {
  95182. this._rootMesh.computeWorldMatrix();
  95183. this._rotateSpheresParent.computeWorldMatrix();
  95184. rotateSpheres[index].computeWorldMatrix();
  95185. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  95186. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  95187. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  95188. }
  95189. else {
  95190. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  95191. }
  95192. }
  95193. }
  95194. }
  95195. // Update scale box locations
  95196. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  95197. for (var i = 0; i < 2; i++) {
  95198. for (var j = 0; j < 2; j++) {
  95199. for (var k = 0; k < 2; k++) {
  95200. var index = ((i * 4) + (j * 2)) + k;
  95201. if (scaleBoxes[index]) {
  95202. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  95203. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  95204. if (this.fixedDragMeshScreenSize) {
  95205. this._rootMesh.computeWorldMatrix();
  95206. this._scaleBoxesParent.computeWorldMatrix();
  95207. scaleBoxes[index].computeWorldMatrix();
  95208. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  95209. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  95210. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  95211. }
  95212. else {
  95213. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  95214. }
  95215. }
  95216. }
  95217. }
  95218. }
  95219. if (this.attachedMesh) {
  95220. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  95221. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  95222. }
  95223. };
  95224. /**
  95225. * Enables rotation on the specified axis and disables rotation on the others
  95226. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  95227. */
  95228. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  95229. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  95230. if (i < 4) {
  95231. m.setEnabled(axis.indexOf("x") != -1);
  95232. }
  95233. else if (i < 8) {
  95234. m.setEnabled(axis.indexOf("y") != -1);
  95235. }
  95236. else {
  95237. m.setEnabled(axis.indexOf("z") != -1);
  95238. }
  95239. });
  95240. };
  95241. /**
  95242. * Disposes of the gizmo
  95243. */
  95244. BoundingBoxGizmo.prototype.dispose = function () {
  95245. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  95246. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  95247. this._lineBoundingBox.dispose();
  95248. this._rotateSpheresParent.dispose();
  95249. this._scaleBoxesParent.dispose();
  95250. _super.prototype.dispose.call(this);
  95251. };
  95252. /**
  95253. * 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)
  95254. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  95255. * @returns the bounding box mesh with the passed in mesh as a child
  95256. */
  95257. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  95258. var makeNotPickable = function (root) {
  95259. root.isPickable = false;
  95260. root.getChildMeshes().forEach(function (c) {
  95261. makeNotPickable(c);
  95262. });
  95263. };
  95264. makeNotPickable(mesh);
  95265. // Reset position to get boudning box from origin with no rotation
  95266. if (!mesh.rotationQuaternion) {
  95267. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  95268. }
  95269. var oldPos = mesh.position.clone();
  95270. var oldRot = mesh.rotationQuaternion.clone();
  95271. mesh.rotationQuaternion.set(0, 0, 0, 1);
  95272. mesh.position.set(0, 0, 0);
  95273. // Update bounding dimensions/positions
  95274. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  95275. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  95276. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  95277. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  95278. // Restore original positions
  95279. mesh.addChild(box);
  95280. mesh.rotationQuaternion.copyFrom(oldRot);
  95281. mesh.position.copyFrom(oldPos);
  95282. // Reverse parenting
  95283. mesh.removeChild(box);
  95284. box.addChild(mesh);
  95285. box.visibility = 0;
  95286. return box;
  95287. };
  95288. /**
  95289. * CustomMeshes are not supported by this gizmo
  95290. * @param mesh The mesh to replace the default mesh of the gizmo
  95291. */
  95292. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  95293. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  95294. };
  95295. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  95296. // store/remove pivot point should only be applied during their outermost calls
  95297. BoundingBoxGizmo._PivotCached = 0;
  95298. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  95299. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  95300. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  95301. return BoundingBoxGizmo;
  95302. }(BABYLON.Gizmo));
  95303. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  95304. })(BABYLON || (BABYLON = {}));
  95305. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  95306. var BABYLON;
  95307. (function (BABYLON) {
  95308. /**
  95309. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  95310. */
  95311. var GizmoManager = /** @class */ (function () {
  95312. /**
  95313. * Instatiates a gizmo manager
  95314. * @param scene the scene to overlay the gizmos on top of
  95315. */
  95316. function GizmoManager(scene) {
  95317. var _this = this;
  95318. this.scene = scene;
  95319. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  95320. this._pointerObserver = null;
  95321. this._attachedMesh = null;
  95322. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  95323. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  95324. /**
  95325. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  95326. */
  95327. this.attachableMeshes = null;
  95328. /**
  95329. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  95330. */
  95331. this.usePointerToAttachGizmos = true;
  95332. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  95333. // Instatiate/dispose gizmos based on pointer actions
  95334. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  95335. if (!_this.usePointerToAttachGizmos) {
  95336. return;
  95337. }
  95338. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  95339. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  95340. var node = pointerInfo.pickInfo.pickedMesh;
  95341. if (_this.attachableMeshes == null) {
  95342. // Attach to the most parent node
  95343. while (node && node.parent != null) {
  95344. node = node.parent;
  95345. }
  95346. }
  95347. else {
  95348. // Attach to the parent node that is an attachableMesh
  95349. var found = false;
  95350. _this.attachableMeshes.forEach(function (mesh) {
  95351. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  95352. node = mesh;
  95353. found = true;
  95354. }
  95355. });
  95356. if (!found) {
  95357. node = null;
  95358. }
  95359. }
  95360. if (node instanceof BABYLON.AbstractMesh) {
  95361. _this.attachToMesh(node);
  95362. }
  95363. else {
  95364. _this.attachToMesh(null);
  95365. }
  95366. }
  95367. else {
  95368. _this.attachToMesh(null);
  95369. }
  95370. }
  95371. });
  95372. }
  95373. /**
  95374. * Attaches a set of gizmos to the specified mesh
  95375. * @param mesh The mesh the gizmo's should be attached to
  95376. */
  95377. GizmoManager.prototype.attachToMesh = function (mesh) {
  95378. if (this._attachedMesh) {
  95379. this._attachedMesh.removeBehavior(this._dragBehavior);
  95380. }
  95381. this._attachedMesh = mesh;
  95382. for (var key in this.gizmos) {
  95383. var gizmo = (this.gizmos[key]);
  95384. if (gizmo && this._gizmosEnabled[key]) {
  95385. gizmo.attachedMesh = mesh;
  95386. }
  95387. }
  95388. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  95389. this._attachedMesh.addBehavior(this._dragBehavior);
  95390. }
  95391. };
  95392. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  95393. get: function () {
  95394. return this._gizmosEnabled.positionGizmo;
  95395. },
  95396. /**
  95397. * If the position gizmo is enabled
  95398. */
  95399. set: function (value) {
  95400. if (value) {
  95401. if (!this.gizmos.positionGizmo) {
  95402. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  95403. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  95404. }
  95405. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  95406. }
  95407. else if (this.gizmos.positionGizmo) {
  95408. this.gizmos.positionGizmo.attachedMesh = null;
  95409. }
  95410. this._gizmosEnabled.positionGizmo = value;
  95411. },
  95412. enumerable: true,
  95413. configurable: true
  95414. });
  95415. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  95416. get: function () {
  95417. return this._gizmosEnabled.rotationGizmo;
  95418. },
  95419. /**
  95420. * If the rotation gizmo is enabled
  95421. */
  95422. set: function (value) {
  95423. if (value) {
  95424. if (!this.gizmos.rotationGizmo) {
  95425. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  95426. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  95427. }
  95428. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  95429. }
  95430. else if (this.gizmos.rotationGizmo) {
  95431. this.gizmos.rotationGizmo.attachedMesh = null;
  95432. }
  95433. this._gizmosEnabled.rotationGizmo = value;
  95434. },
  95435. enumerable: true,
  95436. configurable: true
  95437. });
  95438. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  95439. get: function () {
  95440. return this._gizmosEnabled.scaleGizmo;
  95441. },
  95442. /**
  95443. * If the scale gizmo is enabled
  95444. */
  95445. set: function (value) {
  95446. if (value) {
  95447. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  95448. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  95449. }
  95450. else if (this.gizmos.scaleGizmo) {
  95451. this.gizmos.scaleGizmo.attachedMesh = null;
  95452. }
  95453. this._gizmosEnabled.scaleGizmo = value;
  95454. },
  95455. enumerable: true,
  95456. configurable: true
  95457. });
  95458. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  95459. get: function () {
  95460. return this._gizmosEnabled.boundingBoxGizmo;
  95461. },
  95462. /**
  95463. * If the boundingBox gizmo is enabled
  95464. */
  95465. set: function (value) {
  95466. if (value) {
  95467. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  95468. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  95469. if (this._attachedMesh) {
  95470. this._attachedMesh.removeBehavior(this._dragBehavior);
  95471. this._attachedMesh.addBehavior(this._dragBehavior);
  95472. }
  95473. }
  95474. else if (this.gizmos.boundingBoxGizmo) {
  95475. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  95476. }
  95477. this._gizmosEnabled.boundingBoxGizmo = value;
  95478. },
  95479. enumerable: true,
  95480. configurable: true
  95481. });
  95482. /**
  95483. * Disposes of the gizmo manager
  95484. */
  95485. GizmoManager.prototype.dispose = function () {
  95486. this.scene.onPointerObservable.remove(this._pointerObserver);
  95487. for (var key in this.gizmos) {
  95488. var gizmo = (this.gizmos[key]);
  95489. if (gizmo) {
  95490. gizmo.dispose();
  95491. }
  95492. }
  95493. this._dragBehavior.detach();
  95494. };
  95495. return GizmoManager;
  95496. }());
  95497. BABYLON.GizmoManager = GizmoManager;
  95498. })(BABYLON || (BABYLON = {}));
  95499. //# sourceMappingURL=babylon.gizmoManager.js.map
  95500. var BABYLON;
  95501. (function (BABYLON) {
  95502. /**
  95503. * Defines a target to use with MorphTargetManager
  95504. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  95505. */
  95506. var MorphTarget = /** @class */ (function () {
  95507. /**
  95508. * Creates a new MorphTarget
  95509. * @param name defines the name of the target
  95510. * @param influence defines the influence to use
  95511. */
  95512. function MorphTarget(
  95513. /** defines the name of the target */
  95514. name, influence, scene) {
  95515. if (influence === void 0) { influence = 0; }
  95516. if (scene === void 0) { scene = null; }
  95517. this.name = name;
  95518. /**
  95519. * Gets or sets the list of animations
  95520. */
  95521. this.animations = new Array();
  95522. this._positions = null;
  95523. this._normals = null;
  95524. this._tangents = null;
  95525. /**
  95526. * Observable raised when the influence changes
  95527. */
  95528. this.onInfluenceChanged = new BABYLON.Observable();
  95529. this._animationPropertiesOverride = null;
  95530. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95531. this.influence = influence;
  95532. }
  95533. Object.defineProperty(MorphTarget.prototype, "influence", {
  95534. /**
  95535. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  95536. */
  95537. get: function () {
  95538. return this._influence;
  95539. },
  95540. set: function (influence) {
  95541. if (this._influence === influence) {
  95542. return;
  95543. }
  95544. var previous = this._influence;
  95545. this._influence = influence;
  95546. if (this.onInfluenceChanged.hasObservers) {
  95547. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  95548. }
  95549. },
  95550. enumerable: true,
  95551. configurable: true
  95552. });
  95553. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  95554. /**
  95555. * Gets or sets the animation properties override
  95556. */
  95557. get: function () {
  95558. if (!this._animationPropertiesOverride && this._scene) {
  95559. return this._scene.animationPropertiesOverride;
  95560. }
  95561. return this._animationPropertiesOverride;
  95562. },
  95563. set: function (value) {
  95564. this._animationPropertiesOverride = value;
  95565. },
  95566. enumerable: true,
  95567. configurable: true
  95568. });
  95569. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  95570. /**
  95571. * Gets a boolean defining if the target contains position data
  95572. */
  95573. get: function () {
  95574. return !!this._positions;
  95575. },
  95576. enumerable: true,
  95577. configurable: true
  95578. });
  95579. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  95580. /**
  95581. * Gets a boolean defining if the target contains normal data
  95582. */
  95583. get: function () {
  95584. return !!this._normals;
  95585. },
  95586. enumerable: true,
  95587. configurable: true
  95588. });
  95589. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  95590. /**
  95591. * Gets a boolean defining if the target contains tangent data
  95592. */
  95593. get: function () {
  95594. return !!this._tangents;
  95595. },
  95596. enumerable: true,
  95597. configurable: true
  95598. });
  95599. /**
  95600. * Affects position data to this target
  95601. * @param data defines the position data to use
  95602. */
  95603. MorphTarget.prototype.setPositions = function (data) {
  95604. this._positions = data;
  95605. };
  95606. /**
  95607. * Gets the position data stored in this target
  95608. * @returns a FloatArray containing the position data (or null if not present)
  95609. */
  95610. MorphTarget.prototype.getPositions = function () {
  95611. return this._positions;
  95612. };
  95613. /**
  95614. * Affects normal data to this target
  95615. * @param data defines the normal data to use
  95616. */
  95617. MorphTarget.prototype.setNormals = function (data) {
  95618. this._normals = data;
  95619. };
  95620. /**
  95621. * Gets the normal data stored in this target
  95622. * @returns a FloatArray containing the normal data (or null if not present)
  95623. */
  95624. MorphTarget.prototype.getNormals = function () {
  95625. return this._normals;
  95626. };
  95627. /**
  95628. * Affects tangent data to this target
  95629. * @param data defines the tangent data to use
  95630. */
  95631. MorphTarget.prototype.setTangents = function (data) {
  95632. this._tangents = data;
  95633. };
  95634. /**
  95635. * Gets the tangent data stored in this target
  95636. * @returns a FloatArray containing the tangent data (or null if not present)
  95637. */
  95638. MorphTarget.prototype.getTangents = function () {
  95639. return this._tangents;
  95640. };
  95641. /**
  95642. * Serializes the current target into a Serialization object
  95643. * @returns the serialized object
  95644. */
  95645. MorphTarget.prototype.serialize = function () {
  95646. var serializationObject = {};
  95647. serializationObject.name = this.name;
  95648. serializationObject.influence = this.influence;
  95649. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  95650. if (this.hasNormals) {
  95651. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  95652. }
  95653. if (this.hasTangents) {
  95654. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  95655. }
  95656. // Animations
  95657. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  95658. return serializationObject;
  95659. };
  95660. // Statics
  95661. /**
  95662. * Creates a new target from serialized data
  95663. * @param serializationObject defines the serialized data to use
  95664. * @returns a new MorphTarget
  95665. */
  95666. MorphTarget.Parse = function (serializationObject) {
  95667. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  95668. result.setPositions(serializationObject.positions);
  95669. if (serializationObject.normals) {
  95670. result.setNormals(serializationObject.normals);
  95671. }
  95672. if (serializationObject.tangents) {
  95673. result.setTangents(serializationObject.tangents);
  95674. }
  95675. // Animations
  95676. if (serializationObject.animations) {
  95677. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  95678. var parsedAnimation = serializationObject.animations[animationIndex];
  95679. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  95680. }
  95681. }
  95682. return result;
  95683. };
  95684. /**
  95685. * Creates a MorphTarget from mesh data
  95686. * @param mesh defines the source mesh
  95687. * @param name defines the name to use for the new target
  95688. * @param influence defines the influence to attach to the target
  95689. * @returns a new MorphTarget
  95690. */
  95691. MorphTarget.FromMesh = function (mesh, name, influence) {
  95692. if (!name) {
  95693. name = mesh.name;
  95694. }
  95695. var result = new MorphTarget(name, influence, mesh.getScene());
  95696. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  95697. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  95698. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  95699. }
  95700. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  95701. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  95702. }
  95703. return result;
  95704. };
  95705. return MorphTarget;
  95706. }());
  95707. BABYLON.MorphTarget = MorphTarget;
  95708. })(BABYLON || (BABYLON = {}));
  95709. //# sourceMappingURL=babylon.morphTarget.js.map
  95710. var BABYLON;
  95711. (function (BABYLON) {
  95712. /**
  95713. * This class is used to deform meshes using morphing between different targets
  95714. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  95715. */
  95716. var MorphTargetManager = /** @class */ (function () {
  95717. /**
  95718. * Creates a new MorphTargetManager
  95719. * @param scene defines the current scene
  95720. */
  95721. function MorphTargetManager(scene) {
  95722. if (scene === void 0) { scene = null; }
  95723. this._targets = new Array();
  95724. this._targetObservable = new Array();
  95725. this._activeTargets = new BABYLON.SmartArray(16);
  95726. this._supportsNormals = false;
  95727. this._supportsTangents = false;
  95728. this._vertexCount = 0;
  95729. this._uniqueId = 0;
  95730. this._tempInfluences = new Array();
  95731. if (!scene) {
  95732. scene = BABYLON.Engine.LastCreatedScene;
  95733. }
  95734. this._scene = scene;
  95735. if (this._scene) {
  95736. this._scene.morphTargetManagers.push(this);
  95737. this._uniqueId = this._scene.getUniqueId();
  95738. }
  95739. }
  95740. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  95741. /**
  95742. * Gets the unique ID of this manager
  95743. */
  95744. get: function () {
  95745. return this._uniqueId;
  95746. },
  95747. enumerable: true,
  95748. configurable: true
  95749. });
  95750. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  95751. /**
  95752. * Gets the number of vertices handled by this manager
  95753. */
  95754. get: function () {
  95755. return this._vertexCount;
  95756. },
  95757. enumerable: true,
  95758. configurable: true
  95759. });
  95760. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  95761. /**
  95762. * Gets a boolean indicating if this manager supports morphing of normals
  95763. */
  95764. get: function () {
  95765. return this._supportsNormals;
  95766. },
  95767. enumerable: true,
  95768. configurable: true
  95769. });
  95770. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  95771. /**
  95772. * Gets a boolean indicating if this manager supports morphing of tangents
  95773. */
  95774. get: function () {
  95775. return this._supportsTangents;
  95776. },
  95777. enumerable: true,
  95778. configurable: true
  95779. });
  95780. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  95781. /**
  95782. * Gets the number of targets stored in this manager
  95783. */
  95784. get: function () {
  95785. return this._targets.length;
  95786. },
  95787. enumerable: true,
  95788. configurable: true
  95789. });
  95790. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  95791. /**
  95792. * Gets the number of influencers (ie. the number of targets with influences > 0)
  95793. */
  95794. get: function () {
  95795. return this._activeTargets.length;
  95796. },
  95797. enumerable: true,
  95798. configurable: true
  95799. });
  95800. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  95801. /**
  95802. * Gets the list of influences (one per target)
  95803. */
  95804. get: function () {
  95805. return this._influences;
  95806. },
  95807. enumerable: true,
  95808. configurable: true
  95809. });
  95810. /**
  95811. * Gets the active target at specified index. An active target is a target with an influence > 0
  95812. * @param index defines the index to check
  95813. * @returns the requested target
  95814. */
  95815. MorphTargetManager.prototype.getActiveTarget = function (index) {
  95816. return this._activeTargets.data[index];
  95817. };
  95818. /**
  95819. * Gets the target at specified index
  95820. * @param index defines the index to check
  95821. * @returns the requested target
  95822. */
  95823. MorphTargetManager.prototype.getTarget = function (index) {
  95824. return this._targets[index];
  95825. };
  95826. /**
  95827. * Add a new target to this manager
  95828. * @param target defines the target to add
  95829. */
  95830. MorphTargetManager.prototype.addTarget = function (target) {
  95831. var _this = this;
  95832. this._targets.push(target);
  95833. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  95834. _this._syncActiveTargets(needUpdate);
  95835. }));
  95836. this._syncActiveTargets(true);
  95837. };
  95838. /**
  95839. * Removes a target from the manager
  95840. * @param target defines the target to remove
  95841. */
  95842. MorphTargetManager.prototype.removeTarget = function (target) {
  95843. var index = this._targets.indexOf(target);
  95844. if (index >= 0) {
  95845. this._targets.splice(index, 1);
  95846. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  95847. this._syncActiveTargets(true);
  95848. }
  95849. };
  95850. /**
  95851. * Serializes the current manager into a Serialization object
  95852. * @returns the serialized object
  95853. */
  95854. MorphTargetManager.prototype.serialize = function () {
  95855. var serializationObject = {};
  95856. serializationObject.id = this.uniqueId;
  95857. serializationObject.targets = [];
  95858. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  95859. var target = _a[_i];
  95860. serializationObject.targets.push(target.serialize());
  95861. }
  95862. return serializationObject;
  95863. };
  95864. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  95865. var influenceCount = 0;
  95866. this._activeTargets.reset();
  95867. this._supportsNormals = true;
  95868. this._supportsTangents = true;
  95869. this._vertexCount = 0;
  95870. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  95871. var target = _a[_i];
  95872. this._activeTargets.push(target);
  95873. this._tempInfluences[influenceCount++] = target.influence;
  95874. var positions = target.getPositions();
  95875. if (positions) {
  95876. this._supportsNormals = this._supportsNormals && target.hasNormals;
  95877. this._supportsTangents = this._supportsTangents && target.hasTangents;
  95878. var vertexCount = positions.length / 3;
  95879. if (this._vertexCount === 0) {
  95880. this._vertexCount = vertexCount;
  95881. }
  95882. else if (this._vertexCount !== vertexCount) {
  95883. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  95884. return;
  95885. }
  95886. }
  95887. }
  95888. if (!this._influences || this._influences.length !== influenceCount) {
  95889. this._influences = new Float32Array(influenceCount);
  95890. }
  95891. for (var index = 0; index < influenceCount; index++) {
  95892. this._influences[index] = this._tempInfluences[index];
  95893. }
  95894. if (needUpdate) {
  95895. this.synchronize();
  95896. }
  95897. };
  95898. /**
  95899. * Syncrhonize the targets with all the meshes using this morph target manager
  95900. */
  95901. MorphTargetManager.prototype.synchronize = function () {
  95902. if (!this._scene) {
  95903. return;
  95904. }
  95905. // Flag meshes as dirty to resync with the active targets
  95906. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  95907. var mesh = _a[_i];
  95908. if (mesh.morphTargetManager === this) {
  95909. mesh._syncGeometryWithMorphTargetManager();
  95910. }
  95911. }
  95912. };
  95913. // Statics
  95914. /**
  95915. * Creates a new MorphTargetManager from serialized data
  95916. * @param serializationObject defines the serialized data
  95917. * @param scene defines the hosting scene
  95918. * @returns the new MorphTargetManager
  95919. */
  95920. MorphTargetManager.Parse = function (serializationObject, scene) {
  95921. var result = new MorphTargetManager(scene);
  95922. result._uniqueId = serializationObject.id;
  95923. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  95924. var targetData = _a[_i];
  95925. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  95926. }
  95927. return result;
  95928. };
  95929. return MorphTargetManager;
  95930. }());
  95931. BABYLON.MorphTargetManager = MorphTargetManager;
  95932. })(BABYLON || (BABYLON = {}));
  95933. //# sourceMappingURL=babylon.morphTargetManager.js.map
  95934. var BABYLON;
  95935. (function (BABYLON) {
  95936. var Octree = /** @class */ (function () {
  95937. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  95938. if (maxDepth === void 0) { maxDepth = 2; }
  95939. this.maxDepth = maxDepth;
  95940. this.dynamicContent = new Array();
  95941. this._maxBlockCapacity = maxBlockCapacity || 64;
  95942. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  95943. this._creationFunc = creationFunc;
  95944. }
  95945. // Methods
  95946. Octree.prototype.update = function (worldMin, worldMax, entries) {
  95947. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  95948. };
  95949. Octree.prototype.addMesh = function (entry) {
  95950. for (var index = 0; index < this.blocks.length; index++) {
  95951. var block = this.blocks[index];
  95952. block.addEntry(entry);
  95953. }
  95954. };
  95955. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  95956. this._selectionContent.reset();
  95957. for (var index = 0; index < this.blocks.length; index++) {
  95958. var block = this.blocks[index];
  95959. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  95960. }
  95961. if (allowDuplicate) {
  95962. this._selectionContent.concat(this.dynamicContent);
  95963. }
  95964. else {
  95965. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  95966. }
  95967. return this._selectionContent;
  95968. };
  95969. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  95970. this._selectionContent.reset();
  95971. for (var index = 0; index < this.blocks.length; index++) {
  95972. var block = this.blocks[index];
  95973. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  95974. }
  95975. if (allowDuplicate) {
  95976. this._selectionContent.concat(this.dynamicContent);
  95977. }
  95978. else {
  95979. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  95980. }
  95981. return this._selectionContent;
  95982. };
  95983. Octree.prototype.intersectsRay = function (ray) {
  95984. this._selectionContent.reset();
  95985. for (var index = 0; index < this.blocks.length; index++) {
  95986. var block = this.blocks[index];
  95987. block.intersectsRay(ray, this._selectionContent);
  95988. }
  95989. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  95990. return this._selectionContent;
  95991. };
  95992. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  95993. target.blocks = new Array();
  95994. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  95995. // Segmenting space
  95996. for (var x = 0; x < 2; x++) {
  95997. for (var y = 0; y < 2; y++) {
  95998. for (var z = 0; z < 2; z++) {
  95999. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  96000. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  96001. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  96002. block.addEntries(entries);
  96003. target.blocks.push(block);
  96004. }
  96005. }
  96006. }
  96007. };
  96008. Octree.CreationFuncForMeshes = function (entry, block) {
  96009. var boundingInfo = entry.getBoundingInfo();
  96010. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  96011. block.entries.push(entry);
  96012. }
  96013. };
  96014. Octree.CreationFuncForSubMeshes = function (entry, block) {
  96015. var boundingInfo = entry.getBoundingInfo();
  96016. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  96017. block.entries.push(entry);
  96018. }
  96019. };
  96020. return Octree;
  96021. }());
  96022. BABYLON.Octree = Octree;
  96023. })(BABYLON || (BABYLON = {}));
  96024. //# sourceMappingURL=babylon.octree.js.map
  96025. var BABYLON;
  96026. (function (BABYLON) {
  96027. var OctreeBlock = /** @class */ (function () {
  96028. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  96029. this.entries = new Array();
  96030. this._boundingVectors = new Array();
  96031. this._capacity = capacity;
  96032. this._depth = depth;
  96033. this._maxDepth = maxDepth;
  96034. this._creationFunc = creationFunc;
  96035. this._minPoint = minPoint;
  96036. this._maxPoint = maxPoint;
  96037. this._boundingVectors.push(minPoint.clone());
  96038. this._boundingVectors.push(maxPoint.clone());
  96039. this._boundingVectors.push(minPoint.clone());
  96040. this._boundingVectors[2].x = maxPoint.x;
  96041. this._boundingVectors.push(minPoint.clone());
  96042. this._boundingVectors[3].y = maxPoint.y;
  96043. this._boundingVectors.push(minPoint.clone());
  96044. this._boundingVectors[4].z = maxPoint.z;
  96045. this._boundingVectors.push(maxPoint.clone());
  96046. this._boundingVectors[5].z = minPoint.z;
  96047. this._boundingVectors.push(maxPoint.clone());
  96048. this._boundingVectors[6].x = minPoint.x;
  96049. this._boundingVectors.push(maxPoint.clone());
  96050. this._boundingVectors[7].y = minPoint.y;
  96051. }
  96052. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  96053. // Property
  96054. get: function () {
  96055. return this._capacity;
  96056. },
  96057. enumerable: true,
  96058. configurable: true
  96059. });
  96060. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  96061. get: function () {
  96062. return this._minPoint;
  96063. },
  96064. enumerable: true,
  96065. configurable: true
  96066. });
  96067. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  96068. get: function () {
  96069. return this._maxPoint;
  96070. },
  96071. enumerable: true,
  96072. configurable: true
  96073. });
  96074. // Methods
  96075. OctreeBlock.prototype.addEntry = function (entry) {
  96076. if (this.blocks) {
  96077. for (var index = 0; index < this.blocks.length; index++) {
  96078. var block = this.blocks[index];
  96079. block.addEntry(entry);
  96080. }
  96081. return;
  96082. }
  96083. this._creationFunc(entry, this);
  96084. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  96085. this.createInnerBlocks();
  96086. }
  96087. };
  96088. OctreeBlock.prototype.addEntries = function (entries) {
  96089. for (var index = 0; index < entries.length; index++) {
  96090. var mesh = entries[index];
  96091. this.addEntry(mesh);
  96092. }
  96093. };
  96094. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  96095. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  96096. if (this.blocks) {
  96097. for (var index = 0; index < this.blocks.length; index++) {
  96098. var block = this.blocks[index];
  96099. block.select(frustumPlanes, selection, allowDuplicate);
  96100. }
  96101. return;
  96102. }
  96103. if (allowDuplicate) {
  96104. selection.concat(this.entries);
  96105. }
  96106. else {
  96107. selection.concatWithNoDuplicate(this.entries);
  96108. }
  96109. }
  96110. };
  96111. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  96112. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  96113. if (this.blocks) {
  96114. for (var index = 0; index < this.blocks.length; index++) {
  96115. var block = this.blocks[index];
  96116. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  96117. }
  96118. return;
  96119. }
  96120. if (allowDuplicate) {
  96121. selection.concat(this.entries);
  96122. }
  96123. else {
  96124. selection.concatWithNoDuplicate(this.entries);
  96125. }
  96126. }
  96127. };
  96128. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  96129. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  96130. if (this.blocks) {
  96131. for (var index = 0; index < this.blocks.length; index++) {
  96132. var block = this.blocks[index];
  96133. block.intersectsRay(ray, selection);
  96134. }
  96135. return;
  96136. }
  96137. selection.concatWithNoDuplicate(this.entries);
  96138. }
  96139. };
  96140. OctreeBlock.prototype.createInnerBlocks = function () {
  96141. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  96142. };
  96143. return OctreeBlock;
  96144. }());
  96145. BABYLON.OctreeBlock = OctreeBlock;
  96146. })(BABYLON || (BABYLON = {}));
  96147. //# sourceMappingURL=babylon.octreeBlock.js.map
  96148. var BABYLON;
  96149. (function (BABYLON) {
  96150. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  96151. if (maxCapacity === void 0) { maxCapacity = 64; }
  96152. if (maxDepth === void 0) { maxDepth = 2; }
  96153. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  96154. if (!component) {
  96155. component = new OctreeSceneComponent(this);
  96156. this._addComponent(component);
  96157. }
  96158. if (!this._selectionOctree) {
  96159. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  96160. }
  96161. var worldExtends = this.getWorldExtends();
  96162. // Update octree
  96163. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  96164. return this._selectionOctree;
  96165. };
  96166. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  96167. get: function () {
  96168. return this._selectionOctree;
  96169. },
  96170. enumerable: true,
  96171. configurable: true
  96172. });
  96173. /**
  96174. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  96175. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  96176. * @param maxCapacity defines the maximum size of each block (64 by default)
  96177. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  96178. * @returns the new octree
  96179. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  96180. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  96181. */
  96182. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  96183. if (maxCapacity === void 0) { maxCapacity = 64; }
  96184. if (maxDepth === void 0) { maxDepth = 2; }
  96185. var scene = this.getScene();
  96186. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  96187. if (!component) {
  96188. component = new OctreeSceneComponent(scene);
  96189. scene._addComponent(component);
  96190. }
  96191. if (!this._submeshesOctree) {
  96192. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  96193. }
  96194. this.computeWorldMatrix(true);
  96195. var boundingInfo = this.getBoundingInfo();
  96196. // Update octree
  96197. var bbox = boundingInfo.boundingBox;
  96198. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  96199. return this._submeshesOctree;
  96200. };
  96201. /**
  96202. * Defines the octree scene component responsible to manage any octrees
  96203. * in a given scene.
  96204. */
  96205. var OctreeSceneComponent = /** @class */ (function () {
  96206. /**
  96207. * Creates a new instance of the component for the given scene
  96208. * @param scene Defines the scene to register the component in
  96209. */
  96210. function OctreeSceneComponent(scene) {
  96211. /**
  96212. * The component name helpfull to identify the component in the list of scene components.
  96213. */
  96214. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  96215. /**
  96216. * Indicates if the meshes have been checked to make sure they are isEnabled()
  96217. */
  96218. this.checksIsEnabled = true;
  96219. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  96220. this.scene = scene;
  96221. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  96222. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  96223. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  96224. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  96225. }
  96226. /**
  96227. * Registers the component in a given scene
  96228. */
  96229. OctreeSceneComponent.prototype.register = function () {
  96230. var _this = this;
  96231. this.scene.onMeshRemovedObservable.add(function (mesh) {
  96232. var sceneOctree = _this.scene.selectionOctree;
  96233. if (sceneOctree !== undefined && sceneOctree !== null) {
  96234. var index = sceneOctree.dynamicContent.indexOf(mesh);
  96235. if (index !== -1) {
  96236. sceneOctree.dynamicContent.splice(index, 1);
  96237. }
  96238. }
  96239. });
  96240. this.scene.onMeshImportedObservable.add(function (mesh) {
  96241. var sceneOctree = _this.scene.selectionOctree;
  96242. if (sceneOctree !== undefined && sceneOctree !== null) {
  96243. sceneOctree.addMesh(mesh);
  96244. }
  96245. });
  96246. };
  96247. /**
  96248. * Return the list of active meshes
  96249. * @returns the list of active meshes
  96250. */
  96251. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  96252. if (this.scene._selectionOctree) {
  96253. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  96254. return selection;
  96255. }
  96256. return this.scene._getDefaultMeshCandidates();
  96257. };
  96258. /**
  96259. * Return the list of active sub meshes
  96260. * @param mesh The mesh to get the candidates sub meshes from
  96261. * @returns the list of active sub meshes
  96262. */
  96263. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  96264. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  96265. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  96266. return intersections;
  96267. }
  96268. return this.scene._getDefaultSubMeshCandidates(mesh);
  96269. };
  96270. /**
  96271. * Return the list of sub meshes intersecting with a given local ray
  96272. * @param mesh defines the mesh to find the submesh for
  96273. * @param localRay defines the ray in local space
  96274. * @returns the list of intersecting sub meshes
  96275. */
  96276. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  96277. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  96278. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  96279. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  96280. return intersections;
  96281. }
  96282. return this.scene._getDefaultSubMeshCandidates(mesh);
  96283. };
  96284. /**
  96285. * Return the list of sub meshes colliding with a collider
  96286. * @param mesh defines the mesh to find the submesh for
  96287. * @param collider defines the collider to evaluate the collision against
  96288. * @returns the list of colliding sub meshes
  96289. */
  96290. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  96291. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  96292. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  96293. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  96294. return intersections;
  96295. }
  96296. return this.scene._getDefaultSubMeshCandidates(mesh);
  96297. };
  96298. /**
  96299. * Rebuilds the elements related to this component in case of
  96300. * context lost for instance.
  96301. */
  96302. OctreeSceneComponent.prototype.rebuild = function () {
  96303. // Nothing to do here.
  96304. };
  96305. /**
  96306. * Disposes the component and the associated ressources.
  96307. */
  96308. OctreeSceneComponent.prototype.dispose = function () {
  96309. // Nothing to do here.
  96310. };
  96311. return OctreeSceneComponent;
  96312. }());
  96313. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  96314. })(BABYLON || (BABYLON = {}));
  96315. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  96316. var BABYLON;
  96317. (function (BABYLON) {
  96318. /**
  96319. * Postprocess used to generate anaglyphic rendering
  96320. */
  96321. var AnaglyphPostProcess = /** @class */ (function (_super) {
  96322. __extends(AnaglyphPostProcess, _super);
  96323. /**
  96324. * Creates a new AnaglyphPostProcess
  96325. * @param name defines postprocess name
  96326. * @param options defines creation options or target ratio scale
  96327. * @param rigCameras defines cameras using this postprocess
  96328. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  96329. * @param engine defines hosting engine
  96330. * @param reusable defines if the postprocess will be reused multiple times per frame
  96331. */
  96332. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  96333. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  96334. _this._passedProcess = rigCameras[0]._rigPostProcess;
  96335. _this.onApplyObservable.add(function (effect) {
  96336. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  96337. });
  96338. return _this;
  96339. }
  96340. return AnaglyphPostProcess;
  96341. }(BABYLON.PostProcess));
  96342. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  96343. })(BABYLON || (BABYLON = {}));
  96344. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  96345. var BABYLON;
  96346. (function (BABYLON) {
  96347. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  96348. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  96349. });
  96350. /**
  96351. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  96352. */
  96353. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  96354. __extends(AnaglyphArcRotateCamera, _super);
  96355. /**
  96356. * Creates a new AnaglyphArcRotateCamera
  96357. * @param name defines camera name
  96358. * @param alpha defines alpha angle (in radians)
  96359. * @param beta defines beta angle (in radians)
  96360. * @param radius defines radius
  96361. * @param target defines camera target
  96362. * @param interaxialDistance defines distance between each color axis
  96363. * @param scene defines the hosting scene
  96364. */
  96365. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  96366. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  96367. _this.interaxialDistance = interaxialDistance;
  96368. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  96369. return _this;
  96370. }
  96371. /**
  96372. * Gets camera class name
  96373. * @returns AnaglyphArcRotateCamera
  96374. */
  96375. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  96376. return "AnaglyphArcRotateCamera";
  96377. };
  96378. return AnaglyphArcRotateCamera;
  96379. }(BABYLON.ArcRotateCamera));
  96380. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  96381. })(BABYLON || (BABYLON = {}));
  96382. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  96383. var BABYLON;
  96384. (function (BABYLON) {
  96385. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  96386. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  96387. });
  96388. /**
  96389. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  96390. */
  96391. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  96392. __extends(AnaglyphFreeCamera, _super);
  96393. /**
  96394. * Creates a new AnaglyphFreeCamera
  96395. * @param name defines camera name
  96396. * @param position defines initial position
  96397. * @param interaxialDistance defines distance between each color axis
  96398. * @param scene defines the hosting scene
  96399. */
  96400. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  96401. var _this = _super.call(this, name, position, scene) || this;
  96402. _this.interaxialDistance = interaxialDistance;
  96403. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  96404. return _this;
  96405. }
  96406. /**
  96407. * Gets camera class name
  96408. * @returns AnaglyphFreeCamera
  96409. */
  96410. AnaglyphFreeCamera.prototype.getClassName = function () {
  96411. return "AnaglyphFreeCamera";
  96412. };
  96413. return AnaglyphFreeCamera;
  96414. }(BABYLON.FreeCamera));
  96415. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  96416. })(BABYLON || (BABYLON = {}));
  96417. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  96418. var BABYLON;
  96419. (function (BABYLON) {
  96420. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  96421. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  96422. });
  96423. /**
  96424. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  96425. */
  96426. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  96427. __extends(AnaglyphGamepadCamera, _super);
  96428. /**
  96429. * Creates a new AnaglyphGamepadCamera
  96430. * @param name defines camera name
  96431. * @param position defines initial position
  96432. * @param interaxialDistance defines distance between each color axis
  96433. * @param scene defines the hosting scene
  96434. */
  96435. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  96436. var _this = _super.call(this, name, position, scene) || this;
  96437. _this.interaxialDistance = interaxialDistance;
  96438. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  96439. return _this;
  96440. }
  96441. /**
  96442. * Gets camera class name
  96443. * @returns AnaglyphGamepadCamera
  96444. */
  96445. AnaglyphGamepadCamera.prototype.getClassName = function () {
  96446. return "AnaglyphGamepadCamera";
  96447. };
  96448. return AnaglyphGamepadCamera;
  96449. }(BABYLON.GamepadCamera));
  96450. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  96451. })(BABYLON || (BABYLON = {}));
  96452. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  96453. var BABYLON;
  96454. (function (BABYLON) {
  96455. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  96456. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  96457. });
  96458. /**
  96459. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  96460. */
  96461. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  96462. __extends(AnaglyphUniversalCamera, _super);
  96463. /**
  96464. * Creates a new AnaglyphUniversalCamera
  96465. * @param name defines camera name
  96466. * @param position defines initial position
  96467. * @param interaxialDistance defines distance between each color axis
  96468. * @param scene defines the hosting scene
  96469. */
  96470. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  96471. var _this = _super.call(this, name, position, scene) || this;
  96472. _this.interaxialDistance = interaxialDistance;
  96473. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  96474. return _this;
  96475. }
  96476. /**
  96477. * Gets camera class name
  96478. * @returns AnaglyphUniversalCamera
  96479. */
  96480. AnaglyphUniversalCamera.prototype.getClassName = function () {
  96481. return "AnaglyphUniversalCamera";
  96482. };
  96483. return AnaglyphUniversalCamera;
  96484. }(BABYLON.UniversalCamera));
  96485. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  96486. })(BABYLON || (BABYLON = {}));
  96487. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  96488. var BABYLON;
  96489. (function (BABYLON) {
  96490. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  96491. __extends(StereoscopicInterlacePostProcess, _super);
  96492. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  96493. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  96494. _this._passedProcess = rigCameras[0]._rigPostProcess;
  96495. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  96496. _this.onSizeChangedObservable.add(function () {
  96497. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  96498. });
  96499. _this.onApplyObservable.add(function (effect) {
  96500. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  96501. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  96502. });
  96503. return _this;
  96504. }
  96505. return StereoscopicInterlacePostProcess;
  96506. }(BABYLON.PostProcess));
  96507. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  96508. })(BABYLON || (BABYLON = {}));
  96509. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  96510. var BABYLON;
  96511. (function (BABYLON) {
  96512. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  96513. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96514. });
  96515. /**
  96516. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  96517. */
  96518. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  96519. __extends(StereoscopicArcRotateCamera, _super);
  96520. /**
  96521. * Creates a new StereoscopicArcRotateCamera
  96522. * @param name defines camera name
  96523. * @param alpha defines alpha angle (in radians)
  96524. * @param beta defines beta angle (in radians)
  96525. * @param radius defines radius
  96526. * @param target defines camera target
  96527. * @param interaxialDistance defines distance between each color axis
  96528. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96529. * @param scene defines the hosting scene
  96530. */
  96531. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  96532. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  96533. _this.interaxialDistance = interaxialDistance;
  96534. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96535. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96536. return _this;
  96537. }
  96538. /**
  96539. * Gets camera class name
  96540. * @returns StereoscopicArcRotateCamera
  96541. */
  96542. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  96543. return "StereoscopicArcRotateCamera";
  96544. };
  96545. return StereoscopicArcRotateCamera;
  96546. }(BABYLON.ArcRotateCamera));
  96547. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  96548. })(BABYLON || (BABYLON = {}));
  96549. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  96550. var BABYLON;
  96551. (function (BABYLON) {
  96552. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  96553. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96554. });
  96555. /**
  96556. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  96557. */
  96558. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  96559. __extends(StereoscopicFreeCamera, _super);
  96560. /**
  96561. * Creates a new StereoscopicFreeCamera
  96562. * @param name defines camera name
  96563. * @param position defines initial position
  96564. * @param interaxialDistance defines distance between each color axis
  96565. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96566. * @param scene defines the hosting scene
  96567. */
  96568. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96569. var _this = _super.call(this, name, position, scene) || this;
  96570. _this.interaxialDistance = interaxialDistance;
  96571. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96572. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96573. return _this;
  96574. }
  96575. /**
  96576. * Gets camera class name
  96577. * @returns StereoscopicFreeCamera
  96578. */
  96579. StereoscopicFreeCamera.prototype.getClassName = function () {
  96580. return "StereoscopicFreeCamera";
  96581. };
  96582. return StereoscopicFreeCamera;
  96583. }(BABYLON.FreeCamera));
  96584. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  96585. })(BABYLON || (BABYLON = {}));
  96586. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  96587. var BABYLON;
  96588. (function (BABYLON) {
  96589. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  96590. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96591. });
  96592. /**
  96593. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  96594. */
  96595. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  96596. __extends(StereoscopicGamepadCamera, _super);
  96597. /**
  96598. * Creates a new StereoscopicGamepadCamera
  96599. * @param name defines camera name
  96600. * @param position defines initial position
  96601. * @param interaxialDistance defines distance between each color axis
  96602. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96603. * @param scene defines the hosting scene
  96604. */
  96605. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96606. var _this = _super.call(this, name, position, scene) || this;
  96607. _this.interaxialDistance = interaxialDistance;
  96608. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96609. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96610. return _this;
  96611. }
  96612. /**
  96613. * Gets camera class name
  96614. * @returns StereoscopicGamepadCamera
  96615. */
  96616. StereoscopicGamepadCamera.prototype.getClassName = function () {
  96617. return "StereoscopicGamepadCamera";
  96618. };
  96619. return StereoscopicGamepadCamera;
  96620. }(BABYLON.GamepadCamera));
  96621. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  96622. })(BABYLON || (BABYLON = {}));
  96623. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  96624. var BABYLON;
  96625. (function (BABYLON) {
  96626. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  96627. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96628. });
  96629. /**
  96630. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  96631. */
  96632. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  96633. __extends(StereoscopicUniversalCamera, _super);
  96634. /**
  96635. * Creates a new StereoscopicUniversalCamera
  96636. * @param name defines camera name
  96637. * @param position defines initial position
  96638. * @param interaxialDistance defines distance between each color axis
  96639. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96640. * @param scene defines the hosting scene
  96641. */
  96642. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96643. var _this = _super.call(this, name, position, scene) || this;
  96644. _this.interaxialDistance = interaxialDistance;
  96645. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96646. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96647. return _this;
  96648. }
  96649. /**
  96650. * Gets camera class name
  96651. * @returns StereoscopicUniversalCamera
  96652. */
  96653. StereoscopicUniversalCamera.prototype.getClassName = function () {
  96654. return "StereoscopicUniversalCamera";
  96655. };
  96656. return StereoscopicUniversalCamera;
  96657. }(BABYLON.UniversalCamera));
  96658. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  96659. })(BABYLON || (BABYLON = {}));
  96660. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  96661. var BABYLON;
  96662. (function (BABYLON) {
  96663. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  96664. __extends(VRDistortionCorrectionPostProcess, _super);
  96665. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  96666. var _this = _super.call(this, name, "vrDistortionCorrection", [
  96667. 'LensCenter',
  96668. 'Scale',
  96669. 'ScaleIn',
  96670. 'HmdWarpParam'
  96671. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  96672. _this._isRightEye = isRightEye;
  96673. _this._distortionFactors = vrMetrics.distortionK;
  96674. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  96675. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  96676. _this.adaptScaleToCurrentViewport = true;
  96677. _this.onSizeChangedObservable.add(function () {
  96678. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  96679. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  96680. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  96681. });
  96682. _this.onApplyObservable.add(function (effect) {
  96683. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  96684. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  96685. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  96686. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  96687. });
  96688. return _this;
  96689. }
  96690. return VRDistortionCorrectionPostProcess;
  96691. }(BABYLON.PostProcess));
  96692. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  96693. })(BABYLON || (BABYLON = {}));
  96694. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  96695. var BABYLON;
  96696. (function (BABYLON) {
  96697. /**
  96698. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  96699. * Screen rotation is taken into account.
  96700. */
  96701. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  96702. function FreeCameraDeviceOrientationInput() {
  96703. var _this = this;
  96704. this._screenOrientationAngle = 0;
  96705. this._screenQuaternion = new BABYLON.Quaternion();
  96706. this._alpha = 0;
  96707. this._beta = 0;
  96708. this._gamma = 0;
  96709. this._orientationChanged = function () {
  96710. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  96711. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  96712. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  96713. };
  96714. this._deviceOrientation = function (evt) {
  96715. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  96716. _this._beta = evt.beta !== null ? evt.beta : 0;
  96717. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  96718. };
  96719. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  96720. this._orientationChanged();
  96721. }
  96722. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  96723. get: function () {
  96724. return this._camera;
  96725. },
  96726. set: function (camera) {
  96727. this._camera = camera;
  96728. if (this._camera != null && !this._camera.rotationQuaternion) {
  96729. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  96730. }
  96731. },
  96732. enumerable: true,
  96733. configurable: true
  96734. });
  96735. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  96736. window.addEventListener("orientationchange", this._orientationChanged);
  96737. window.addEventListener("deviceorientation", this._deviceOrientation);
  96738. //In certain cases, the attach control is called AFTER orientation was changed,
  96739. //So this is needed.
  96740. this._orientationChanged();
  96741. };
  96742. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  96743. window.removeEventListener("orientationchange", this._orientationChanged);
  96744. window.removeEventListener("deviceorientation", this._deviceOrientation);
  96745. };
  96746. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  96747. //if no device orientation provided, don't update the rotation.
  96748. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  96749. if (!this._alpha)
  96750. return;
  96751. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  96752. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  96753. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  96754. //Mirror on XY Plane
  96755. this._camera.rotationQuaternion.z *= -1;
  96756. this._camera.rotationQuaternion.w *= -1;
  96757. };
  96758. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  96759. return "FreeCameraDeviceOrientationInput";
  96760. };
  96761. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  96762. return "deviceOrientation";
  96763. };
  96764. return FreeCameraDeviceOrientationInput;
  96765. }());
  96766. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  96767. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  96768. })(BABYLON || (BABYLON = {}));
  96769. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  96770. var BABYLON;
  96771. (function (BABYLON) {
  96772. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  96773. function ArcRotateCameraVRDeviceOrientationInput() {
  96774. this.alphaCorrection = 1;
  96775. this.betaCorrection = 1;
  96776. this.gammaCorrection = 1;
  96777. this._alpha = 0;
  96778. this._gamma = 0;
  96779. this._dirty = false;
  96780. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  96781. }
  96782. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  96783. this.camera.attachControl(element, noPreventDefault);
  96784. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  96785. };
  96786. /** @hidden */
  96787. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  96788. if (evt.alpha !== null) {
  96789. this._alpha = +evt.alpha | 0;
  96790. }
  96791. if (evt.gamma !== null) {
  96792. this._gamma = +evt.gamma | 0;
  96793. }
  96794. this._dirty = true;
  96795. };
  96796. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  96797. if (this._dirty) {
  96798. this._dirty = false;
  96799. if (this._gamma < 0) {
  96800. this._gamma = 180 + this._gamma;
  96801. }
  96802. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  96803. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  96804. }
  96805. };
  96806. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  96807. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  96808. };
  96809. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  96810. return "ArcRotateCameraVRDeviceOrientationInput";
  96811. };
  96812. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  96813. return "VRDeviceOrientation";
  96814. };
  96815. return ArcRotateCameraVRDeviceOrientationInput;
  96816. }());
  96817. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  96818. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  96819. })(BABYLON || (BABYLON = {}));
  96820. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  96821. var BABYLON;
  96822. (function (BABYLON) {
  96823. var VRCameraMetrics = /** @class */ (function () {
  96824. function VRCameraMetrics() {
  96825. this.compensateDistortion = true;
  96826. }
  96827. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  96828. get: function () {
  96829. return this.hResolution / (2 * this.vResolution);
  96830. },
  96831. enumerable: true,
  96832. configurable: true
  96833. });
  96834. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  96835. get: function () {
  96836. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  96837. },
  96838. enumerable: true,
  96839. configurable: true
  96840. });
  96841. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  96842. get: function () {
  96843. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  96844. var h = (4 * meters) / this.hScreenSize;
  96845. return BABYLON.Matrix.Translation(h, 0, 0);
  96846. },
  96847. enumerable: true,
  96848. configurable: true
  96849. });
  96850. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  96851. get: function () {
  96852. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  96853. var h = (4 * meters) / this.hScreenSize;
  96854. return BABYLON.Matrix.Translation(-h, 0, 0);
  96855. },
  96856. enumerable: true,
  96857. configurable: true
  96858. });
  96859. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  96860. get: function () {
  96861. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  96862. },
  96863. enumerable: true,
  96864. configurable: true
  96865. });
  96866. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  96867. get: function () {
  96868. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  96869. },
  96870. enumerable: true,
  96871. configurable: true
  96872. });
  96873. VRCameraMetrics.GetDefault = function () {
  96874. var result = new VRCameraMetrics();
  96875. result.hResolution = 1280;
  96876. result.vResolution = 800;
  96877. result.hScreenSize = 0.149759993;
  96878. result.vScreenSize = 0.0935999975;
  96879. result.vScreenCenter = 0.0467999987;
  96880. result.eyeToScreenDistance = 0.0410000011;
  96881. result.lensSeparationDistance = 0.0635000020;
  96882. result.interpupillaryDistance = 0.0640000030;
  96883. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  96884. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  96885. result.postProcessScaleFactor = 1.714605507808412;
  96886. result.lensCenterOffset = 0.151976421;
  96887. return result;
  96888. };
  96889. return VRCameraMetrics;
  96890. }());
  96891. BABYLON.VRCameraMetrics = VRCameraMetrics;
  96892. })(BABYLON || (BABYLON = {}));
  96893. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  96894. var BABYLON;
  96895. (function (BABYLON) {
  96896. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  96897. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  96898. });
  96899. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  96900. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  96901. });
  96902. /**
  96903. * This represents a WebVR camera.
  96904. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  96905. * @example http://doc.babylonjs.com/how_to/webvr_camera
  96906. */
  96907. var WebVRFreeCamera = /** @class */ (function (_super) {
  96908. __extends(WebVRFreeCamera, _super);
  96909. /**
  96910. * Instantiates a WebVRFreeCamera.
  96911. * @param name The name of the WebVRFreeCamera
  96912. * @param position The starting anchor position for the camera
  96913. * @param scene The scene the camera belongs to
  96914. * @param webVROptions a set of customizable options for the webVRCamera
  96915. */
  96916. function WebVRFreeCamera(name, position, scene, webVROptions) {
  96917. if (webVROptions === void 0) { webVROptions = {}; }
  96918. var _this = _super.call(this, name, position, scene) || this;
  96919. _this.webVROptions = webVROptions;
  96920. /**
  96921. * @hidden
  96922. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  96923. */
  96924. _this._vrDevice = null;
  96925. /**
  96926. * The rawPose of the vrDevice.
  96927. */
  96928. _this.rawPose = null;
  96929. _this._specsVersion = "1.1";
  96930. _this._attached = false;
  96931. _this._descendants = [];
  96932. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  96933. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  96934. /** @hidden */
  96935. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  96936. _this._standingMatrix = null;
  96937. /**
  96938. * Represents device position in babylon space.
  96939. */
  96940. _this.devicePosition = BABYLON.Vector3.Zero();
  96941. /**
  96942. * Represents device rotation in babylon space.
  96943. */
  96944. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  96945. /**
  96946. * The scale of the device to be used when translating from device space to babylon space.
  96947. */
  96948. _this.deviceScaleFactor = 1;
  96949. _this._deviceToWorld = BABYLON.Matrix.Identity();
  96950. _this._worldToDevice = BABYLON.Matrix.Identity();
  96951. /**
  96952. * References to the webVR controllers for the vrDevice.
  96953. */
  96954. _this.controllers = [];
  96955. /**
  96956. * Emits an event when a controller is attached.
  96957. */
  96958. _this.onControllersAttachedObservable = new BABYLON.Observable();
  96959. /**
  96960. * Emits an event when a controller's mesh has been loaded;
  96961. */
  96962. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  96963. /**
  96964. * Emits an event when the HMD's pose has been updated.
  96965. */
  96966. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  96967. _this._poseSet = false;
  96968. /**
  96969. * If the rig cameras be used as parent instead of this camera.
  96970. */
  96971. _this.rigParenting = true;
  96972. _this._defaultHeight = undefined;
  96973. _this._htmlElementAttached = null;
  96974. _this._detachIfAttached = function () {
  96975. var vrDisplay = _this.getEngine().getVRDevice();
  96976. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  96977. _this.detachControl(_this._htmlElementAttached);
  96978. }
  96979. };
  96980. _this._workingVector = BABYLON.Vector3.Zero();
  96981. _this._oneVector = BABYLON.Vector3.One();
  96982. _this._workingMatrix = BABYLON.Matrix.Identity();
  96983. _this._tmpMatrix = new BABYLON.Matrix();
  96984. _this._cache.position = BABYLON.Vector3.Zero();
  96985. if (webVROptions.defaultHeight) {
  96986. _this._defaultHeight = webVROptions.defaultHeight;
  96987. _this.position.y = _this._defaultHeight;
  96988. }
  96989. _this.minZ = 0.1;
  96990. //legacy support - the compensation boolean was removed.
  96991. if (arguments.length === 5) {
  96992. _this.webVROptions = arguments[4];
  96993. }
  96994. // default webVR options
  96995. if (_this.webVROptions.trackPosition == undefined) {
  96996. _this.webVROptions.trackPosition = true;
  96997. }
  96998. if (_this.webVROptions.controllerMeshes == undefined) {
  96999. _this.webVROptions.controllerMeshes = true;
  97000. }
  97001. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  97002. _this.webVROptions.defaultLightingOnControllers = true;
  97003. }
  97004. _this.rotationQuaternion = new BABYLON.Quaternion();
  97005. if (_this.webVROptions && _this.webVROptions.positionScale) {
  97006. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  97007. }
  97008. //enable VR
  97009. var engine = _this.getEngine();
  97010. _this._onVREnabled = function (success) { if (success) {
  97011. _this.initControllers();
  97012. } };
  97013. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  97014. engine.initWebVR().add(function (event) {
  97015. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  97016. return;
  97017. }
  97018. _this._vrDevice = event.vrDisplay;
  97019. //reset the rig parameters.
  97020. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  97021. if (_this._attached) {
  97022. _this.getEngine().enableVR();
  97023. }
  97024. });
  97025. if (typeof (VRFrameData) !== "undefined")
  97026. _this._frameData = new VRFrameData();
  97027. /**
  97028. * The idea behind the following lines:
  97029. * objects that have the camera as parent should actually have the rig cameras as a parent.
  97030. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  97031. * the second will not show it correctly.
  97032. *
  97033. * To solve this - each object that has the camera as parent will be added to a protected array.
  97034. * When the rig camera renders, it will take this array and set all of those to be its children.
  97035. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  97036. * Amazing!
  97037. */
  97038. scene.onBeforeCameraRenderObservable.add(function (camera) {
  97039. if (camera.parent === _this && _this.rigParenting) {
  97040. _this._descendants = _this.getDescendants(true, function (n) {
  97041. // don't take the cameras or the controllers!
  97042. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  97043. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  97044. return !isController && !isRigCamera;
  97045. });
  97046. _this._descendants.forEach(function (node) {
  97047. node.parent = camera;
  97048. });
  97049. }
  97050. });
  97051. scene.onAfterCameraRenderObservable.add(function (camera) {
  97052. if (camera.parent === _this && _this.rigParenting) {
  97053. _this._descendants.forEach(function (node) {
  97054. node.parent = _this;
  97055. });
  97056. }
  97057. });
  97058. return _this;
  97059. }
  97060. /**
  97061. * Gets the device distance from the ground in meters.
  97062. * @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.
  97063. */
  97064. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  97065. if (this._standingMatrix) {
  97066. // Add standing matrix offset to get real offset from ground in room
  97067. this._standingMatrix.getTranslationToRef(this._workingVector);
  97068. return this._deviceRoomPosition.y + this._workingVector.y;
  97069. }
  97070. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  97071. return this._defaultHeight || 0;
  97072. };
  97073. /**
  97074. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  97075. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  97076. */
  97077. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  97078. var _this = this;
  97079. if (callback === void 0) { callback = function (bool) { }; }
  97080. // Use standing matrix if available
  97081. this.getEngine().initWebVRAsync().then(function (result) {
  97082. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  97083. callback(false);
  97084. }
  97085. else {
  97086. _this._standingMatrix = new BABYLON.Matrix();
  97087. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  97088. if (!_this.getScene().useRightHandedSystem) {
  97089. [2, 6, 8, 9, 14].forEach(function (num) {
  97090. if (_this._standingMatrix) {
  97091. _this._standingMatrix.m[num] *= -1;
  97092. }
  97093. });
  97094. }
  97095. callback(true);
  97096. }
  97097. });
  97098. };
  97099. /**
  97100. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  97101. * @returns A promise with a boolean set to if the standing matrix is supported.
  97102. */
  97103. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  97104. var _this = this;
  97105. return new Promise(function (res, rej) {
  97106. _this.useStandingMatrix(function (supported) {
  97107. res(supported);
  97108. });
  97109. });
  97110. };
  97111. /**
  97112. * Disposes the camera
  97113. */
  97114. WebVRFreeCamera.prototype.dispose = function () {
  97115. this._detachIfAttached();
  97116. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  97117. _super.prototype.dispose.call(this);
  97118. };
  97119. /**
  97120. * Gets a vrController by name.
  97121. * @param name The name of the controller to retreive
  97122. * @returns the controller matching the name specified or null if not found
  97123. */
  97124. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  97125. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  97126. var gp = _a[_i];
  97127. if (gp.hand === name) {
  97128. return gp;
  97129. }
  97130. }
  97131. return null;
  97132. };
  97133. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  97134. /**
  97135. * The controller corrisponding to the users left hand.
  97136. */
  97137. get: function () {
  97138. if (!this._leftController) {
  97139. this._leftController = this.getControllerByName("left");
  97140. }
  97141. return this._leftController;
  97142. },
  97143. enumerable: true,
  97144. configurable: true
  97145. });
  97146. ;
  97147. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  97148. /**
  97149. * The controller corrisponding to the users right hand.
  97150. */
  97151. get: function () {
  97152. if (!this._rightController) {
  97153. this._rightController = this.getControllerByName("right");
  97154. }
  97155. return this._rightController;
  97156. },
  97157. enumerable: true,
  97158. configurable: true
  97159. });
  97160. ;
  97161. /**
  97162. * Casts a ray forward from the vrCamera's gaze.
  97163. * @param length Length of the ray (default: 100)
  97164. * @returns the ray corrisponding to the gaze
  97165. */
  97166. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  97167. if (length === void 0) { length = 100; }
  97168. if (this.leftCamera) {
  97169. // Use left eye to avoid computation to compute center on every call
  97170. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  97171. }
  97172. else {
  97173. return _super.prototype.getForwardRay.call(this, length);
  97174. }
  97175. };
  97176. /**
  97177. * @hidden
  97178. * Updates the camera based on device's frame data
  97179. */
  97180. WebVRFreeCamera.prototype._checkInputs = function () {
  97181. if (this._vrDevice && this._vrDevice.isPresenting) {
  97182. this._vrDevice.getFrameData(this._frameData);
  97183. this.updateFromDevice(this._frameData.pose);
  97184. }
  97185. _super.prototype._checkInputs.call(this);
  97186. };
  97187. /**
  97188. * Updates the poseControlled values based on the input device pose.
  97189. * @param poseData Pose coming from the device
  97190. */
  97191. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  97192. if (poseData && poseData.orientation) {
  97193. this.rawPose = poseData;
  97194. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  97195. if (this.getScene().useRightHandedSystem) {
  97196. this._deviceRoomRotationQuaternion.z *= -1;
  97197. this._deviceRoomRotationQuaternion.w *= -1;
  97198. }
  97199. if (this.webVROptions.trackPosition && this.rawPose.position) {
  97200. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  97201. if (this.getScene().useRightHandedSystem) {
  97202. this._deviceRoomPosition.z *= -1;
  97203. }
  97204. }
  97205. this._poseSet = true;
  97206. }
  97207. };
  97208. /**
  97209. * WebVR's attach control will start broadcasting frames to the device.
  97210. * Note that in certain browsers (chrome for example) this function must be called
  97211. * within a user-interaction callback. Example:
  97212. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  97213. *
  97214. * @param element html element to attach the vrDevice to
  97215. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  97216. */
  97217. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  97218. _super.prototype.attachControl.call(this, element, noPreventDefault);
  97219. this._attached = true;
  97220. this._htmlElementAttached = element;
  97221. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  97222. if (this._vrDevice) {
  97223. this.getEngine().enableVR();
  97224. }
  97225. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  97226. };
  97227. /**
  97228. * Detaches the camera from the html element and disables VR
  97229. *
  97230. * @param element html element to detach from
  97231. */
  97232. WebVRFreeCamera.prototype.detachControl = function (element) {
  97233. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  97234. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  97235. _super.prototype.detachControl.call(this, element);
  97236. this._attached = false;
  97237. this.getEngine().disableVR();
  97238. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  97239. };
  97240. /**
  97241. * @returns the name of this class
  97242. */
  97243. WebVRFreeCamera.prototype.getClassName = function () {
  97244. return "WebVRFreeCamera";
  97245. };
  97246. /**
  97247. * Calls resetPose on the vrDisplay
  97248. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  97249. */
  97250. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  97251. //uses the vrDisplay's "resetPose()".
  97252. //pitch and roll won't be affected.
  97253. this._vrDevice.resetPose();
  97254. };
  97255. /**
  97256. * @hidden
  97257. * Updates the rig cameras (left and right eye)
  97258. */
  97259. WebVRFreeCamera.prototype._updateRigCameras = function () {
  97260. var camLeft = this._rigCameras[0];
  97261. var camRight = this._rigCameras[1];
  97262. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  97263. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  97264. camLeft.position.copyFrom(this._deviceRoomPosition);
  97265. camRight.position.copyFrom(this._deviceRoomPosition);
  97266. };
  97267. // Remove translation from 6dof headset if trackposition is set to false
  97268. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  97269. if (isViewMatrix === void 0) { isViewMatrix = false; }
  97270. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  97271. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  97272. if (!isViewMatrix) {
  97273. this._tmpMatrix.invert();
  97274. }
  97275. this._tmpMatrix.multiplyToRef(matrix, matrix);
  97276. }
  97277. };
  97278. /**
  97279. * @hidden
  97280. * Updates the cached values of the camera
  97281. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  97282. */
  97283. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  97284. var _this = this;
  97285. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  97286. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  97287. if (!this.updateCacheCalled) {
  97288. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  97289. this.updateCacheCalled = true;
  97290. this.update();
  97291. }
  97292. // Set working vector to the device position in room space rotated by the new rotation
  97293. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  97294. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  97295. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  97296. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  97297. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  97298. // Add translation from anchor position
  97299. this._deviceToWorld.getTranslationToRef(this._workingVector);
  97300. this._workingVector.addInPlace(this.position);
  97301. this._workingVector.subtractInPlace(this._cache.position);
  97302. this._deviceToWorld.setTranslation(this._workingVector);
  97303. // Set an inverted matrix to be used when updating the camera
  97304. this._deviceToWorld.invertToRef(this._worldToDevice);
  97305. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  97306. this.controllers.forEach(function (controller) {
  97307. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  97308. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  97309. controller.update();
  97310. });
  97311. }
  97312. if (!ignoreParentClass) {
  97313. _super.prototype._updateCache.call(this);
  97314. }
  97315. this.updateCacheCalled = false;
  97316. };
  97317. /**
  97318. * Updates the current device position and rotation in the babylon world
  97319. */
  97320. WebVRFreeCamera.prototype.update = function () {
  97321. // Get current device position in babylon world
  97322. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  97323. // Get current device rotation in babylon world
  97324. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  97325. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  97326. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  97327. if (this._poseSet) {
  97328. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  97329. }
  97330. _super.prototype.update.call(this);
  97331. };
  97332. /**
  97333. * @hidden
  97334. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  97335. * @returns an identity matrix
  97336. */
  97337. WebVRFreeCamera.prototype._getViewMatrix = function () {
  97338. return BABYLON.Matrix.Identity();
  97339. };
  97340. /**
  97341. * This function is called by the two RIG cameras.
  97342. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  97343. */
  97344. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  97345. var _this = this;
  97346. // Update the parent camera prior to using a child camera to avoid desynchronization
  97347. var parentCamera = this._cameraRigParams["parentCamera"];
  97348. parentCamera._updateCache();
  97349. //WebVR 1.1
  97350. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  97351. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  97352. if (!this.getScene().useRightHandedSystem) {
  97353. [2, 6, 8, 9, 14].forEach(function (num) {
  97354. _this._webvrViewMatrix.m[num] *= -1;
  97355. });
  97356. }
  97357. // update the camera rotation matrix
  97358. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  97359. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  97360. // Computing target and final matrix
  97361. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  97362. // should the view matrix be updated with scale and position offset?
  97363. if (parentCamera.deviceScaleFactor !== 1) {
  97364. this._webvrViewMatrix.invert();
  97365. // scale the position, if set
  97366. if (parentCamera.deviceScaleFactor) {
  97367. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  97368. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  97369. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  97370. }
  97371. this._webvrViewMatrix.invert();
  97372. }
  97373. // Remove translation from 6dof headset if trackposition is set to false
  97374. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  97375. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  97376. // Compute global position
  97377. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  97378. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  97379. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  97380. this._workingMatrix.getTranslationToRef(this._globalPosition);
  97381. this._markSyncedWithParent();
  97382. return this._webvrViewMatrix;
  97383. };
  97384. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  97385. var _this = this;
  97386. var parentCamera = this.parent;
  97387. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  97388. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  97389. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  97390. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  97391. //babylon compatible matrix
  97392. if (!this.getScene().useRightHandedSystem) {
  97393. [8, 9, 10, 11].forEach(function (num) {
  97394. _this._projectionMatrix.m[num] *= -1;
  97395. });
  97396. }
  97397. return this._projectionMatrix;
  97398. };
  97399. /**
  97400. * Initializes the controllers and their meshes
  97401. */
  97402. WebVRFreeCamera.prototype.initControllers = function () {
  97403. var _this = this;
  97404. this.controllers = [];
  97405. var manager = this.getScene().gamepadManager;
  97406. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  97407. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  97408. var webVrController = gamepad;
  97409. if (webVrController.defaultModel) {
  97410. webVrController.defaultModel.setEnabled(false);
  97411. }
  97412. if (webVrController.hand === "right") {
  97413. _this._rightController = null;
  97414. }
  97415. if (webVrController.hand === "left") {
  97416. _this._leftController = null;
  97417. }
  97418. var controllerIndex = _this.controllers.indexOf(webVrController);
  97419. if (controllerIndex !== -1) {
  97420. _this.controllers.splice(controllerIndex, 1);
  97421. }
  97422. }
  97423. });
  97424. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  97425. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  97426. var webVrController_1 = gamepad;
  97427. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  97428. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  97429. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  97430. if (_this.webVROptions.controllerMeshes) {
  97431. if (webVrController_1.defaultModel) {
  97432. webVrController_1.defaultModel.setEnabled(true);
  97433. }
  97434. else {
  97435. // Load the meshes
  97436. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  97437. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  97438. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  97439. if (_this.webVROptions.defaultLightingOnControllers) {
  97440. if (!_this._lightOnControllers) {
  97441. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  97442. }
  97443. var activateLightOnSubMeshes_1 = function (mesh, light) {
  97444. var children = mesh.getChildren();
  97445. if (children && children.length !== 0) {
  97446. children.forEach(function (mesh) {
  97447. light.includedOnlyMeshes.push(mesh);
  97448. activateLightOnSubMeshes_1(mesh, light);
  97449. });
  97450. }
  97451. };
  97452. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  97453. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  97454. }
  97455. });
  97456. }
  97457. }
  97458. webVrController_1.attachToPoseControlledCamera(_this);
  97459. // since this is async - sanity check. Is the controller already stored?
  97460. if (_this.controllers.indexOf(webVrController_1) === -1) {
  97461. //add to the controllers array
  97462. _this.controllers.push(webVrController_1);
  97463. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  97464. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  97465. // So we're overriding setting left & right manually to be sure
  97466. var firstViveWandDetected = false;
  97467. for (var i = 0; i < _this.controllers.length; i++) {
  97468. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  97469. if (!firstViveWandDetected) {
  97470. firstViveWandDetected = true;
  97471. _this.controllers[i].hand = "left";
  97472. }
  97473. else {
  97474. _this.controllers[i].hand = "right";
  97475. }
  97476. }
  97477. }
  97478. //did we find enough controllers? Great! let the developer know.
  97479. if (_this.controllers.length >= 2) {
  97480. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  97481. }
  97482. }
  97483. }
  97484. });
  97485. };
  97486. return WebVRFreeCamera;
  97487. }(BABYLON.FreeCamera));
  97488. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  97489. })(BABYLON || (BABYLON = {}));
  97490. //# sourceMappingURL=babylon.webVRCamera.js.map
  97491. var BABYLON;
  97492. (function (BABYLON) {
  97493. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  97494. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  97495. });
  97496. // We're mainly based on the logic defined into the FreeCamera code
  97497. /**
  97498. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  97499. * being tilted forward or back and left or right.
  97500. */
  97501. var DeviceOrientationCamera = /** @class */ (function (_super) {
  97502. __extends(DeviceOrientationCamera, _super);
  97503. /**
  97504. * Creates a new device orientation camera
  97505. * @param name The name of the camera
  97506. * @param position The start position camera
  97507. * @param scene The scene the camera belongs to
  97508. */
  97509. function DeviceOrientationCamera(name, position, scene) {
  97510. var _this = _super.call(this, name, position, scene) || this;
  97511. _this._quaternionCache = new BABYLON.Quaternion();
  97512. _this.inputs.addDeviceOrientation();
  97513. return _this;
  97514. }
  97515. /**
  97516. * Gets the current instance class name ("DeviceOrientationCamera").
  97517. * This helps avoiding instanceof at run time.
  97518. * @returns the class name
  97519. */
  97520. DeviceOrientationCamera.prototype.getClassName = function () {
  97521. return "DeviceOrientationCamera";
  97522. };
  97523. /**
  97524. * @hidden
  97525. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  97526. */
  97527. DeviceOrientationCamera.prototype._checkInputs = function () {
  97528. _super.prototype._checkInputs.call(this);
  97529. this._quaternionCache.copyFrom(this.rotationQuaternion);
  97530. if (this._initialQuaternion) {
  97531. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  97532. }
  97533. };
  97534. /**
  97535. * Reset the camera to its default orientation on the specified axis only.
  97536. * @param axis The axis to reset
  97537. */
  97538. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  97539. var _this = this;
  97540. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  97541. //can only work if this camera has a rotation quaternion already.
  97542. if (!this.rotationQuaternion)
  97543. return;
  97544. if (!this._initialQuaternion) {
  97545. this._initialQuaternion = new BABYLON.Quaternion();
  97546. }
  97547. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  97548. ['x', 'y', 'z'].forEach(function (axisName) {
  97549. if (!axis[axisName]) {
  97550. _this._initialQuaternion[axisName] = 0;
  97551. }
  97552. else {
  97553. _this._initialQuaternion[axisName] *= -1;
  97554. }
  97555. });
  97556. this._initialQuaternion.normalize();
  97557. //force rotation update
  97558. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  97559. };
  97560. return DeviceOrientationCamera;
  97561. }(BABYLON.FreeCamera));
  97562. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  97563. })(BABYLON || (BABYLON = {}));
  97564. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  97565. var BABYLON;
  97566. (function (BABYLON) {
  97567. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  97568. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  97569. });
  97570. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  97571. __extends(VRDeviceOrientationFreeCamera, _super);
  97572. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  97573. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97574. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97575. var _this = _super.call(this, name, position, scene) || this;
  97576. vrCameraMetrics.compensateDistortion = compensateDistortion;
  97577. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  97578. return _this;
  97579. }
  97580. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  97581. return "VRDeviceOrientationFreeCamera";
  97582. };
  97583. return VRDeviceOrientationFreeCamera;
  97584. }(BABYLON.DeviceOrientationCamera));
  97585. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  97586. })(BABYLON || (BABYLON = {}));
  97587. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  97588. var BABYLON;
  97589. (function (BABYLON) {
  97590. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  97591. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  97592. });
  97593. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  97594. __extends(VRDeviceOrientationArcRotateCamera, _super);
  97595. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  97596. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97597. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97598. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  97599. vrCameraMetrics.compensateDistortion = compensateDistortion;
  97600. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  97601. _this.inputs.addVRDeviceOrientation();
  97602. return _this;
  97603. }
  97604. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  97605. return "VRDeviceOrientationArcRotateCamera";
  97606. };
  97607. return VRDeviceOrientationArcRotateCamera;
  97608. }(BABYLON.ArcRotateCamera));
  97609. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  97610. })(BABYLON || (BABYLON = {}));
  97611. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  97612. var BABYLON;
  97613. (function (BABYLON) {
  97614. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  97615. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  97616. });
  97617. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  97618. __extends(VRDeviceOrientationGamepadCamera, _super);
  97619. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  97620. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97621. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97622. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  97623. _this.inputs.addGamepad();
  97624. return _this;
  97625. }
  97626. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  97627. return "VRDeviceOrientationGamepadCamera";
  97628. };
  97629. return VRDeviceOrientationGamepadCamera;
  97630. }(BABYLON.VRDeviceOrientationFreeCamera));
  97631. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  97632. })(BABYLON || (BABYLON = {}));
  97633. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  97634. var BABYLON;
  97635. (function (BABYLON) {
  97636. var VRExperienceHelperGazer = /** @class */ (function () {
  97637. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  97638. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  97639. this.scene = scene;
  97640. /** @hidden */
  97641. this._pointerDownOnMeshAsked = false;
  97642. /** @hidden */
  97643. this._isActionableMesh = false;
  97644. /** @hidden */
  97645. this._teleportationRequestInitiated = false;
  97646. /** @hidden */
  97647. this._teleportationBackRequestInitiated = false;
  97648. /** @hidden */
  97649. this._rotationRightAsked = false;
  97650. /** @hidden */
  97651. this._rotationLeftAsked = false;
  97652. /** @hidden */
  97653. this._dpadPressed = true;
  97654. /** @hidden */
  97655. this._activePointer = false;
  97656. this._id = VRExperienceHelperGazer._idCounter++;
  97657. // Gaze tracker
  97658. if (!gazeTrackerToClone) {
  97659. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  97660. this._gazeTracker.bakeCurrentTransformIntoVertices();
  97661. this._gazeTracker.isPickable = false;
  97662. this._gazeTracker.isVisible = false;
  97663. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  97664. targetMat.specularColor = BABYLON.Color3.Black();
  97665. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  97666. targetMat.backFaceCulling = false;
  97667. this._gazeTracker.material = targetMat;
  97668. }
  97669. else {
  97670. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  97671. }
  97672. }
  97673. /** @hidden */
  97674. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  97675. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  97676. };
  97677. /** @hidden */
  97678. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  97679. this._pointerDownOnMeshAsked = true;
  97680. if (this._currentHit) {
  97681. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  97682. }
  97683. };
  97684. /** @hidden */
  97685. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  97686. if (this._currentHit) {
  97687. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  97688. }
  97689. this._pointerDownOnMeshAsked = false;
  97690. };
  97691. /** @hidden */
  97692. VRExperienceHelperGazer.prototype._activatePointer = function () {
  97693. this._activePointer = true;
  97694. };
  97695. /** @hidden */
  97696. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  97697. this._activePointer = false;
  97698. };
  97699. /** @hidden */
  97700. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  97701. if (distance === void 0) { distance = 100; }
  97702. };
  97703. VRExperienceHelperGazer.prototype.dispose = function () {
  97704. this._interactionsEnabled = false;
  97705. this._teleportationEnabled = false;
  97706. if (this._gazeTracker) {
  97707. this._gazeTracker.dispose();
  97708. }
  97709. };
  97710. VRExperienceHelperGazer._idCounter = 0;
  97711. return VRExperienceHelperGazer;
  97712. }());
  97713. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  97714. __extends(VRExperienceHelperControllerGazer, _super);
  97715. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  97716. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  97717. _this.webVRController = webVRController;
  97718. // Laser pointer
  97719. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  97720. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  97721. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  97722. laserPointerMaterial.alpha = 0.6;
  97723. _this._laserPointer.material = laserPointerMaterial;
  97724. _this._laserPointer.rotation.x = Math.PI / 2;
  97725. _this._laserPointer.position.z = -0.5;
  97726. _this._laserPointer.isVisible = false;
  97727. _this._laserPointer.isPickable = false;
  97728. if (!webVRController.mesh) {
  97729. // Create an empty mesh that is used prior to loading the high quality model
  97730. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  97731. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  97732. preloadPointerPose.rotation.x = -0.7;
  97733. preloadMesh.addChild(preloadPointerPose);
  97734. webVRController.attachToMesh(preloadMesh);
  97735. }
  97736. _this._setLaserPointerParent(webVRController.mesh);
  97737. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  97738. _this._setLaserPointerParent(mesh);
  97739. });
  97740. return _this;
  97741. }
  97742. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  97743. return this.webVRController.getForwardRay(length);
  97744. };
  97745. /** @hidden */
  97746. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  97747. _super.prototype._activatePointer.call(this);
  97748. this._laserPointer.isVisible = true;
  97749. };
  97750. /** @hidden */
  97751. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  97752. _super.prototype._deactivatePointer.call(this);
  97753. this._laserPointer.isVisible = false;
  97754. };
  97755. /** @hidden */
  97756. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  97757. this._laserPointer.material.emissiveColor = color;
  97758. };
  97759. /** @hidden */
  97760. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  97761. var makeNotPick = function (root) {
  97762. root.isPickable = false;
  97763. root.getChildMeshes().forEach(function (c) {
  97764. makeNotPick(c);
  97765. });
  97766. };
  97767. makeNotPick(mesh);
  97768. var childMeshes = mesh.getChildMeshes();
  97769. this.webVRController._pointingPoseNode = null;
  97770. for (var i = 0; i < childMeshes.length; i++) {
  97771. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  97772. mesh = childMeshes[i];
  97773. this.webVRController._pointingPoseNode = mesh;
  97774. break;
  97775. }
  97776. }
  97777. this._laserPointer.parent = mesh;
  97778. };
  97779. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  97780. if (distance === void 0) { distance = 100; }
  97781. this._laserPointer.scaling.y = distance;
  97782. this._laserPointer.position.z = -distance / 2;
  97783. };
  97784. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  97785. _super.prototype.dispose.call(this);
  97786. this._laserPointer.dispose();
  97787. if (this._meshAttachedObserver) {
  97788. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  97789. }
  97790. };
  97791. return VRExperienceHelperControllerGazer;
  97792. }(VRExperienceHelperGazer));
  97793. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  97794. __extends(VRExperienceHelperCameraGazer, _super);
  97795. function VRExperienceHelperCameraGazer(getCamera, scene) {
  97796. var _this = _super.call(this, scene) || this;
  97797. _this.getCamera = getCamera;
  97798. return _this;
  97799. }
  97800. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  97801. var camera = this.getCamera();
  97802. if (camera) {
  97803. return camera.getForwardRay(length);
  97804. }
  97805. else {
  97806. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  97807. }
  97808. };
  97809. return VRExperienceHelperCameraGazer;
  97810. }(VRExperienceHelperGazer));
  97811. /**
  97812. * Helps to quickly add VR support to an existing scene.
  97813. * See http://doc.babylonjs.com/how_to/webvr_helper
  97814. */
  97815. var VRExperienceHelper = /** @class */ (function () {
  97816. /**
  97817. * Instantiates a VRExperienceHelper.
  97818. * Helps to quickly add VR support to an existing scene.
  97819. * @param scene The scene the VRExperienceHelper belongs to.
  97820. * @param webVROptions Options to modify the vr experience helper's behavior.
  97821. */
  97822. function VRExperienceHelper(scene,
  97823. /** Options to modify the vr experience helper's behavior. */
  97824. webVROptions) {
  97825. if (webVROptions === void 0) { webVROptions = {}; }
  97826. var _this = this;
  97827. this.webVROptions = webVROptions;
  97828. // Can the system support WebVR, even if a headset isn't plugged in?
  97829. this._webVRsupported = false;
  97830. // If WebVR is supported, is a headset plugged in and are we ready to present?
  97831. this._webVRready = false;
  97832. // Are we waiting for the requestPresent callback to complete?
  97833. this._webVRrequesting = false;
  97834. // Are we presenting to the headset right now? (this is the vrDevice state)
  97835. this._webVRpresenting = false;
  97836. // Are we presenting in the fullscreen fallback?
  97837. this._fullscreenVRpresenting = false;
  97838. /**
  97839. * Observable raised when entering VR.
  97840. */
  97841. this.onEnteringVRObservable = new BABYLON.Observable();
  97842. /**
  97843. * Observable raised when exiting VR.
  97844. */
  97845. this.onExitingVRObservable = new BABYLON.Observable();
  97846. /**
  97847. * Observable raised when controller mesh is loaded.
  97848. */
  97849. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  97850. this._useCustomVRButton = false;
  97851. this._teleportationRequested = false;
  97852. this._teleportActive = false;
  97853. this._floorMeshesCollection = [];
  97854. this._rotationAllowed = true;
  97855. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  97856. this._isDefaultTeleportationTarget = true;
  97857. this._teleportationFillColor = "#444444";
  97858. this._teleportationBorderColor = "#FFFFFF";
  97859. this._rotationAngle = 0;
  97860. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  97861. this._padSensibilityUp = 0.65;
  97862. this._padSensibilityDown = 0.35;
  97863. this._leftController = null;
  97864. this._rightController = null;
  97865. /**
  97866. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  97867. */
  97868. this.onNewMeshSelected = new BABYLON.Observable();
  97869. /**
  97870. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  97871. */
  97872. this.onNewMeshPicked = new BABYLON.Observable();
  97873. /**
  97874. * Observable raised before camera teleportation
  97875. */
  97876. this.onBeforeCameraTeleport = new BABYLON.Observable();
  97877. /**
  97878. * Observable raised after camera teleportation
  97879. */
  97880. this.onAfterCameraTeleport = new BABYLON.Observable();
  97881. /**
  97882. * Observable raised when current selected mesh gets unselected
  97883. */
  97884. this.onSelectedMeshUnselected = new BABYLON.Observable();
  97885. /**
  97886. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  97887. */
  97888. this.teleportationEnabled = true;
  97889. this._teleportationInitialized = false;
  97890. this._interactionsEnabled = false;
  97891. this._interactionsRequested = false;
  97892. this._displayGaze = true;
  97893. this._displayLaserPointer = true;
  97894. /**
  97895. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  97896. */
  97897. this.updateGazeTrackerScale = true;
  97898. this._onResize = function () {
  97899. _this.moveButtonToBottomRight();
  97900. if (_this._fullscreenVRpresenting && _this._webVRready) {
  97901. _this.exitVR();
  97902. }
  97903. };
  97904. this._onFullscreenChange = function () {
  97905. if (document.fullscreen !== undefined) {
  97906. _this._fullscreenVRpresenting = document.fullscreen;
  97907. }
  97908. else if (document.mozFullScreen !== undefined) {
  97909. _this._fullscreenVRpresenting = document.mozFullScreen;
  97910. }
  97911. else if (document.webkitIsFullScreen !== undefined) {
  97912. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  97913. }
  97914. else if (document.msIsFullScreen !== undefined) {
  97915. _this._fullscreenVRpresenting = document.msIsFullScreen;
  97916. }
  97917. else if (document.msFullscreenElement !== undefined) {
  97918. _this._fullscreenVRpresenting = document.msFullscreenElement;
  97919. }
  97920. if (!_this._fullscreenVRpresenting && _this._canvas) {
  97921. _this.exitVR();
  97922. if (!_this._useCustomVRButton) {
  97923. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  97924. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  97925. }
  97926. }
  97927. };
  97928. this.beforeRender = function () {
  97929. if (_this._leftController && _this._leftController._activePointer) {
  97930. _this._castRayAndSelectObject(_this._leftController);
  97931. }
  97932. if (_this._rightController && _this._rightController._activePointer) {
  97933. _this._castRayAndSelectObject(_this._rightController);
  97934. }
  97935. if (_this._noControllerIsActive) {
  97936. _this._castRayAndSelectObject(_this._cameraGazer);
  97937. }
  97938. else {
  97939. _this._cameraGazer._gazeTracker.isVisible = false;
  97940. }
  97941. };
  97942. this._onNewGamepadConnected = function (gamepad) {
  97943. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  97944. if (gamepad.leftStick) {
  97945. gamepad.onleftstickchanged(function (stickValues) {
  97946. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  97947. // Listening to classic/xbox gamepad only if no VR controller is active
  97948. if ((!_this._leftController && !_this._rightController) ||
  97949. ((_this._leftController && !_this._leftController._activePointer) &&
  97950. (_this._rightController && !_this._rightController._activePointer))) {
  97951. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  97952. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  97953. }
  97954. }
  97955. });
  97956. }
  97957. if (gamepad.rightStick) {
  97958. gamepad.onrightstickchanged(function (stickValues) {
  97959. if (_this._teleportationInitialized) {
  97960. _this._checkRotate(stickValues, _this._cameraGazer);
  97961. }
  97962. });
  97963. }
  97964. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  97965. gamepad.onbuttondown(function (buttonPressed) {
  97966. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  97967. _this._cameraGazer._selectionPointerDown();
  97968. }
  97969. });
  97970. gamepad.onbuttonup(function (buttonPressed) {
  97971. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  97972. _this._cameraGazer._selectionPointerUp();
  97973. }
  97974. });
  97975. }
  97976. }
  97977. else {
  97978. var webVRController = gamepad;
  97979. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  97980. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  97981. _this._rightController = controller;
  97982. }
  97983. else {
  97984. _this._leftController = controller;
  97985. }
  97986. _this._tryEnableInteractionOnController(controller);
  97987. }
  97988. };
  97989. // 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
  97990. this._tryEnableInteractionOnController = function (controller) {
  97991. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  97992. _this._enableInteractionOnController(controller);
  97993. }
  97994. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  97995. _this._enableTeleportationOnController(controller);
  97996. }
  97997. };
  97998. this._onNewGamepadDisconnected = function (gamepad) {
  97999. if (gamepad instanceof BABYLON.WebVRController) {
  98000. if (gamepad.hand === "left" && _this._leftController != null) {
  98001. _this._leftController.dispose();
  98002. _this._leftController = null;
  98003. }
  98004. if (gamepad.hand === "right" && _this._rightController != null) {
  98005. _this._rightController.dispose();
  98006. _this._rightController = null;
  98007. }
  98008. }
  98009. };
  98010. this._workingVector = BABYLON.Vector3.Zero();
  98011. this._workingQuaternion = BABYLON.Quaternion.Identity();
  98012. this._workingMatrix = BABYLON.Matrix.Identity();
  98013. this._scene = scene;
  98014. this._canvas = scene.getEngine().getRenderingCanvas();
  98015. // Parse options
  98016. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  98017. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  98018. }
  98019. if (webVROptions.createDeviceOrientationCamera === undefined) {
  98020. webVROptions.createDeviceOrientationCamera = true;
  98021. }
  98022. if (webVROptions.laserToggle === undefined) {
  98023. webVROptions.laserToggle = true;
  98024. }
  98025. if (webVROptions.defaultHeight === undefined) {
  98026. webVROptions.defaultHeight = 1.7;
  98027. }
  98028. if (webVROptions.useCustomVRButton) {
  98029. this._useCustomVRButton = true;
  98030. if (webVROptions.customVRButton) {
  98031. this._btnVR = webVROptions.customVRButton;
  98032. }
  98033. }
  98034. if (webVROptions.rayLength) {
  98035. this._rayLength = webVROptions.rayLength;
  98036. }
  98037. this._defaultHeight = webVROptions.defaultHeight;
  98038. if (webVROptions.positionScale) {
  98039. this._rayLength *= webVROptions.positionScale;
  98040. this._defaultHeight *= webVROptions.positionScale;
  98041. }
  98042. this._hasEnteredVR = false;
  98043. // Set position
  98044. if (this._scene.activeCamera) {
  98045. this._position = this._scene.activeCamera.position.clone();
  98046. }
  98047. else {
  98048. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  98049. }
  98050. // Set non-vr camera
  98051. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  98052. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  98053. // Copy data from existing camera
  98054. if (this._scene.activeCamera) {
  98055. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  98056. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  98057. // Set rotation from previous camera
  98058. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  98059. var targetCamera = this._scene.activeCamera;
  98060. if (targetCamera.rotationQuaternion) {
  98061. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  98062. }
  98063. else {
  98064. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  98065. }
  98066. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  98067. }
  98068. }
  98069. this._scene.activeCamera = this._deviceOrientationCamera;
  98070. if (this._canvas) {
  98071. this._scene.activeCamera.attachControl(this._canvas);
  98072. }
  98073. }
  98074. else {
  98075. this._existingCamera = this._scene.activeCamera;
  98076. }
  98077. // Create VR cameras
  98078. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  98079. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  98080. }
  98081. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  98082. this._webVRCamera.useStandingMatrix();
  98083. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  98084. // Create default button
  98085. if (!this._useCustomVRButton) {
  98086. this._btnVR = document.createElement("BUTTON");
  98087. this._btnVR.className = "babylonVRicon";
  98088. this._btnVR.id = "babylonVRiconbtn";
  98089. this._btnVR.title = "Click to switch to VR";
  98090. 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) }";
  98091. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  98092. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  98093. // css += ".babylonVRicon.vrdisplaysupported { }";
  98094. // css += ".babylonVRicon.vrdisplayready { }";
  98095. // css += ".babylonVRicon.vrdisplayrequesting { }";
  98096. var style = document.createElement('style');
  98097. style.appendChild(document.createTextNode(css));
  98098. document.getElementsByTagName('head')[0].appendChild(style);
  98099. this.moveButtonToBottomRight();
  98100. }
  98101. // VR button click event
  98102. if (this._btnVR) {
  98103. this._btnVR.addEventListener("click", function () {
  98104. if (!_this.isInVRMode) {
  98105. _this.enterVR();
  98106. }
  98107. else {
  98108. _this.exitVR();
  98109. }
  98110. });
  98111. }
  98112. // Window events
  98113. window.addEventListener("resize", this._onResize);
  98114. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  98115. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  98116. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  98117. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  98118. document.onmsfullscreenchange = this._onFullscreenChange;
  98119. // Display vr button when headset is connected
  98120. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  98121. this.displayVRButton();
  98122. }
  98123. else {
  98124. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  98125. if (e.vrDisplay) {
  98126. _this.displayVRButton();
  98127. }
  98128. });
  98129. }
  98130. // Exiting VR mode using 'ESC' key on desktop
  98131. this._onKeyDown = function (event) {
  98132. if (event.keyCode === 27 && _this.isInVRMode) {
  98133. _this.exitVR();
  98134. }
  98135. };
  98136. document.addEventListener("keydown", this._onKeyDown);
  98137. // Exiting VR mode double tapping the touch screen
  98138. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  98139. if (_this.isInVRMode) {
  98140. _this.exitVR();
  98141. if (_this._fullscreenVRpresenting) {
  98142. _this._scene.getEngine().switchFullscreen(true);
  98143. }
  98144. }
  98145. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  98146. // Listen for WebVR display changes
  98147. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  98148. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  98149. this._onVRRequestPresentStart = function () {
  98150. _this._webVRrequesting = true;
  98151. _this.updateButtonVisibility();
  98152. };
  98153. this._onVRRequestPresentComplete = function (success) {
  98154. _this._webVRrequesting = false;
  98155. _this.updateButtonVisibility();
  98156. };
  98157. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  98158. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  98159. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  98160. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  98161. scene.onDisposeObservable.add(function () {
  98162. _this.dispose();
  98163. });
  98164. // Gamepad connection events
  98165. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  98166. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  98167. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  98168. this.updateButtonVisibility();
  98169. //create easing functions
  98170. this._circleEase = new BABYLON.CircleEase();
  98171. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  98172. if (this.webVROptions.floorMeshes) {
  98173. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  98174. }
  98175. }
  98176. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  98177. /** Return this.onEnteringVRObservable
  98178. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  98179. */
  98180. get: function () {
  98181. return this.onEnteringVRObservable;
  98182. },
  98183. enumerable: true,
  98184. configurable: true
  98185. });
  98186. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  98187. /** Return this.onExitingVRObservable
  98188. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  98189. */
  98190. get: function () {
  98191. return this.onExitingVRObservable;
  98192. },
  98193. enumerable: true,
  98194. configurable: true
  98195. });
  98196. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  98197. /** Return this.onControllerMeshLoadedObservable
  98198. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  98199. */
  98200. get: function () {
  98201. return this.onControllerMeshLoadedObservable;
  98202. },
  98203. enumerable: true,
  98204. configurable: true
  98205. });
  98206. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  98207. /**
  98208. * The mesh used to display where the user is going to teleport.
  98209. */
  98210. get: function () {
  98211. return this._teleportationTarget;
  98212. },
  98213. /**
  98214. * Sets the mesh to be used to display where the user is going to teleport.
  98215. */
  98216. set: function (value) {
  98217. if (value) {
  98218. value.name = "teleportationTarget";
  98219. this._isDefaultTeleportationTarget = false;
  98220. this._teleportationTarget = value;
  98221. }
  98222. },
  98223. enumerable: true,
  98224. configurable: true
  98225. });
  98226. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  98227. /**
  98228. * 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
  98229. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  98230. * See http://doc.babylonjs.com/resources/baking_transformations
  98231. */
  98232. get: function () {
  98233. return this._cameraGazer._gazeTracker;
  98234. },
  98235. set: function (value) {
  98236. if (value) {
  98237. // Dispose of existing meshes
  98238. if (this._cameraGazer._gazeTracker) {
  98239. this._cameraGazer._gazeTracker.dispose();
  98240. }
  98241. if (this._leftController && this._leftController._gazeTracker) {
  98242. this._leftController._gazeTracker.dispose();
  98243. }
  98244. if (this._rightController && this._rightController._gazeTracker) {
  98245. this._rightController._gazeTracker.dispose();
  98246. }
  98247. // Set and create gaze trackers on head and controllers
  98248. this._cameraGazer._gazeTracker = value;
  98249. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  98250. this._cameraGazer._gazeTracker.isPickable = false;
  98251. this._cameraGazer._gazeTracker.isVisible = false;
  98252. this._cameraGazer._gazeTracker.name = "gazeTracker";
  98253. if (this._leftController) {
  98254. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  98255. }
  98256. if (this._rightController) {
  98257. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  98258. }
  98259. }
  98260. },
  98261. enumerable: true,
  98262. configurable: true
  98263. });
  98264. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  98265. /**
  98266. * The gaze tracking mesh corresponding to the left controller
  98267. */
  98268. get: function () {
  98269. if (this._leftController) {
  98270. return this._leftController._gazeTracker;
  98271. }
  98272. return null;
  98273. },
  98274. enumerable: true,
  98275. configurable: true
  98276. });
  98277. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  98278. /**
  98279. * The gaze tracking mesh corresponding to the right controller
  98280. */
  98281. get: function () {
  98282. if (this._rightController) {
  98283. return this._rightController._gazeTracker;
  98284. }
  98285. return null;
  98286. },
  98287. enumerable: true,
  98288. configurable: true
  98289. });
  98290. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  98291. /**
  98292. * If the ray of the gaze should be displayed.
  98293. */
  98294. get: function () {
  98295. return this._displayGaze;
  98296. },
  98297. /**
  98298. * Sets if the ray of the gaze should be displayed.
  98299. */
  98300. set: function (value) {
  98301. this._displayGaze = value;
  98302. if (!value) {
  98303. this._cameraGazer._gazeTracker.isVisible = false;
  98304. if (this._leftController) {
  98305. this._leftController._gazeTracker.isVisible = false;
  98306. }
  98307. if (this._rightController) {
  98308. this._rightController._gazeTracker.isVisible = false;
  98309. }
  98310. }
  98311. },
  98312. enumerable: true,
  98313. configurable: true
  98314. });
  98315. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  98316. /**
  98317. * If the ray of the LaserPointer should be displayed.
  98318. */
  98319. get: function () {
  98320. return this._displayLaserPointer;
  98321. },
  98322. /**
  98323. * Sets if the ray of the LaserPointer should be displayed.
  98324. */
  98325. set: function (value) {
  98326. this._displayLaserPointer = value;
  98327. if (!value) {
  98328. if (this._rightController) {
  98329. this._rightController._deactivatePointer();
  98330. this._rightController._gazeTracker.isVisible = false;
  98331. }
  98332. if (this._leftController) {
  98333. this._leftController._deactivatePointer();
  98334. this._leftController._gazeTracker.isVisible = false;
  98335. }
  98336. }
  98337. else {
  98338. if (this._rightController) {
  98339. this._rightController._activatePointer();
  98340. }
  98341. if (this._leftController) {
  98342. this._leftController._activatePointer();
  98343. }
  98344. }
  98345. },
  98346. enumerable: true,
  98347. configurable: true
  98348. });
  98349. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  98350. /**
  98351. * The deviceOrientationCamera used as the camera when not in VR.
  98352. */
  98353. get: function () {
  98354. return this._deviceOrientationCamera;
  98355. },
  98356. enumerable: true,
  98357. configurable: true
  98358. });
  98359. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  98360. /**
  98361. * Based on the current WebVR support, returns the current VR camera used.
  98362. */
  98363. get: function () {
  98364. if (this._webVRready) {
  98365. return this._webVRCamera;
  98366. }
  98367. else {
  98368. return this._scene.activeCamera;
  98369. }
  98370. },
  98371. enumerable: true,
  98372. configurable: true
  98373. });
  98374. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  98375. /**
  98376. * The webVRCamera which is used when in VR.
  98377. */
  98378. get: function () {
  98379. return this._webVRCamera;
  98380. },
  98381. enumerable: true,
  98382. configurable: true
  98383. });
  98384. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  98385. /**
  98386. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  98387. */
  98388. get: function () {
  98389. return this._vrDeviceOrientationCamera;
  98390. },
  98391. enumerable: true,
  98392. configurable: true
  98393. });
  98394. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  98395. get: function () {
  98396. var result = this._cameraGazer._teleportationRequestInitiated
  98397. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  98398. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  98399. return result;
  98400. },
  98401. enumerable: true,
  98402. configurable: true
  98403. });
  98404. // Raised when one of the controller has loaded successfully its associated default mesh
  98405. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  98406. if (this._leftController && this._leftController.webVRController == webVRController) {
  98407. if (webVRController.mesh) {
  98408. this._leftController._setLaserPointerParent(webVRController.mesh);
  98409. }
  98410. }
  98411. if (this._rightController && this._rightController.webVRController == webVRController) {
  98412. if (webVRController.mesh) {
  98413. this._rightController._setLaserPointerParent(webVRController.mesh);
  98414. }
  98415. }
  98416. try {
  98417. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  98418. }
  98419. catch (err) {
  98420. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  98421. }
  98422. };
  98423. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  98424. /**
  98425. * Gets a value indicating if we are currently in VR mode.
  98426. */
  98427. get: function () {
  98428. return this._webVRpresenting || this._fullscreenVRpresenting;
  98429. },
  98430. enumerable: true,
  98431. configurable: true
  98432. });
  98433. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  98434. var vrDisplay = this._scene.getEngine().getVRDevice();
  98435. if (vrDisplay) {
  98436. var wasPresenting = this._webVRpresenting;
  98437. this._webVRpresenting = vrDisplay.isPresenting;
  98438. if (wasPresenting && !this._webVRpresenting)
  98439. this.exitVR();
  98440. }
  98441. else {
  98442. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  98443. }
  98444. this.updateButtonVisibility();
  98445. };
  98446. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  98447. this._webVRsupported = eventArgs.vrSupported;
  98448. this._webVRready = !!eventArgs.vrDisplay;
  98449. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  98450. this.updateButtonVisibility();
  98451. };
  98452. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  98453. if (this._canvas && !this._useCustomVRButton) {
  98454. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  98455. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  98456. }
  98457. };
  98458. VRExperienceHelper.prototype.displayVRButton = function () {
  98459. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  98460. document.body.appendChild(this._btnVR);
  98461. this._btnVRDisplayed = true;
  98462. }
  98463. };
  98464. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  98465. if (!this._btnVR || this._useCustomVRButton) {
  98466. return;
  98467. }
  98468. this._btnVR.className = "babylonVRicon";
  98469. if (this.isInVRMode) {
  98470. this._btnVR.className += " vrdisplaypresenting";
  98471. }
  98472. else {
  98473. if (this._webVRready)
  98474. this._btnVR.className += " vrdisplayready";
  98475. if (this._webVRsupported)
  98476. this._btnVR.className += " vrdisplaysupported";
  98477. if (this._webVRrequesting)
  98478. this._btnVR.className += " vrdisplayrequesting";
  98479. }
  98480. };
  98481. /**
  98482. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  98483. * Otherwise, will use the fullscreen API.
  98484. */
  98485. VRExperienceHelper.prototype.enterVR = function () {
  98486. if (this.onEnteringVRObservable) {
  98487. try {
  98488. this.onEnteringVRObservable.notifyObservers(this);
  98489. }
  98490. catch (err) {
  98491. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  98492. }
  98493. }
  98494. if (this._scene.activeCamera) {
  98495. this._position = this._scene.activeCamera.position.clone();
  98496. // make sure that we return to the last active camera
  98497. this._existingCamera = this._scene.activeCamera;
  98498. }
  98499. if (this._webVRrequesting)
  98500. return;
  98501. // If WebVR is supported and a headset is connected
  98502. if (this._webVRready) {
  98503. if (!this._webVRpresenting) {
  98504. this._webVRCamera.position = this._position;
  98505. this._scene.activeCamera = this._webVRCamera;
  98506. }
  98507. }
  98508. else if (this._vrDeviceOrientationCamera) {
  98509. this._vrDeviceOrientationCamera.position = this._position;
  98510. if (this._scene.activeCamera) {
  98511. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  98512. }
  98513. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  98514. this._scene.getEngine().switchFullscreen(true);
  98515. this.updateButtonVisibility();
  98516. }
  98517. if (this._scene.activeCamera && this._canvas) {
  98518. this._scene.activeCamera.attachControl(this._canvas);
  98519. }
  98520. if (this._interactionsEnabled) {
  98521. this._scene.registerBeforeRender(this.beforeRender);
  98522. }
  98523. this._hasEnteredVR = true;
  98524. };
  98525. /**
  98526. * Attempt to exit VR, or fullscreen.
  98527. */
  98528. VRExperienceHelper.prototype.exitVR = function () {
  98529. if (this._hasEnteredVR) {
  98530. if (this.onExitingVRObservable) {
  98531. try {
  98532. this.onExitingVRObservable.notifyObservers(this);
  98533. }
  98534. catch (err) {
  98535. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  98536. }
  98537. }
  98538. if (this._webVRpresenting) {
  98539. this._scene.getEngine().disableVR();
  98540. }
  98541. if (this._scene.activeCamera) {
  98542. this._position = this._scene.activeCamera.position.clone();
  98543. }
  98544. if (this._deviceOrientationCamera) {
  98545. this._deviceOrientationCamera.position = this._position;
  98546. this._scene.activeCamera = this._deviceOrientationCamera;
  98547. if (this._canvas) {
  98548. this._scene.activeCamera.attachControl(this._canvas);
  98549. }
  98550. }
  98551. else if (this._existingCamera) {
  98552. this._existingCamera.position = this._position;
  98553. this._scene.activeCamera = this._existingCamera;
  98554. }
  98555. this.updateButtonVisibility();
  98556. if (this._interactionsEnabled) {
  98557. this._scene.unregisterBeforeRender(this.beforeRender);
  98558. this._cameraGazer._gazeTracker.isVisible = false;
  98559. if (this._leftController) {
  98560. this._leftController._gazeTracker.isVisible = false;
  98561. }
  98562. if (this._rightController) {
  98563. this._rightController._gazeTracker.isVisible = false;
  98564. }
  98565. }
  98566. // resize to update width and height when exiting vr exits fullscreen
  98567. this._scene.getEngine().resize();
  98568. this._hasEnteredVR = false;
  98569. }
  98570. };
  98571. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  98572. /**
  98573. * The position of the vr experience helper.
  98574. */
  98575. get: function () {
  98576. return this._position;
  98577. },
  98578. /**
  98579. * Sets the position of the vr experience helper.
  98580. */
  98581. set: function (value) {
  98582. this._position = value;
  98583. if (this._scene.activeCamera) {
  98584. this._scene.activeCamera.position = value;
  98585. }
  98586. },
  98587. enumerable: true,
  98588. configurable: true
  98589. });
  98590. /**
  98591. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  98592. */
  98593. VRExperienceHelper.prototype.enableInteractions = function () {
  98594. var _this = this;
  98595. if (!this._interactionsEnabled) {
  98596. this._interactionsRequested = true;
  98597. if (this._leftController) {
  98598. this._enableInteractionOnController(this._leftController);
  98599. }
  98600. if (this._rightController) {
  98601. this._enableInteractionOnController(this._rightController);
  98602. }
  98603. this.raySelectionPredicate = function (mesh) {
  98604. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  98605. };
  98606. this.meshSelectionPredicate = function (mesh) {
  98607. return true;
  98608. };
  98609. this._raySelectionPredicate = function (mesh) {
  98610. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  98611. && mesh.name.indexOf("teleportationTarget") === -1
  98612. && mesh.name.indexOf("torusTeleportation") === -1)) {
  98613. return _this.raySelectionPredicate(mesh);
  98614. }
  98615. return false;
  98616. };
  98617. this._interactionsEnabled = true;
  98618. }
  98619. };
  98620. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  98621. get: function () {
  98622. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  98623. },
  98624. enumerable: true,
  98625. configurable: true
  98626. });
  98627. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  98628. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  98629. if (this._floorMeshesCollection[i].id === mesh.id) {
  98630. return true;
  98631. }
  98632. }
  98633. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  98634. return true;
  98635. }
  98636. return false;
  98637. };
  98638. /**
  98639. * Adds a floor mesh to be used for teleportation.
  98640. * @param floorMesh the mesh to be used for teleportation.
  98641. */
  98642. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  98643. if (!this._floorMeshesCollection) {
  98644. return;
  98645. }
  98646. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  98647. return;
  98648. }
  98649. this._floorMeshesCollection.push(floorMesh);
  98650. };
  98651. /**
  98652. * Removes a floor mesh from being used for teleportation.
  98653. * @param floorMesh the mesh to be removed.
  98654. */
  98655. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  98656. if (!this._floorMeshesCollection) {
  98657. return;
  98658. }
  98659. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  98660. if (meshIndex !== -1) {
  98661. this._floorMeshesCollection.splice(meshIndex, 1);
  98662. }
  98663. };
  98664. /**
  98665. * Enables interactions and teleportation using the VR controllers and gaze.
  98666. * @param vrTeleportationOptions options to modify teleportation behavior.
  98667. */
  98668. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  98669. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  98670. if (!this._teleportationInitialized) {
  98671. this._teleportationRequested = true;
  98672. this.enableInteractions();
  98673. if (vrTeleportationOptions.floorMeshName) {
  98674. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  98675. }
  98676. if (vrTeleportationOptions.floorMeshes) {
  98677. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  98678. }
  98679. if (this._leftController != null) {
  98680. this._enableTeleportationOnController(this._leftController);
  98681. }
  98682. if (this._rightController != null) {
  98683. this._enableTeleportationOnController(this._rightController);
  98684. }
  98685. // Creates an image processing post process for the vignette not relying
  98686. // on the main scene configuration for image processing to reduce setup and spaces
  98687. // (gamma/linear) conflicts.
  98688. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  98689. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  98690. imageProcessingConfiguration.vignetteEnabled = true;
  98691. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  98692. this._webVRCamera.detachPostProcess(this._postProcessMove);
  98693. this._teleportationInitialized = true;
  98694. if (this._isDefaultTeleportationTarget) {
  98695. this._createTeleportationCircles();
  98696. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  98697. }
  98698. }
  98699. };
  98700. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  98701. var _this = this;
  98702. var controllerMesh = controller.webVRController.mesh;
  98703. if (controllerMesh) {
  98704. controller._interactionsEnabled = true;
  98705. controller._activatePointer();
  98706. if (this.webVROptions.laserToggle) {
  98707. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  98708. // Enabling / disabling laserPointer
  98709. if (_this._displayLaserPointer && stateObject.value === 1) {
  98710. if (controller._activePointer) {
  98711. controller._deactivatePointer();
  98712. }
  98713. else {
  98714. controller._activatePointer();
  98715. }
  98716. if (_this.displayGaze) {
  98717. controller._gazeTracker.isVisible = controller._activePointer;
  98718. }
  98719. }
  98720. });
  98721. }
  98722. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  98723. var gazer = controller;
  98724. if (_this._noControllerIsActive) {
  98725. gazer = _this._cameraGazer;
  98726. }
  98727. if (!gazer._pointerDownOnMeshAsked) {
  98728. if (stateObject.value > _this._padSensibilityUp) {
  98729. gazer._selectionPointerDown();
  98730. }
  98731. }
  98732. else if (stateObject.value < _this._padSensibilityDown) {
  98733. gazer._selectionPointerUp();
  98734. }
  98735. });
  98736. }
  98737. };
  98738. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  98739. // Dont teleport if another gaze already requested teleportation
  98740. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  98741. return;
  98742. }
  98743. if (!gazer._teleportationRequestInitiated) {
  98744. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  98745. gazer._activatePointer();
  98746. gazer._teleportationRequestInitiated = true;
  98747. }
  98748. }
  98749. else {
  98750. // Listening to the proper controller values changes to confirm teleportation
  98751. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  98752. if (this._teleportActive) {
  98753. this.teleportCamera(this._haloCenter);
  98754. }
  98755. gazer._teleportationRequestInitiated = false;
  98756. }
  98757. }
  98758. };
  98759. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  98760. // Only rotate when user is not currently selecting a teleportation location
  98761. if (gazer._teleportationRequestInitiated) {
  98762. return;
  98763. }
  98764. if (!gazer._rotationLeftAsked) {
  98765. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  98766. gazer._rotationLeftAsked = true;
  98767. if (this._rotationAllowed) {
  98768. this._rotateCamera(false);
  98769. }
  98770. }
  98771. }
  98772. else {
  98773. if (stateObject.x > -this._padSensibilityDown) {
  98774. gazer._rotationLeftAsked = false;
  98775. }
  98776. }
  98777. if (!gazer._rotationRightAsked) {
  98778. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  98779. gazer._rotationRightAsked = true;
  98780. if (this._rotationAllowed) {
  98781. this._rotateCamera(true);
  98782. }
  98783. }
  98784. }
  98785. else {
  98786. if (stateObject.x < this._padSensibilityDown) {
  98787. gazer._rotationRightAsked = false;
  98788. }
  98789. }
  98790. };
  98791. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  98792. // Only teleport backwards when user is not currently selecting a teleportation location
  98793. if (gazer._teleportationRequestInitiated) {
  98794. return;
  98795. }
  98796. // Teleport backwards
  98797. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  98798. if (!gazer._teleportationBackRequestInitiated) {
  98799. if (!this.currentVRCamera) {
  98800. return;
  98801. }
  98802. // Get rotation and position of the current camera
  98803. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  98804. var position = this.currentVRCamera.position;
  98805. // If the camera has device position, use that instead
  98806. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  98807. rotation = this.currentVRCamera.deviceRotationQuaternion;
  98808. position = this.currentVRCamera.devicePosition;
  98809. }
  98810. // Get matrix with only the y rotation of the device rotation
  98811. rotation.toEulerAnglesToRef(this._workingVector);
  98812. this._workingVector.z = 0;
  98813. this._workingVector.x = 0;
  98814. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  98815. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  98816. // Rotate backwards ray by device rotation to cast at the ground behind the user
  98817. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  98818. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  98819. var ray = new BABYLON.Ray(position, this._workingVector);
  98820. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  98821. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  98822. this.teleportCamera(hit.pickedPoint);
  98823. }
  98824. gazer._teleportationBackRequestInitiated = true;
  98825. }
  98826. }
  98827. else {
  98828. gazer._teleportationBackRequestInitiated = false;
  98829. }
  98830. };
  98831. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  98832. var _this = this;
  98833. var controllerMesh = controller.webVRController.mesh;
  98834. if (controllerMesh) {
  98835. if (!controller._interactionsEnabled) {
  98836. this._enableInteractionOnController(controller);
  98837. }
  98838. controller._interactionsEnabled = true;
  98839. controller._teleportationEnabled = true;
  98840. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  98841. controller._dpadPressed = false;
  98842. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  98843. controller._dpadPressed = stateObject.pressed;
  98844. if (!controller._dpadPressed) {
  98845. controller._rotationLeftAsked = false;
  98846. controller._rotationRightAsked = false;
  98847. controller._teleportationBackRequestInitiated = false;
  98848. }
  98849. });
  98850. }
  98851. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  98852. if (_this.teleportationEnabled) {
  98853. _this._checkTeleportBackwards(stateObject, controller);
  98854. _this._checkTeleportWithRay(stateObject, controller);
  98855. }
  98856. _this._checkRotate(stateObject, controller);
  98857. });
  98858. }
  98859. };
  98860. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  98861. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  98862. this._teleportationTarget.isPickable = false;
  98863. var length = 512;
  98864. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  98865. dynamicTexture.hasAlpha = true;
  98866. var context = dynamicTexture.getContext();
  98867. var centerX = length / 2;
  98868. var centerY = length / 2;
  98869. var radius = 200;
  98870. context.beginPath();
  98871. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  98872. context.fillStyle = this._teleportationFillColor;
  98873. context.fill();
  98874. context.lineWidth = 10;
  98875. context.strokeStyle = this._teleportationBorderColor;
  98876. context.stroke();
  98877. context.closePath();
  98878. dynamicTexture.update();
  98879. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  98880. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  98881. this._teleportationTarget.material = teleportationCircleMaterial;
  98882. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  98883. torus.isPickable = false;
  98884. torus.parent = this._teleportationTarget;
  98885. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  98886. var keys = [];
  98887. keys.push({
  98888. frame: 0,
  98889. value: 0
  98890. });
  98891. keys.push({
  98892. frame: 30,
  98893. value: 0.4
  98894. });
  98895. keys.push({
  98896. frame: 60,
  98897. value: 0
  98898. });
  98899. animationInnerCircle.setKeys(keys);
  98900. var easingFunction = new BABYLON.SineEase();
  98901. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  98902. animationInnerCircle.setEasingFunction(easingFunction);
  98903. torus.animations = [];
  98904. torus.animations.push(animationInnerCircle);
  98905. this._scene.beginAnimation(torus, 0, 60, true);
  98906. this._hideTeleportationTarget();
  98907. };
  98908. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  98909. this._teleportActive = true;
  98910. if (this._teleportationInitialized) {
  98911. this._teleportationTarget.isVisible = true;
  98912. if (this._isDefaultTeleportationTarget) {
  98913. this._teleportationTarget.getChildren()[0].isVisible = true;
  98914. }
  98915. }
  98916. };
  98917. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  98918. this._teleportActive = false;
  98919. if (this._teleportationInitialized) {
  98920. this._teleportationTarget.isVisible = false;
  98921. if (this._isDefaultTeleportationTarget) {
  98922. this._teleportationTarget.getChildren()[0].isVisible = false;
  98923. }
  98924. }
  98925. };
  98926. VRExperienceHelper.prototype._rotateCamera = function (right) {
  98927. var _this = this;
  98928. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  98929. return;
  98930. }
  98931. if (right) {
  98932. this._rotationAngle++;
  98933. }
  98934. else {
  98935. this._rotationAngle--;
  98936. }
  98937. this.currentVRCamera.animations = [];
  98938. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  98939. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98940. var animationRotationKeys = [];
  98941. animationRotationKeys.push({
  98942. frame: 0,
  98943. value: this.currentVRCamera.rotationQuaternion
  98944. });
  98945. animationRotationKeys.push({
  98946. frame: 6,
  98947. value: target
  98948. });
  98949. animationRotation.setKeys(animationRotationKeys);
  98950. animationRotation.setEasingFunction(this._circleEase);
  98951. this.currentVRCamera.animations.push(animationRotation);
  98952. this._postProcessMove.animations = [];
  98953. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98954. var vignetteWeightKeys = [];
  98955. vignetteWeightKeys.push({
  98956. frame: 0,
  98957. value: 0
  98958. });
  98959. vignetteWeightKeys.push({
  98960. frame: 3,
  98961. value: 4
  98962. });
  98963. vignetteWeightKeys.push({
  98964. frame: 6,
  98965. value: 0
  98966. });
  98967. animationPP.setKeys(vignetteWeightKeys);
  98968. animationPP.setEasingFunction(this._circleEase);
  98969. this._postProcessMove.animations.push(animationPP);
  98970. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98971. var vignetteStretchKeys = [];
  98972. vignetteStretchKeys.push({
  98973. frame: 0,
  98974. value: 0
  98975. });
  98976. vignetteStretchKeys.push({
  98977. frame: 3,
  98978. value: 10
  98979. });
  98980. vignetteStretchKeys.push({
  98981. frame: 6,
  98982. value: 0
  98983. });
  98984. animationPP2.setKeys(vignetteStretchKeys);
  98985. animationPP2.setEasingFunction(this._circleEase);
  98986. this._postProcessMove.animations.push(animationPP2);
  98987. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  98988. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  98989. this._postProcessMove.samples = 4;
  98990. this._webVRCamera.attachPostProcess(this._postProcessMove);
  98991. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  98992. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  98993. });
  98994. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  98995. };
  98996. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  98997. if (hit.pickedPoint) {
  98998. if (gazer._teleportationRequestInitiated) {
  98999. this._displayTeleportationTarget();
  99000. this._haloCenter.copyFrom(hit.pickedPoint);
  99001. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  99002. }
  99003. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  99004. if (pickNormal) {
  99005. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  99006. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  99007. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  99008. }
  99009. this._teleportationTarget.position.y += 0.1;
  99010. }
  99011. };
  99012. /**
  99013. * Teleports the users feet to the desired location
  99014. * @param location The location where the user's feet should be placed
  99015. */
  99016. VRExperienceHelper.prototype.teleportCamera = function (location) {
  99017. var _this = this;
  99018. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  99019. return;
  99020. }
  99021. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  99022. // offset of the headset from the anchor.
  99023. if (this.webVRCamera.leftCamera) {
  99024. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  99025. this._workingVector.subtractInPlace(this.webVRCamera.position);
  99026. location.subtractToRef(this._workingVector, this._workingVector);
  99027. }
  99028. else {
  99029. this._workingVector.copyFrom(location);
  99030. }
  99031. // Add height to account for user's height offset
  99032. if (this.isInVRMode) {
  99033. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  99034. }
  99035. else {
  99036. this._workingVector.y += this._defaultHeight;
  99037. }
  99038. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  99039. // Create animation from the camera's position to the new location
  99040. this.currentVRCamera.animations = [];
  99041. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99042. var animationCameraTeleportationKeys = [{
  99043. frame: 0,
  99044. value: this.currentVRCamera.position
  99045. },
  99046. {
  99047. frame: 11,
  99048. value: this._workingVector
  99049. }
  99050. ];
  99051. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  99052. animationCameraTeleportation.setEasingFunction(this._circleEase);
  99053. this.currentVRCamera.animations.push(animationCameraTeleportation);
  99054. this._postProcessMove.animations = [];
  99055. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99056. var vignetteWeightKeys = [];
  99057. vignetteWeightKeys.push({
  99058. frame: 0,
  99059. value: 0
  99060. });
  99061. vignetteWeightKeys.push({
  99062. frame: 5,
  99063. value: 8
  99064. });
  99065. vignetteWeightKeys.push({
  99066. frame: 11,
  99067. value: 0
  99068. });
  99069. animationPP.setKeys(vignetteWeightKeys);
  99070. this._postProcessMove.animations.push(animationPP);
  99071. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99072. var vignetteStretchKeys = [];
  99073. vignetteStretchKeys.push({
  99074. frame: 0,
  99075. value: 0
  99076. });
  99077. vignetteStretchKeys.push({
  99078. frame: 5,
  99079. value: 10
  99080. });
  99081. vignetteStretchKeys.push({
  99082. frame: 11,
  99083. value: 0
  99084. });
  99085. animationPP2.setKeys(vignetteStretchKeys);
  99086. this._postProcessMove.animations.push(animationPP2);
  99087. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  99088. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  99089. this._webVRCamera.attachPostProcess(this._postProcessMove);
  99090. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  99091. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  99092. });
  99093. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  99094. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  99095. });
  99096. this._hideTeleportationTarget();
  99097. };
  99098. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  99099. if (normal) {
  99100. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  99101. if (angle < Math.PI / 2) {
  99102. normal.scaleInPlace(-1);
  99103. }
  99104. }
  99105. return normal;
  99106. };
  99107. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  99108. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  99109. return;
  99110. }
  99111. var ray = gazer._getForwardRay(this._rayLength);
  99112. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  99113. if (hit) {
  99114. // Populate the contrllers mesh that can be used for drag/drop
  99115. if (gazer._laserPointer) {
  99116. hit.originMesh = gazer._laserPointer.parent;
  99117. }
  99118. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  99119. }
  99120. gazer._currentHit = hit;
  99121. // Moving the gazeTracker on the mesh face targetted
  99122. if (hit && hit.pickedPoint) {
  99123. if (this._displayGaze) {
  99124. var multiplier = 1;
  99125. gazer._gazeTracker.isVisible = true;
  99126. if (gazer._isActionableMesh) {
  99127. multiplier = 3;
  99128. }
  99129. if (this.updateGazeTrackerScale) {
  99130. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  99131. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  99132. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  99133. }
  99134. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  99135. // To avoid z-fighting
  99136. var deltaFighting = 0.002;
  99137. if (pickNormal) {
  99138. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  99139. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  99140. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  99141. }
  99142. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  99143. if (gazer._gazeTracker.position.x < 0) {
  99144. gazer._gazeTracker.position.x += deltaFighting;
  99145. }
  99146. else {
  99147. gazer._gazeTracker.position.x -= deltaFighting;
  99148. }
  99149. if (gazer._gazeTracker.position.y < 0) {
  99150. gazer._gazeTracker.position.y += deltaFighting;
  99151. }
  99152. else {
  99153. gazer._gazeTracker.position.y -= deltaFighting;
  99154. }
  99155. if (gazer._gazeTracker.position.z < 0) {
  99156. gazer._gazeTracker.position.z += deltaFighting;
  99157. }
  99158. else {
  99159. gazer._gazeTracker.position.z -= deltaFighting;
  99160. }
  99161. }
  99162. // Changing the size of the laser pointer based on the distance from the targetted point
  99163. gazer._updatePointerDistance(hit.distance);
  99164. }
  99165. else {
  99166. gazer._updatePointerDistance();
  99167. gazer._gazeTracker.isVisible = false;
  99168. }
  99169. if (hit && hit.pickedMesh) {
  99170. // The object selected is the floor, we're in a teleportation scenario
  99171. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  99172. // Moving the teleportation area to this targetted point
  99173. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  99174. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  99175. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  99176. }
  99177. gazer._currentMeshSelected = null;
  99178. if (gazer._teleportationRequestInitiated) {
  99179. this._moveTeleportationSelectorTo(hit, gazer, ray);
  99180. }
  99181. return;
  99182. }
  99183. // If not, we're in a selection scenario
  99184. //this._teleportationAllowed = false;
  99185. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  99186. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  99187. this.onNewMeshPicked.notifyObservers(hit);
  99188. gazer._currentMeshSelected = hit.pickedMesh;
  99189. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  99190. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  99191. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  99192. gazer._isActionableMesh = true;
  99193. }
  99194. else {
  99195. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99196. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99197. gazer._isActionableMesh = false;
  99198. }
  99199. try {
  99200. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  99201. }
  99202. catch (err) {
  99203. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  99204. }
  99205. }
  99206. else {
  99207. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  99208. gazer._currentMeshSelected = null;
  99209. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99210. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99211. }
  99212. }
  99213. }
  99214. else {
  99215. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  99216. gazer._currentMeshSelected = null;
  99217. //this._teleportationAllowed = false;
  99218. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99219. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  99220. }
  99221. };
  99222. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  99223. if (mesh) {
  99224. this.onSelectedMeshUnselected.notifyObservers(mesh);
  99225. }
  99226. };
  99227. /**
  99228. * Sets the color of the laser ray from the vr controllers.
  99229. * @param color new color for the ray.
  99230. */
  99231. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  99232. if (this._leftController) {
  99233. this._leftController._setLaserPointerColor(color);
  99234. }
  99235. if (this._rightController) {
  99236. this._rightController._setLaserPointerColor(color);
  99237. }
  99238. };
  99239. /**
  99240. * Sets the color of the ray from the vr headsets gaze.
  99241. * @param color new color for the ray.
  99242. */
  99243. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  99244. if (!this._cameraGazer._gazeTracker.material) {
  99245. return;
  99246. }
  99247. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  99248. if (this._leftController) {
  99249. this._leftController._gazeTracker.material.emissiveColor = color;
  99250. }
  99251. if (this._rightController) {
  99252. this._rightController._gazeTracker.material.emissiveColor = color;
  99253. }
  99254. };
  99255. /**
  99256. * Exits VR and disposes of the vr experience helper
  99257. */
  99258. VRExperienceHelper.prototype.dispose = function () {
  99259. if (this.isInVRMode) {
  99260. this.exitVR();
  99261. }
  99262. if (this._postProcessMove) {
  99263. this._postProcessMove.dispose();
  99264. }
  99265. if (this._webVRCamera) {
  99266. this._webVRCamera.dispose();
  99267. }
  99268. if (this._vrDeviceOrientationCamera) {
  99269. this._vrDeviceOrientationCamera.dispose();
  99270. }
  99271. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  99272. document.body.removeChild(this._btnVR);
  99273. }
  99274. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  99275. this._deviceOrientationCamera.dispose();
  99276. }
  99277. if (this._cameraGazer) {
  99278. this._cameraGazer.dispose();
  99279. }
  99280. if (this._leftController) {
  99281. this._leftController.dispose();
  99282. }
  99283. if (this._rightController) {
  99284. this._rightController.dispose();
  99285. }
  99286. if (this._teleportationTarget) {
  99287. this._teleportationTarget.dispose();
  99288. }
  99289. this._floorMeshesCollection = [];
  99290. document.removeEventListener("keydown", this._onKeyDown);
  99291. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  99292. window.removeEventListener("resize", this._onResize);
  99293. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  99294. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  99295. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  99296. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  99297. document.onmsfullscreenchange = null;
  99298. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  99299. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  99300. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  99301. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  99302. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  99303. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  99304. this._scene.unregisterBeforeRender(this.beforeRender);
  99305. };
  99306. /**
  99307. * Gets the name of the VRExperienceHelper class
  99308. * @returns "VRExperienceHelper"
  99309. */
  99310. VRExperienceHelper.prototype.getClassName = function () {
  99311. return "VRExperienceHelper";
  99312. };
  99313. return VRExperienceHelper;
  99314. }());
  99315. BABYLON.VRExperienceHelper = VRExperienceHelper;
  99316. })(BABYLON || (BABYLON = {}));
  99317. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  99318. // Mainly based on these 2 articles :
  99319. // 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
  99320. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  99321. var BABYLON;
  99322. (function (BABYLON) {
  99323. /**
  99324. * Defines the potential axis of a Joystick
  99325. */
  99326. var JoystickAxis;
  99327. (function (JoystickAxis) {
  99328. /** X axis */
  99329. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  99330. /** Y axis */
  99331. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  99332. /** Z axis */
  99333. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  99334. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  99335. /**
  99336. * Class used to define virtual joystick (used in touch mode)
  99337. */
  99338. var VirtualJoystick = /** @class */ (function () {
  99339. /**
  99340. * Creates a new virtual joystick
  99341. * @param leftJoystick defines that the joystick is for left hand (false by default)
  99342. */
  99343. function VirtualJoystick(leftJoystick) {
  99344. var _this = this;
  99345. if (leftJoystick) {
  99346. this._leftJoystick = true;
  99347. }
  99348. else {
  99349. this._leftJoystick = false;
  99350. }
  99351. VirtualJoystick._globalJoystickIndex++;
  99352. // By default left & right arrow keys are moving the X
  99353. // and up & down keys are moving the Y
  99354. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  99355. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  99356. this.reverseLeftRight = false;
  99357. this.reverseUpDown = false;
  99358. // collections of pointers
  99359. this._touches = new BABYLON.StringDictionary();
  99360. this.deltaPosition = BABYLON.Vector3.Zero();
  99361. this._joystickSensibility = 25;
  99362. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  99363. this._onResize = function (evt) {
  99364. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  99365. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  99366. if (VirtualJoystick.vjCanvas) {
  99367. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  99368. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  99369. }
  99370. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  99371. };
  99372. // injecting a canvas element on top of the canvas 3D game
  99373. if (!VirtualJoystick.vjCanvas) {
  99374. window.addEventListener("resize", this._onResize, false);
  99375. VirtualJoystick.vjCanvas = document.createElement("canvas");
  99376. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  99377. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  99378. VirtualJoystick.vjCanvas.width = window.innerWidth;
  99379. VirtualJoystick.vjCanvas.height = window.innerHeight;
  99380. VirtualJoystick.vjCanvas.style.width = "100%";
  99381. VirtualJoystick.vjCanvas.style.height = "100%";
  99382. VirtualJoystick.vjCanvas.style.position = "absolute";
  99383. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  99384. VirtualJoystick.vjCanvas.style.top = "0px";
  99385. VirtualJoystick.vjCanvas.style.left = "0px";
  99386. VirtualJoystick.vjCanvas.style.zIndex = "5";
  99387. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  99388. // Support for jQuery PEP polyfill
  99389. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  99390. var context = VirtualJoystick.vjCanvas.getContext('2d');
  99391. if (!context) {
  99392. throw new Error("Unable to create canvas for virtual joystick");
  99393. }
  99394. VirtualJoystick.vjCanvasContext = context;
  99395. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  99396. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  99397. document.body.appendChild(VirtualJoystick.vjCanvas);
  99398. }
  99399. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  99400. this.pressed = false;
  99401. // default joystick color
  99402. this._joystickColor = "cyan";
  99403. this._joystickPointerID = -1;
  99404. // current joystick position
  99405. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  99406. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  99407. // origin joystick position
  99408. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  99409. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  99410. this._onPointerDownHandlerRef = function (evt) {
  99411. _this._onPointerDown(evt);
  99412. };
  99413. this._onPointerMoveHandlerRef = function (evt) {
  99414. _this._onPointerMove(evt);
  99415. };
  99416. this._onPointerUpHandlerRef = function (evt) {
  99417. _this._onPointerUp(evt);
  99418. };
  99419. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  99420. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  99421. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  99422. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  99423. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  99424. evt.preventDefault(); // Disables system menu
  99425. }, false);
  99426. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  99427. }
  99428. /**
  99429. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  99430. * @param newJoystickSensibility defines the new sensibility
  99431. */
  99432. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  99433. this._joystickSensibility = newJoystickSensibility;
  99434. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  99435. };
  99436. VirtualJoystick.prototype._onPointerDown = function (e) {
  99437. var positionOnScreenCondition;
  99438. e.preventDefault();
  99439. if (this._leftJoystick === true) {
  99440. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  99441. }
  99442. else {
  99443. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  99444. }
  99445. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  99446. // First contact will be dedicated to the virtual joystick
  99447. this._joystickPointerID = e.pointerId;
  99448. this._joystickPointerStartPos.x = e.clientX;
  99449. this._joystickPointerStartPos.y = e.clientY;
  99450. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  99451. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  99452. this._deltaJoystickVector.x = 0;
  99453. this._deltaJoystickVector.y = 0;
  99454. this.pressed = true;
  99455. this._touches.add(e.pointerId.toString(), e);
  99456. }
  99457. else {
  99458. // You can only trigger the action buttons with a joystick declared
  99459. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  99460. this._action();
  99461. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  99462. }
  99463. }
  99464. };
  99465. VirtualJoystick.prototype._onPointerMove = function (e) {
  99466. // If the current pointer is the one associated to the joystick (first touch contact)
  99467. if (this._joystickPointerID == e.pointerId) {
  99468. this._joystickPointerPos.x = e.clientX;
  99469. this._joystickPointerPos.y = e.clientY;
  99470. this._deltaJoystickVector = this._joystickPointerPos.clone();
  99471. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  99472. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  99473. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  99474. switch (this._axisTargetedByLeftAndRight) {
  99475. case JoystickAxis.X:
  99476. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  99477. break;
  99478. case JoystickAxis.Y:
  99479. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  99480. break;
  99481. case JoystickAxis.Z:
  99482. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  99483. break;
  99484. }
  99485. var directionUpDown = this.reverseUpDown ? 1 : -1;
  99486. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  99487. switch (this._axisTargetedByUpAndDown) {
  99488. case JoystickAxis.X:
  99489. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  99490. break;
  99491. case JoystickAxis.Y:
  99492. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  99493. break;
  99494. case JoystickAxis.Z:
  99495. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  99496. break;
  99497. }
  99498. }
  99499. else {
  99500. var data = this._touches.get(e.pointerId.toString());
  99501. if (data) {
  99502. data.x = e.clientX;
  99503. data.y = e.clientY;
  99504. }
  99505. }
  99506. };
  99507. VirtualJoystick.prototype._onPointerUp = function (e) {
  99508. if (this._joystickPointerID == e.pointerId) {
  99509. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  99510. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  99511. this._joystickPointerID = -1;
  99512. this.pressed = false;
  99513. }
  99514. else {
  99515. var touch = this._touches.get(e.pointerId.toString());
  99516. if (touch) {
  99517. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  99518. }
  99519. }
  99520. this._deltaJoystickVector.x = 0;
  99521. this._deltaJoystickVector.y = 0;
  99522. this._touches.remove(e.pointerId.toString());
  99523. };
  99524. /**
  99525. * Change the color of the virtual joystick
  99526. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  99527. */
  99528. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  99529. this._joystickColor = newColor;
  99530. };
  99531. /**
  99532. * Defines a callback to call when the joystick is touched
  99533. * @param action defines the callback
  99534. */
  99535. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  99536. this._action = action;
  99537. };
  99538. /**
  99539. * Defines which axis you'd like to control for left & right
  99540. * @param axis defines the axis to use
  99541. */
  99542. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  99543. switch (axis) {
  99544. case JoystickAxis.X:
  99545. case JoystickAxis.Y:
  99546. case JoystickAxis.Z:
  99547. this._axisTargetedByLeftAndRight = axis;
  99548. break;
  99549. default:
  99550. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  99551. break;
  99552. }
  99553. };
  99554. /**
  99555. * Defines which axis you'd like to control for up & down
  99556. * @param axis defines the axis to use
  99557. */
  99558. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  99559. switch (axis) {
  99560. case JoystickAxis.X:
  99561. case JoystickAxis.Y:
  99562. case JoystickAxis.Z:
  99563. this._axisTargetedByUpAndDown = axis;
  99564. break;
  99565. default:
  99566. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  99567. break;
  99568. }
  99569. };
  99570. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  99571. var _this = this;
  99572. if (this.pressed) {
  99573. this._touches.forEach(function (key, touch) {
  99574. if (touch.pointerId === _this._joystickPointerID) {
  99575. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  99576. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  99577. VirtualJoystick.vjCanvasContext.beginPath();
  99578. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  99579. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99580. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  99581. VirtualJoystick.vjCanvasContext.stroke();
  99582. VirtualJoystick.vjCanvasContext.closePath();
  99583. VirtualJoystick.vjCanvasContext.beginPath();
  99584. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99585. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  99586. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  99587. VirtualJoystick.vjCanvasContext.stroke();
  99588. VirtualJoystick.vjCanvasContext.closePath();
  99589. VirtualJoystick.vjCanvasContext.beginPath();
  99590. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99591. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  99592. VirtualJoystick.vjCanvasContext.stroke();
  99593. VirtualJoystick.vjCanvasContext.closePath();
  99594. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  99595. }
  99596. else {
  99597. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  99598. VirtualJoystick.vjCanvasContext.beginPath();
  99599. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  99600. VirtualJoystick.vjCanvasContext.beginPath();
  99601. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  99602. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  99603. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  99604. VirtualJoystick.vjCanvasContext.stroke();
  99605. VirtualJoystick.vjCanvasContext.closePath();
  99606. touch.prevX = touch.x;
  99607. touch.prevY = touch.y;
  99608. }
  99609. ;
  99610. });
  99611. }
  99612. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  99613. };
  99614. /**
  99615. * Release internal HTML canvas
  99616. */
  99617. VirtualJoystick.prototype.releaseCanvas = function () {
  99618. if (VirtualJoystick.vjCanvas) {
  99619. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  99620. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  99621. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  99622. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  99623. window.removeEventListener("resize", this._onResize);
  99624. document.body.removeChild(VirtualJoystick.vjCanvas);
  99625. VirtualJoystick.vjCanvas = null;
  99626. }
  99627. };
  99628. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  99629. VirtualJoystick._globalJoystickIndex = 0;
  99630. return VirtualJoystick;
  99631. }());
  99632. BABYLON.VirtualJoystick = VirtualJoystick;
  99633. })(BABYLON || (BABYLON = {}));
  99634. //# sourceMappingURL=babylon.virtualJoystick.js.map
  99635. var BABYLON;
  99636. (function (BABYLON) {
  99637. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  99638. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  99639. });
  99640. // We're mainly based on the logic defined into the FreeCamera code
  99641. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  99642. __extends(VirtualJoysticksCamera, _super);
  99643. function VirtualJoysticksCamera(name, position, scene) {
  99644. var _this = _super.call(this, name, position, scene) || this;
  99645. _this.inputs.addVirtualJoystick();
  99646. return _this;
  99647. }
  99648. VirtualJoysticksCamera.prototype.getClassName = function () {
  99649. return "VirtualJoysticksCamera";
  99650. };
  99651. return VirtualJoysticksCamera;
  99652. }(BABYLON.FreeCamera));
  99653. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  99654. })(BABYLON || (BABYLON = {}));
  99655. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  99656. var BABYLON;
  99657. (function (BABYLON) {
  99658. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  99659. function FreeCameraVirtualJoystickInput() {
  99660. }
  99661. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  99662. return this._leftjoystick;
  99663. };
  99664. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  99665. return this._rightjoystick;
  99666. };
  99667. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  99668. if (this._leftjoystick) {
  99669. var camera = this.camera;
  99670. var speed = camera._computeLocalCameraSpeed() * 50;
  99671. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  99672. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  99673. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  99674. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  99675. if (!this._leftjoystick.pressed) {
  99676. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  99677. }
  99678. if (!this._rightjoystick.pressed) {
  99679. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  99680. }
  99681. }
  99682. };
  99683. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  99684. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  99685. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  99686. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  99687. this._leftjoystick.setJoystickSensibility(0.15);
  99688. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  99689. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  99690. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  99691. this._rightjoystick.reverseUpDown = true;
  99692. this._rightjoystick.setJoystickSensibility(0.05);
  99693. this._rightjoystick.setJoystickColor("yellow");
  99694. };
  99695. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  99696. this._leftjoystick.releaseCanvas();
  99697. this._rightjoystick.releaseCanvas();
  99698. };
  99699. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  99700. return "FreeCameraVirtualJoystickInput";
  99701. };
  99702. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  99703. return "virtualJoystick";
  99704. };
  99705. return FreeCameraVirtualJoystickInput;
  99706. }());
  99707. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  99708. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  99709. })(BABYLON || (BABYLON = {}));
  99710. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  99711. var BABYLON;
  99712. (function (BABYLON) {
  99713. var SimplificationSettings = /** @class */ (function () {
  99714. function SimplificationSettings(quality, distance, optimizeMesh) {
  99715. this.quality = quality;
  99716. this.distance = distance;
  99717. this.optimizeMesh = optimizeMesh;
  99718. }
  99719. return SimplificationSettings;
  99720. }());
  99721. BABYLON.SimplificationSettings = SimplificationSettings;
  99722. var SimplificationQueue = /** @class */ (function () {
  99723. function SimplificationQueue() {
  99724. this.running = false;
  99725. this._simplificationArray = [];
  99726. }
  99727. SimplificationQueue.prototype.addTask = function (task) {
  99728. this._simplificationArray.push(task);
  99729. };
  99730. SimplificationQueue.prototype.executeNext = function () {
  99731. var task = this._simplificationArray.pop();
  99732. if (task) {
  99733. this.running = true;
  99734. this.runSimplification(task);
  99735. }
  99736. else {
  99737. this.running = false;
  99738. }
  99739. };
  99740. SimplificationQueue.prototype.runSimplification = function (task) {
  99741. var _this = this;
  99742. if (task.parallelProcessing) {
  99743. //parallel simplifier
  99744. task.settings.forEach(function (setting) {
  99745. var simplifier = _this.getSimplifier(task);
  99746. simplifier.simplify(setting, function (newMesh) {
  99747. task.mesh.addLODLevel(setting.distance, newMesh);
  99748. newMesh.isVisible = true;
  99749. //check if it is the last
  99750. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  99751. //all done, run the success callback.
  99752. task.successCallback();
  99753. }
  99754. _this.executeNext();
  99755. });
  99756. });
  99757. }
  99758. else {
  99759. //single simplifier.
  99760. var simplifier = this.getSimplifier(task);
  99761. var runDecimation = function (setting, callback) {
  99762. simplifier.simplify(setting, function (newMesh) {
  99763. task.mesh.addLODLevel(setting.distance, newMesh);
  99764. newMesh.isVisible = true;
  99765. //run the next quality level
  99766. callback();
  99767. });
  99768. };
  99769. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  99770. runDecimation(task.settings[loop.index], function () {
  99771. loop.executeNext();
  99772. });
  99773. }, function () {
  99774. //execution ended, run the success callback.
  99775. if (task.successCallback) {
  99776. task.successCallback();
  99777. }
  99778. _this.executeNext();
  99779. });
  99780. }
  99781. };
  99782. SimplificationQueue.prototype.getSimplifier = function (task) {
  99783. switch (task.simplificationType) {
  99784. case SimplificationType.QUADRATIC:
  99785. default:
  99786. return new QuadraticErrorSimplification(task.mesh);
  99787. }
  99788. };
  99789. return SimplificationQueue;
  99790. }());
  99791. BABYLON.SimplificationQueue = SimplificationQueue;
  99792. /**
  99793. * The implemented types of simplification
  99794. * At the moment only Quadratic Error Decimation is implemented
  99795. */
  99796. var SimplificationType;
  99797. (function (SimplificationType) {
  99798. /** Quadratic error decimation */
  99799. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  99800. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  99801. var DecimationTriangle = /** @class */ (function () {
  99802. function DecimationTriangle(vertices) {
  99803. this.vertices = vertices;
  99804. this.error = new Array(4);
  99805. this.deleted = false;
  99806. this.isDirty = false;
  99807. this.deletePending = false;
  99808. this.borderFactor = 0;
  99809. }
  99810. return DecimationTriangle;
  99811. }());
  99812. BABYLON.DecimationTriangle = DecimationTriangle;
  99813. var DecimationVertex = /** @class */ (function () {
  99814. function DecimationVertex(position, id) {
  99815. this.position = position;
  99816. this.id = id;
  99817. this.isBorder = true;
  99818. this.q = new QuadraticMatrix();
  99819. this.triangleCount = 0;
  99820. this.triangleStart = 0;
  99821. this.originalOffsets = [];
  99822. }
  99823. DecimationVertex.prototype.updatePosition = function (newPosition) {
  99824. this.position.copyFrom(newPosition);
  99825. };
  99826. return DecimationVertex;
  99827. }());
  99828. BABYLON.DecimationVertex = DecimationVertex;
  99829. var QuadraticMatrix = /** @class */ (function () {
  99830. function QuadraticMatrix(data) {
  99831. this.data = new Array(10);
  99832. for (var i = 0; i < 10; ++i) {
  99833. if (data && data[i]) {
  99834. this.data[i] = data[i];
  99835. }
  99836. else {
  99837. this.data[i] = 0;
  99838. }
  99839. }
  99840. }
  99841. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  99842. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  99843. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  99844. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  99845. return det;
  99846. };
  99847. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  99848. for (var i = 0; i < 10; ++i) {
  99849. this.data[i] += matrix.data[i];
  99850. }
  99851. };
  99852. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  99853. for (var i = 0; i < 10; ++i) {
  99854. this.data[i] += data[i];
  99855. }
  99856. };
  99857. QuadraticMatrix.prototype.add = function (matrix) {
  99858. var m = new QuadraticMatrix();
  99859. for (var i = 0; i < 10; ++i) {
  99860. m.data[i] = this.data[i] + matrix.data[i];
  99861. }
  99862. return m;
  99863. };
  99864. QuadraticMatrix.FromData = function (a, b, c, d) {
  99865. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  99866. };
  99867. //returning an array to avoid garbage collection
  99868. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  99869. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  99870. };
  99871. return QuadraticMatrix;
  99872. }());
  99873. BABYLON.QuadraticMatrix = QuadraticMatrix;
  99874. var Reference = /** @class */ (function () {
  99875. function Reference(vertexId, triangleId) {
  99876. this.vertexId = vertexId;
  99877. this.triangleId = triangleId;
  99878. }
  99879. return Reference;
  99880. }());
  99881. BABYLON.Reference = Reference;
  99882. /**
  99883. * An implementation of the Quadratic Error simplification algorithm.
  99884. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  99885. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  99886. * @author RaananW
  99887. */
  99888. var QuadraticErrorSimplification = /** @class */ (function () {
  99889. function QuadraticErrorSimplification(_mesh) {
  99890. this._mesh = _mesh;
  99891. this.syncIterations = 5000;
  99892. this.aggressiveness = 7;
  99893. this.decimationIterations = 100;
  99894. this.boundingBoxEpsilon = BABYLON.Epsilon;
  99895. }
  99896. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  99897. var _this = this;
  99898. this.initDecimatedMesh();
  99899. //iterating through the submeshes array, one after the other.
  99900. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  99901. _this.initWithMesh(loop.index, function () {
  99902. _this.runDecimation(settings, loop.index, function () {
  99903. loop.executeNext();
  99904. });
  99905. }, settings.optimizeMesh);
  99906. }, function () {
  99907. setTimeout(function () {
  99908. successCallback(_this._reconstructedMesh);
  99909. }, 0);
  99910. });
  99911. };
  99912. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  99913. var _this = this;
  99914. var targetCount = ~~(this.triangles.length * settings.quality);
  99915. var deletedTriangles = 0;
  99916. var triangleCount = this.triangles.length;
  99917. var iterationFunction = function (iteration, callback) {
  99918. setTimeout(function () {
  99919. if (iteration % 5 === 0) {
  99920. _this.updateMesh(iteration === 0);
  99921. }
  99922. for (var i = 0; i < _this.triangles.length; ++i) {
  99923. _this.triangles[i].isDirty = false;
  99924. }
  99925. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  99926. var trianglesIterator = function (i) {
  99927. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  99928. var t = _this.triangles[tIdx];
  99929. if (!t)
  99930. return;
  99931. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  99932. return;
  99933. }
  99934. for (var j = 0; j < 3; ++j) {
  99935. if (t.error[j] < threshold) {
  99936. var deleted0 = [];
  99937. var deleted1 = [];
  99938. var v0 = t.vertices[j];
  99939. var v1 = t.vertices[(j + 1) % 3];
  99940. if (v0.isBorder || v1.isBorder)
  99941. continue;
  99942. var p = BABYLON.Vector3.Zero();
  99943. var n = BABYLON.Vector3.Zero();
  99944. var uv = BABYLON.Vector2.Zero();
  99945. var color = new BABYLON.Color4(0, 0, 0, 1);
  99946. _this.calculateError(v0, v1, p, n, uv, color);
  99947. var delTr = new Array();
  99948. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  99949. continue;
  99950. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  99951. continue;
  99952. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  99953. continue;
  99954. var uniqueArray = new Array();
  99955. delTr.forEach(function (deletedT) {
  99956. if (uniqueArray.indexOf(deletedT) === -1) {
  99957. deletedT.deletePending = true;
  99958. uniqueArray.push(deletedT);
  99959. }
  99960. });
  99961. if (uniqueArray.length % 2 !== 0) {
  99962. continue;
  99963. }
  99964. v0.q = v1.q.add(v0.q);
  99965. v0.updatePosition(p);
  99966. var tStart = _this.references.length;
  99967. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  99968. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  99969. var tCount = _this.references.length - tStart;
  99970. if (tCount <= v0.triangleCount) {
  99971. if (tCount) {
  99972. for (var c = 0; c < tCount; c++) {
  99973. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  99974. }
  99975. }
  99976. }
  99977. else {
  99978. v0.triangleStart = tStart;
  99979. }
  99980. v0.triangleCount = tCount;
  99981. break;
  99982. }
  99983. }
  99984. };
  99985. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  99986. }, 0);
  99987. };
  99988. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  99989. if (triangleCount - deletedTriangles <= targetCount)
  99990. loop.breakLoop();
  99991. else {
  99992. iterationFunction(loop.index, function () {
  99993. loop.executeNext();
  99994. });
  99995. }
  99996. }, function () {
  99997. setTimeout(function () {
  99998. //reconstruct this part of the mesh
  99999. _this.reconstructMesh(submeshIndex);
  100000. successCallback();
  100001. }, 0);
  100002. });
  100003. };
  100004. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  100005. var _this = this;
  100006. this.vertices = [];
  100007. this.triangles = [];
  100008. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  100009. var indices = this._mesh.getIndices();
  100010. var submesh = this._mesh.subMeshes[submeshIndex];
  100011. var findInVertices = function (positionToSearch) {
  100012. if (optimizeMesh) {
  100013. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  100014. if (_this.vertices[ii].position.equals(positionToSearch)) {
  100015. return _this.vertices[ii];
  100016. }
  100017. }
  100018. }
  100019. return null;
  100020. };
  100021. var vertexReferences = [];
  100022. var vertexInit = function (i) {
  100023. if (!positionData) {
  100024. return;
  100025. }
  100026. var offset = i + submesh.verticesStart;
  100027. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  100028. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  100029. vertex.originalOffsets.push(offset);
  100030. if (vertex.id === _this.vertices.length) {
  100031. _this.vertices.push(vertex);
  100032. }
  100033. vertexReferences.push(vertex.id);
  100034. };
  100035. //var totalVertices = mesh.getTotalVertices();
  100036. var totalVertices = submesh.verticesCount;
  100037. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  100038. var indicesInit = function (i) {
  100039. if (!indices) {
  100040. return;
  100041. }
  100042. var offset = (submesh.indexStart / 3) + i;
  100043. var pos = (offset * 3);
  100044. var i0 = indices[pos + 0];
  100045. var i1 = indices[pos + 1];
  100046. var i2 = indices[pos + 2];
  100047. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  100048. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  100049. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  100050. var triangle = new DecimationTriangle([v0, v1, v2]);
  100051. triangle.originalOffset = pos;
  100052. _this.triangles.push(triangle);
  100053. };
  100054. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  100055. _this.init(callback);
  100056. });
  100057. });
  100058. };
  100059. QuadraticErrorSimplification.prototype.init = function (callback) {
  100060. var _this = this;
  100061. var triangleInit1 = function (i) {
  100062. var t = _this.triangles[i];
  100063. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  100064. for (var j = 0; j < 3; j++) {
  100065. 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))));
  100066. }
  100067. };
  100068. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  100069. var triangleInit2 = function (i) {
  100070. var t = _this.triangles[i];
  100071. for (var j = 0; j < 3; ++j) {
  100072. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  100073. }
  100074. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  100075. };
  100076. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  100077. callback();
  100078. });
  100079. });
  100080. };
  100081. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  100082. var newTriangles = [];
  100083. var i;
  100084. for (i = 0; i < this.vertices.length; ++i) {
  100085. this.vertices[i].triangleCount = 0;
  100086. }
  100087. var t;
  100088. var j;
  100089. for (i = 0; i < this.triangles.length; ++i) {
  100090. if (!this.triangles[i].deleted) {
  100091. t = this.triangles[i];
  100092. for (j = 0; j < 3; ++j) {
  100093. t.vertices[j].triangleCount = 1;
  100094. }
  100095. newTriangles.push(t);
  100096. }
  100097. }
  100098. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  100099. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  100100. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  100101. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  100102. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  100103. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  100104. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  100105. var vertexCount = 0;
  100106. for (i = 0; i < this.vertices.length; ++i) {
  100107. var vertex = this.vertices[i];
  100108. vertex.id = vertexCount;
  100109. if (vertex.triangleCount) {
  100110. vertex.originalOffsets.forEach(function (originalOffset) {
  100111. if (!normalData) {
  100112. return;
  100113. }
  100114. newPositionData.push(vertex.position.x);
  100115. newPositionData.push(vertex.position.y);
  100116. newPositionData.push(vertex.position.z);
  100117. newNormalData.push(normalData[originalOffset * 3]);
  100118. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  100119. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  100120. if (uvs && uvs.length) {
  100121. newUVsData.push(uvs[(originalOffset * 2)]);
  100122. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  100123. }
  100124. else if (colorsData && colorsData.length) {
  100125. newColorsData.push(colorsData[(originalOffset * 4)]);
  100126. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  100127. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  100128. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  100129. }
  100130. ++vertexCount;
  100131. });
  100132. }
  100133. }
  100134. var startingIndex = this._reconstructedMesh.getTotalIndices();
  100135. var startingVertex = this._reconstructedMesh.getTotalVertices();
  100136. var submeshesArray = this._reconstructedMesh.subMeshes;
  100137. this._reconstructedMesh.subMeshes = [];
  100138. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  100139. var originalIndices = this._mesh.getIndices();
  100140. for (i = 0; i < newTriangles.length; ++i) {
  100141. t = newTriangles[i]; //now get the new referencing point for each vertex
  100142. [0, 1, 2].forEach(function (idx) {
  100143. var id = originalIndices[t.originalOffset + idx];
  100144. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  100145. if (offset < 0)
  100146. offset = 0;
  100147. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  100148. });
  100149. }
  100150. //overwriting the old vertex buffers and indices.
  100151. this._reconstructedMesh.setIndices(newIndicesArray);
  100152. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  100153. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  100154. if (newUVsData.length > 0)
  100155. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  100156. if (newColorsData.length > 0)
  100157. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  100158. //create submesh
  100159. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  100160. if (submeshIndex > 0) {
  100161. this._reconstructedMesh.subMeshes = [];
  100162. submeshesArray.forEach(function (submesh) {
  100163. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  100164. });
  100165. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  100166. }
  100167. };
  100168. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  100169. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  100170. this._reconstructedMesh.material = this._mesh.material;
  100171. this._reconstructedMesh.parent = this._mesh.parent;
  100172. this._reconstructedMesh.isVisible = false;
  100173. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  100174. };
  100175. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  100176. for (var i = 0; i < vertex1.triangleCount; ++i) {
  100177. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  100178. if (t.deleted)
  100179. continue;
  100180. var s = this.references[vertex1.triangleStart + i].vertexId;
  100181. var v1 = t.vertices[(s + 1) % 3];
  100182. var v2 = t.vertices[(s + 2) % 3];
  100183. if ((v1 === vertex2 || v2 === vertex2)) {
  100184. deletedArray[i] = true;
  100185. delTr.push(t);
  100186. continue;
  100187. }
  100188. var d1 = v1.position.subtract(point);
  100189. d1 = d1.normalize();
  100190. var d2 = v2.position.subtract(point);
  100191. d2 = d2.normalize();
  100192. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  100193. return true;
  100194. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  100195. deletedArray[i] = false;
  100196. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  100197. return true;
  100198. }
  100199. return false;
  100200. };
  100201. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  100202. var newDeleted = deletedTriangles;
  100203. for (var i = 0; i < vertex.triangleCount; ++i) {
  100204. var ref = this.references[vertex.triangleStart + i];
  100205. var t = this.triangles[ref.triangleId];
  100206. if (t.deleted)
  100207. continue;
  100208. if (deletedArray[i] && t.deletePending) {
  100209. t.deleted = true;
  100210. newDeleted++;
  100211. continue;
  100212. }
  100213. t.vertices[ref.vertexId] = origVertex;
  100214. t.isDirty = true;
  100215. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  100216. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  100217. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  100218. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  100219. this.references.push(ref);
  100220. }
  100221. return newDeleted;
  100222. };
  100223. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  100224. for (var i = 0; i < this.vertices.length; ++i) {
  100225. var vCount = [];
  100226. var vId = [];
  100227. var v = this.vertices[i];
  100228. var j;
  100229. for (j = 0; j < v.triangleCount; ++j) {
  100230. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  100231. for (var ii = 0; ii < 3; ii++) {
  100232. var ofs = 0;
  100233. var vv = triangle.vertices[ii];
  100234. while (ofs < vCount.length) {
  100235. if (vId[ofs] === vv.id)
  100236. break;
  100237. ++ofs;
  100238. }
  100239. if (ofs === vCount.length) {
  100240. vCount.push(1);
  100241. vId.push(vv.id);
  100242. }
  100243. else {
  100244. vCount[ofs]++;
  100245. }
  100246. }
  100247. }
  100248. for (j = 0; j < vCount.length; ++j) {
  100249. if (vCount[j] === 1) {
  100250. this.vertices[vId[j]].isBorder = true;
  100251. }
  100252. else {
  100253. this.vertices[vId[j]].isBorder = false;
  100254. }
  100255. }
  100256. }
  100257. };
  100258. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  100259. if (identifyBorders === void 0) { identifyBorders = false; }
  100260. var i;
  100261. if (!identifyBorders) {
  100262. var newTrianglesVector = [];
  100263. for (i = 0; i < this.triangles.length; ++i) {
  100264. if (!this.triangles[i].deleted) {
  100265. newTrianglesVector.push(this.triangles[i]);
  100266. }
  100267. }
  100268. this.triangles = newTrianglesVector;
  100269. }
  100270. for (i = 0; i < this.vertices.length; ++i) {
  100271. this.vertices[i].triangleCount = 0;
  100272. this.vertices[i].triangleStart = 0;
  100273. }
  100274. var t;
  100275. var j;
  100276. var v;
  100277. for (i = 0; i < this.triangles.length; ++i) {
  100278. t = this.triangles[i];
  100279. for (j = 0; j < 3; ++j) {
  100280. v = t.vertices[j];
  100281. v.triangleCount++;
  100282. }
  100283. }
  100284. var tStart = 0;
  100285. for (i = 0; i < this.vertices.length; ++i) {
  100286. this.vertices[i].triangleStart = tStart;
  100287. tStart += this.vertices[i].triangleCount;
  100288. this.vertices[i].triangleCount = 0;
  100289. }
  100290. var newReferences = new Array(this.triangles.length * 3);
  100291. for (i = 0; i < this.triangles.length; ++i) {
  100292. t = this.triangles[i];
  100293. for (j = 0; j < 3; ++j) {
  100294. v = t.vertices[j];
  100295. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  100296. v.triangleCount++;
  100297. }
  100298. }
  100299. this.references = newReferences;
  100300. if (identifyBorders) {
  100301. this.identifyBorder();
  100302. }
  100303. };
  100304. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  100305. var x = point.x;
  100306. var y = point.y;
  100307. var z = point.z;
  100308. 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
  100309. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  100310. };
  100311. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  100312. var q = vertex1.q.add(vertex2.q);
  100313. var border = vertex1.isBorder && vertex2.isBorder;
  100314. var error = 0;
  100315. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  100316. if (qDet !== 0 && !border) {
  100317. if (!pointResult) {
  100318. pointResult = BABYLON.Vector3.Zero();
  100319. }
  100320. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  100321. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  100322. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  100323. error = this.vertexError(q, pointResult);
  100324. }
  100325. else {
  100326. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  100327. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  100328. var error1 = this.vertexError(q, vertex1.position);
  100329. var error2 = this.vertexError(q, vertex2.position);
  100330. var error3 = this.vertexError(q, p3);
  100331. error = Math.min(error1, error2, error3);
  100332. if (error === error1) {
  100333. if (pointResult) {
  100334. pointResult.copyFrom(vertex1.position);
  100335. }
  100336. }
  100337. else if (error === error2) {
  100338. if (pointResult) {
  100339. pointResult.copyFrom(vertex2.position);
  100340. }
  100341. }
  100342. else {
  100343. if (pointResult) {
  100344. pointResult.copyFrom(p3);
  100345. }
  100346. }
  100347. }
  100348. return error;
  100349. };
  100350. return QuadraticErrorSimplification;
  100351. }());
  100352. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  100353. })(BABYLON || (BABYLON = {}));
  100354. //# sourceMappingURL=babylon.meshSimplification.js.map
  100355. var BABYLON;
  100356. (function (BABYLON) {
  100357. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  100358. get: function () {
  100359. if (!this._simplificationQueue) {
  100360. this._simplificationQueue = new BABYLON.SimplificationQueue();
  100361. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  100362. if (!component) {
  100363. component = new SimplicationQueueSceneComponent(this);
  100364. this._addComponent(component);
  100365. }
  100366. }
  100367. return this._simplificationQueue;
  100368. },
  100369. set: function (value) {
  100370. this._simplificationQueue = value;
  100371. },
  100372. enumerable: true,
  100373. configurable: true
  100374. });
  100375. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  100376. if (parallelProcessing === void 0) { parallelProcessing = true; }
  100377. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  100378. this.getScene().simplificationQueue.addTask({
  100379. settings: settings,
  100380. parallelProcessing: parallelProcessing,
  100381. mesh: this,
  100382. simplificationType: simplificationType,
  100383. successCallback: successCallback
  100384. });
  100385. return this;
  100386. };
  100387. /**
  100388. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  100389. * created in a scene
  100390. */
  100391. var SimplicationQueueSceneComponent = /** @class */ (function () {
  100392. /**
  100393. * Creates a new instance of the component for the given scene
  100394. * @param scene Defines the scene to register the component in
  100395. */
  100396. function SimplicationQueueSceneComponent(scene) {
  100397. /**
  100398. * The component name helpfull to identify the component in the list of scene components.
  100399. */
  100400. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  100401. this.scene = scene;
  100402. }
  100403. /**
  100404. * Registers the component in a given scene
  100405. */
  100406. SimplicationQueueSceneComponent.prototype.register = function () {
  100407. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  100408. };
  100409. /**
  100410. * Rebuilds the elements related to this component in case of
  100411. * context lost for instance.
  100412. */
  100413. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  100414. // Nothing to do for this component
  100415. };
  100416. /**
  100417. * Disposes the component and the associated ressources
  100418. */
  100419. SimplicationQueueSceneComponent.prototype.dispose = function () {
  100420. // Nothing to do for this component
  100421. };
  100422. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  100423. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  100424. this.scene._simplificationQueue.executeNext();
  100425. }
  100426. };
  100427. return SimplicationQueueSceneComponent;
  100428. }());
  100429. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  100430. })(BABYLON || (BABYLON = {}));
  100431. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  100432. var BABYLON;
  100433. (function (BABYLON) {
  100434. var MeshLODLevel = /** @class */ (function () {
  100435. function MeshLODLevel(distance, mesh) {
  100436. this.distance = distance;
  100437. this.mesh = mesh;
  100438. }
  100439. return MeshLODLevel;
  100440. }());
  100441. BABYLON.MeshLODLevel = MeshLODLevel;
  100442. })(BABYLON || (BABYLON = {}));
  100443. //# sourceMappingURL=babylon.meshLODLevel.js.map
  100444. var BABYLON;
  100445. (function (BABYLON) {
  100446. /**
  100447. * Defines the root class used to create scene optimization to use with SceneOptimizer
  100448. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100449. */
  100450. var SceneOptimization = /** @class */ (function () {
  100451. /**
  100452. * Creates the SceneOptimization object
  100453. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100454. * @param desc defines the description associated with the optimization
  100455. */
  100456. function SceneOptimization(
  100457. /**
  100458. * Defines the priority of this optimization (0 by default which means first in the list)
  100459. */
  100460. priority) {
  100461. if (priority === void 0) { priority = 0; }
  100462. this.priority = priority;
  100463. }
  100464. /**
  100465. * Gets a string describing the action executed by the current optimization
  100466. * @returns description string
  100467. */
  100468. SceneOptimization.prototype.getDescription = function () {
  100469. return "";
  100470. };
  100471. /**
  100472. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100473. * @param scene defines the current scene where to apply this optimization
  100474. * @param optimizer defines the current optimizer
  100475. * @returns true if everything that can be done was applied
  100476. */
  100477. SceneOptimization.prototype.apply = function (scene, optimizer) {
  100478. return true;
  100479. };
  100480. ;
  100481. return SceneOptimization;
  100482. }());
  100483. BABYLON.SceneOptimization = SceneOptimization;
  100484. /**
  100485. * Defines an optimization used to reduce the size of render target textures
  100486. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100487. */
  100488. var TextureOptimization = /** @class */ (function (_super) {
  100489. __extends(TextureOptimization, _super);
  100490. /**
  100491. * Creates the TextureOptimization object
  100492. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100493. * @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
  100494. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  100495. */
  100496. function TextureOptimization(
  100497. /**
  100498. * Defines the priority of this optimization (0 by default which means first in the list)
  100499. */
  100500. priority,
  100501. /**
  100502. * 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
  100503. */
  100504. maximumSize,
  100505. /**
  100506. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  100507. */
  100508. step) {
  100509. if (priority === void 0) { priority = 0; }
  100510. if (maximumSize === void 0) { maximumSize = 1024; }
  100511. if (step === void 0) { step = 0.5; }
  100512. var _this = _super.call(this, priority) || this;
  100513. _this.priority = priority;
  100514. _this.maximumSize = maximumSize;
  100515. _this.step = step;
  100516. return _this;
  100517. }
  100518. /**
  100519. * Gets a string describing the action executed by the current optimization
  100520. * @returns description string
  100521. */
  100522. TextureOptimization.prototype.getDescription = function () {
  100523. return "Reducing render target texture size to " + this.maximumSize;
  100524. };
  100525. /**
  100526. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100527. * @param scene defines the current scene where to apply this optimization
  100528. * @param optimizer defines the current optimizer
  100529. * @returns true if everything that can be done was applied
  100530. */
  100531. TextureOptimization.prototype.apply = function (scene, optimizer) {
  100532. var allDone = true;
  100533. for (var index = 0; index < scene.textures.length; index++) {
  100534. var texture = scene.textures[index];
  100535. if (!texture.canRescale || texture.getContext) {
  100536. continue;
  100537. }
  100538. var currentSize = texture.getSize();
  100539. var maxDimension = Math.max(currentSize.width, currentSize.height);
  100540. if (maxDimension > this.maximumSize) {
  100541. texture.scale(this.step);
  100542. allDone = false;
  100543. }
  100544. }
  100545. return allDone;
  100546. };
  100547. return TextureOptimization;
  100548. }(SceneOptimization));
  100549. BABYLON.TextureOptimization = TextureOptimization;
  100550. /**
  100551. * Defines an optimization used to increase or decrease the rendering resolution
  100552. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100553. */
  100554. var HardwareScalingOptimization = /** @class */ (function (_super) {
  100555. __extends(HardwareScalingOptimization, _super);
  100556. /**
  100557. * Creates the HardwareScalingOptimization object
  100558. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100559. * @param maximumScale defines the maximum scale to use (2 by default)
  100560. * @param step defines the step to use between two passes (0.5 by default)
  100561. */
  100562. function HardwareScalingOptimization(
  100563. /**
  100564. * Defines the priority of this optimization (0 by default which means first in the list)
  100565. */
  100566. priority,
  100567. /**
  100568. * Defines the maximum scale to use (2 by default)
  100569. */
  100570. maximumScale,
  100571. /**
  100572. * Defines the step to use between two passes (0.5 by default)
  100573. */
  100574. step) {
  100575. if (priority === void 0) { priority = 0; }
  100576. if (maximumScale === void 0) { maximumScale = 2; }
  100577. if (step === void 0) { step = 0.25; }
  100578. var _this = _super.call(this, priority) || this;
  100579. _this.priority = priority;
  100580. _this.maximumScale = maximumScale;
  100581. _this.step = step;
  100582. _this._currentScale = -1;
  100583. _this._directionOffset = 1;
  100584. return _this;
  100585. }
  100586. /**
  100587. * Gets a string describing the action executed by the current optimization
  100588. * @return description string
  100589. */
  100590. HardwareScalingOptimization.prototype.getDescription = function () {
  100591. return "Setting hardware scaling level to " + this._currentScale;
  100592. };
  100593. /**
  100594. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100595. * @param scene defines the current scene where to apply this optimization
  100596. * @param optimizer defines the current optimizer
  100597. * @returns true if everything that can be done was applied
  100598. */
  100599. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  100600. if (this._currentScale === -1) {
  100601. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  100602. if (this._currentScale > this.maximumScale) {
  100603. this._directionOffset = -1;
  100604. }
  100605. }
  100606. this._currentScale += this._directionOffset * this.step;
  100607. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  100608. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  100609. };
  100610. ;
  100611. return HardwareScalingOptimization;
  100612. }(SceneOptimization));
  100613. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  100614. /**
  100615. * Defines an optimization used to remove shadows
  100616. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100617. */
  100618. var ShadowsOptimization = /** @class */ (function (_super) {
  100619. __extends(ShadowsOptimization, _super);
  100620. function ShadowsOptimization() {
  100621. return _super !== null && _super.apply(this, arguments) || this;
  100622. }
  100623. /**
  100624. * Gets a string describing the action executed by the current optimization
  100625. * @return description string
  100626. */
  100627. ShadowsOptimization.prototype.getDescription = function () {
  100628. return "Turning shadows on/off";
  100629. };
  100630. /**
  100631. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100632. * @param scene defines the current scene where to apply this optimization
  100633. * @param optimizer defines the current optimizer
  100634. * @returns true if everything that can be done was applied
  100635. */
  100636. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  100637. scene.shadowsEnabled = optimizer.isInImprovementMode;
  100638. return true;
  100639. };
  100640. ;
  100641. return ShadowsOptimization;
  100642. }(SceneOptimization));
  100643. BABYLON.ShadowsOptimization = ShadowsOptimization;
  100644. /**
  100645. * Defines an optimization used to turn post-processes off
  100646. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100647. */
  100648. var PostProcessesOptimization = /** @class */ (function (_super) {
  100649. __extends(PostProcessesOptimization, _super);
  100650. function PostProcessesOptimization() {
  100651. return _super !== null && _super.apply(this, arguments) || this;
  100652. }
  100653. /**
  100654. * Gets a string describing the action executed by the current optimization
  100655. * @return description string
  100656. */
  100657. PostProcessesOptimization.prototype.getDescription = function () {
  100658. return "Turning post-processes on/off";
  100659. };
  100660. /**
  100661. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100662. * @param scene defines the current scene where to apply this optimization
  100663. * @param optimizer defines the current optimizer
  100664. * @returns true if everything that can be done was applied
  100665. */
  100666. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  100667. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  100668. return true;
  100669. };
  100670. ;
  100671. return PostProcessesOptimization;
  100672. }(SceneOptimization));
  100673. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  100674. /**
  100675. * Defines an optimization used to turn lens flares off
  100676. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100677. */
  100678. var LensFlaresOptimization = /** @class */ (function (_super) {
  100679. __extends(LensFlaresOptimization, _super);
  100680. function LensFlaresOptimization() {
  100681. return _super !== null && _super.apply(this, arguments) || this;
  100682. }
  100683. /**
  100684. * Gets a string describing the action executed by the current optimization
  100685. * @return description string
  100686. */
  100687. LensFlaresOptimization.prototype.getDescription = function () {
  100688. return "Turning lens flares on/off";
  100689. };
  100690. /**
  100691. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100692. * @param scene defines the current scene where to apply this optimization
  100693. * @param optimizer defines the current optimizer
  100694. * @returns true if everything that can be done was applied
  100695. */
  100696. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  100697. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  100698. return true;
  100699. };
  100700. ;
  100701. return LensFlaresOptimization;
  100702. }(SceneOptimization));
  100703. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  100704. /**
  100705. * Defines an optimization based on user defined callback.
  100706. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100707. */
  100708. var CustomOptimization = /** @class */ (function (_super) {
  100709. __extends(CustomOptimization, _super);
  100710. function CustomOptimization() {
  100711. return _super !== null && _super.apply(this, arguments) || this;
  100712. }
  100713. /**
  100714. * Gets a string describing the action executed by the current optimization
  100715. * @returns description string
  100716. */
  100717. CustomOptimization.prototype.getDescription = function () {
  100718. if (this.onGetDescription) {
  100719. return this.onGetDescription();
  100720. }
  100721. return "Running user defined callback";
  100722. };
  100723. /**
  100724. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100725. * @param scene defines the current scene where to apply this optimization
  100726. * @param optimizer defines the current optimizer
  100727. * @returns true if everything that can be done was applied
  100728. */
  100729. CustomOptimization.prototype.apply = function (scene, optimizer) {
  100730. if (this.onApply) {
  100731. return this.onApply(scene, optimizer);
  100732. }
  100733. return true;
  100734. };
  100735. ;
  100736. return CustomOptimization;
  100737. }(SceneOptimization));
  100738. BABYLON.CustomOptimization = CustomOptimization;
  100739. /**
  100740. * Defines an optimization used to turn particles off
  100741. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100742. */
  100743. var ParticlesOptimization = /** @class */ (function (_super) {
  100744. __extends(ParticlesOptimization, _super);
  100745. function ParticlesOptimization() {
  100746. return _super !== null && _super.apply(this, arguments) || this;
  100747. }
  100748. /**
  100749. * Gets a string describing the action executed by the current optimization
  100750. * @return description string
  100751. */
  100752. ParticlesOptimization.prototype.getDescription = function () {
  100753. return "Turning particles on/off";
  100754. };
  100755. /**
  100756. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100757. * @param scene defines the current scene where to apply this optimization
  100758. * @param optimizer defines the current optimizer
  100759. * @returns true if everything that can be done was applied
  100760. */
  100761. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  100762. scene.particlesEnabled = optimizer.isInImprovementMode;
  100763. return true;
  100764. };
  100765. ;
  100766. return ParticlesOptimization;
  100767. }(SceneOptimization));
  100768. BABYLON.ParticlesOptimization = ParticlesOptimization;
  100769. /**
  100770. * Defines an optimization used to turn render targets off
  100771. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100772. */
  100773. var RenderTargetsOptimization = /** @class */ (function (_super) {
  100774. __extends(RenderTargetsOptimization, _super);
  100775. function RenderTargetsOptimization() {
  100776. return _super !== null && _super.apply(this, arguments) || this;
  100777. }
  100778. /**
  100779. * Gets a string describing the action executed by the current optimization
  100780. * @return description string
  100781. */
  100782. RenderTargetsOptimization.prototype.getDescription = function () {
  100783. return "Turning render targets off";
  100784. };
  100785. /**
  100786. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100787. * @param scene defines the current scene where to apply this optimization
  100788. * @param optimizer defines the current optimizer
  100789. * @returns true if everything that can be done was applied
  100790. */
  100791. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  100792. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  100793. return true;
  100794. };
  100795. ;
  100796. return RenderTargetsOptimization;
  100797. }(SceneOptimization));
  100798. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  100799. /**
  100800. * Defines an optimization used to merge meshes with compatible materials
  100801. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100802. */
  100803. var MergeMeshesOptimization = /** @class */ (function (_super) {
  100804. __extends(MergeMeshesOptimization, _super);
  100805. function MergeMeshesOptimization() {
  100806. var _this = _super !== null && _super.apply(this, arguments) || this;
  100807. _this._canBeMerged = function (abstractMesh) {
  100808. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  100809. return false;
  100810. }
  100811. var mesh = abstractMesh;
  100812. if (mesh.isDisposed()) {
  100813. return false;
  100814. }
  100815. if (!mesh.isVisible || !mesh.isEnabled()) {
  100816. return false;
  100817. }
  100818. if (mesh.instances.length > 0) {
  100819. return false;
  100820. }
  100821. if (mesh.skeleton || mesh.hasLODLevels) {
  100822. return false;
  100823. }
  100824. return true;
  100825. };
  100826. return _this;
  100827. }
  100828. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  100829. /**
  100830. * Gets or sets a boolean which defines if optimization octree has to be updated
  100831. */
  100832. get: function () {
  100833. return MergeMeshesOptimization._UpdateSelectionTree;
  100834. },
  100835. /**
  100836. * Gets or sets a boolean which defines if optimization octree has to be updated
  100837. */
  100838. set: function (value) {
  100839. MergeMeshesOptimization._UpdateSelectionTree = value;
  100840. },
  100841. enumerable: true,
  100842. configurable: true
  100843. });
  100844. /**
  100845. * Gets a string describing the action executed by the current optimization
  100846. * @return description string
  100847. */
  100848. MergeMeshesOptimization.prototype.getDescription = function () {
  100849. return "Merging similar meshes together";
  100850. };
  100851. /**
  100852. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100853. * @param scene defines the current scene where to apply this optimization
  100854. * @param optimizer defines the current optimizer
  100855. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  100856. * @returns true if everything that can be done was applied
  100857. */
  100858. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  100859. var globalPool = scene.meshes.slice(0);
  100860. var globalLength = globalPool.length;
  100861. for (var index = 0; index < globalLength; index++) {
  100862. var currentPool = new Array();
  100863. var current = globalPool[index];
  100864. // Checks
  100865. if (!this._canBeMerged(current)) {
  100866. continue;
  100867. }
  100868. currentPool.push(current);
  100869. // Find compatible meshes
  100870. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  100871. var otherMesh = globalPool[subIndex];
  100872. if (!this._canBeMerged(otherMesh)) {
  100873. continue;
  100874. }
  100875. if (otherMesh.material !== current.material) {
  100876. continue;
  100877. }
  100878. if (otherMesh.checkCollisions !== current.checkCollisions) {
  100879. continue;
  100880. }
  100881. currentPool.push(otherMesh);
  100882. globalLength--;
  100883. globalPool.splice(subIndex, 1);
  100884. subIndex--;
  100885. }
  100886. if (currentPool.length < 2) {
  100887. continue;
  100888. }
  100889. // Merge meshes
  100890. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  100891. }
  100892. // Call the octree system optimization if it is defined.
  100893. var sceneAsAny = scene;
  100894. if (sceneAsAny.createOrUpdateSelectionOctree) {
  100895. if (updateSelectionTree != undefined) {
  100896. if (updateSelectionTree) {
  100897. sceneAsAny.createOrUpdateSelectionOctree();
  100898. }
  100899. }
  100900. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  100901. sceneAsAny.createOrUpdateSelectionOctree();
  100902. }
  100903. }
  100904. return true;
  100905. };
  100906. ;
  100907. MergeMeshesOptimization._UpdateSelectionTree = false;
  100908. return MergeMeshesOptimization;
  100909. }(SceneOptimization));
  100910. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  100911. /**
  100912. * Defines a list of options used by SceneOptimizer
  100913. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100914. */
  100915. var SceneOptimizerOptions = /** @class */ (function () {
  100916. /**
  100917. * Creates a new list of options used by SceneOptimizer
  100918. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  100919. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  100920. */
  100921. function SceneOptimizerOptions(
  100922. /**
  100923. * Defines the target frame rate to reach (60 by default)
  100924. */
  100925. targetFrameRate,
  100926. /**
  100927. * Defines the interval between two checkes (2000ms by default)
  100928. */
  100929. trackerDuration) {
  100930. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  100931. if (trackerDuration === void 0) { trackerDuration = 2000; }
  100932. this.targetFrameRate = targetFrameRate;
  100933. this.trackerDuration = trackerDuration;
  100934. /**
  100935. * Gets the list of optimizations to apply
  100936. */
  100937. this.optimizations = new Array();
  100938. }
  100939. /**
  100940. * Add a new optimization
  100941. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  100942. * @returns the current SceneOptimizerOptions
  100943. */
  100944. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  100945. this.optimizations.push(optimization);
  100946. return this;
  100947. };
  100948. /**
  100949. * Add a new custom optimization
  100950. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  100951. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  100952. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100953. * @returns the current SceneOptimizerOptions
  100954. */
  100955. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  100956. if (priority === void 0) { priority = 0; }
  100957. var optimization = new CustomOptimization(priority);
  100958. optimization.onApply = onApply;
  100959. optimization.onGetDescription = onGetDescription;
  100960. this.optimizations.push(optimization);
  100961. return this;
  100962. };
  100963. /**
  100964. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  100965. * @param targetFrameRate defines the target frame rate (60 by default)
  100966. * @returns a SceneOptimizerOptions object
  100967. */
  100968. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  100969. var result = new SceneOptimizerOptions(targetFrameRate);
  100970. var priority = 0;
  100971. result.addOptimization(new MergeMeshesOptimization(priority));
  100972. result.addOptimization(new ShadowsOptimization(priority));
  100973. result.addOptimization(new LensFlaresOptimization(priority));
  100974. // Next priority
  100975. priority++;
  100976. result.addOptimization(new PostProcessesOptimization(priority));
  100977. result.addOptimization(new ParticlesOptimization(priority));
  100978. // Next priority
  100979. priority++;
  100980. result.addOptimization(new TextureOptimization(priority, 1024));
  100981. return result;
  100982. };
  100983. /**
  100984. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  100985. * @param targetFrameRate defines the target frame rate (60 by default)
  100986. * @returns a SceneOptimizerOptions object
  100987. */
  100988. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  100989. var result = new SceneOptimizerOptions(targetFrameRate);
  100990. var priority = 0;
  100991. result.addOptimization(new MergeMeshesOptimization(priority));
  100992. result.addOptimization(new ShadowsOptimization(priority));
  100993. result.addOptimization(new LensFlaresOptimization(priority));
  100994. // Next priority
  100995. priority++;
  100996. result.addOptimization(new PostProcessesOptimization(priority));
  100997. result.addOptimization(new ParticlesOptimization(priority));
  100998. // Next priority
  100999. priority++;
  101000. result.addOptimization(new TextureOptimization(priority, 512));
  101001. // Next priority
  101002. priority++;
  101003. result.addOptimization(new RenderTargetsOptimization(priority));
  101004. // Next priority
  101005. priority++;
  101006. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  101007. return result;
  101008. };
  101009. /**
  101010. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  101011. * @param targetFrameRate defines the target frame rate (60 by default)
  101012. * @returns a SceneOptimizerOptions object
  101013. */
  101014. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  101015. var result = new SceneOptimizerOptions(targetFrameRate);
  101016. var priority = 0;
  101017. result.addOptimization(new MergeMeshesOptimization(priority));
  101018. result.addOptimization(new ShadowsOptimization(priority));
  101019. result.addOptimization(new LensFlaresOptimization(priority));
  101020. // Next priority
  101021. priority++;
  101022. result.addOptimization(new PostProcessesOptimization(priority));
  101023. result.addOptimization(new ParticlesOptimization(priority));
  101024. // Next priority
  101025. priority++;
  101026. result.addOptimization(new TextureOptimization(priority, 256));
  101027. // Next priority
  101028. priority++;
  101029. result.addOptimization(new RenderTargetsOptimization(priority));
  101030. // Next priority
  101031. priority++;
  101032. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  101033. return result;
  101034. };
  101035. return SceneOptimizerOptions;
  101036. }());
  101037. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  101038. /**
  101039. * Class used to run optimizations in order to reach a target frame rate
  101040. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  101041. */
  101042. var SceneOptimizer = /** @class */ (function () {
  101043. /**
  101044. * Creates a new SceneOptimizer
  101045. * @param scene defines the scene to work on
  101046. * @param options defines the options to use with the SceneOptimizer
  101047. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  101048. * @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)
  101049. */
  101050. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  101051. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  101052. if (improvementMode === void 0) { improvementMode = false; }
  101053. var _this = this;
  101054. this._isRunning = false;
  101055. this._currentPriorityLevel = 0;
  101056. this._targetFrameRate = 60;
  101057. this._trackerDuration = 2000;
  101058. this._currentFrameRate = 0;
  101059. this._improvementMode = false;
  101060. /**
  101061. * Defines an observable called when the optimizer reaches the target frame rate
  101062. */
  101063. this.onSuccessObservable = new BABYLON.Observable();
  101064. /**
  101065. * Defines an observable called when the optimizer enables an optimization
  101066. */
  101067. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  101068. /**
  101069. * Defines an observable called when the optimizer is not able to reach the target frame rate
  101070. */
  101071. this.onFailureObservable = new BABYLON.Observable();
  101072. if (!options) {
  101073. this._options = new SceneOptimizerOptions();
  101074. }
  101075. else {
  101076. this._options = options;
  101077. }
  101078. if (this._options.targetFrameRate) {
  101079. this._targetFrameRate = this._options.targetFrameRate;
  101080. }
  101081. if (this._options.trackerDuration) {
  101082. this._trackerDuration = this._options.trackerDuration;
  101083. }
  101084. if (autoGeneratePriorities) {
  101085. var priority = 0;
  101086. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  101087. var optim = _a[_i];
  101088. optim.priority = priority++;
  101089. }
  101090. }
  101091. this._improvementMode = improvementMode;
  101092. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  101093. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  101094. _this._sceneDisposeObserver = null;
  101095. _this.dispose();
  101096. });
  101097. }
  101098. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  101099. /**
  101100. * Gets a boolean indicating if the optimizer is in improvement mode
  101101. */
  101102. get: function () {
  101103. return this._improvementMode;
  101104. },
  101105. enumerable: true,
  101106. configurable: true
  101107. });
  101108. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  101109. /**
  101110. * Gets the current priority level (0 at start)
  101111. */
  101112. get: function () {
  101113. return this._currentPriorityLevel;
  101114. },
  101115. enumerable: true,
  101116. configurable: true
  101117. });
  101118. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  101119. /**
  101120. * Gets the current frame rate checked by the SceneOptimizer
  101121. */
  101122. get: function () {
  101123. return this._currentFrameRate;
  101124. },
  101125. enumerable: true,
  101126. configurable: true
  101127. });
  101128. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  101129. /**
  101130. * Gets or sets the current target frame rate (60 by default)
  101131. */
  101132. get: function () {
  101133. return this._targetFrameRate;
  101134. },
  101135. /**
  101136. * Gets or sets the current target frame rate (60 by default)
  101137. */
  101138. set: function (value) {
  101139. this._targetFrameRate = value;
  101140. },
  101141. enumerable: true,
  101142. configurable: true
  101143. });
  101144. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  101145. /**
  101146. * Gets or sets the current interval between two checks (every 2000ms by default)
  101147. */
  101148. get: function () {
  101149. return this._trackerDuration;
  101150. },
  101151. /**
  101152. * Gets or sets the current interval between two checks (every 2000ms by default)
  101153. */
  101154. set: function (value) {
  101155. this._trackerDuration = value;
  101156. },
  101157. enumerable: true,
  101158. configurable: true
  101159. });
  101160. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  101161. /**
  101162. * Gets the list of active optimizations
  101163. */
  101164. get: function () {
  101165. return this._options.optimizations;
  101166. },
  101167. enumerable: true,
  101168. configurable: true
  101169. });
  101170. /**
  101171. * Stops the current optimizer
  101172. */
  101173. SceneOptimizer.prototype.stop = function () {
  101174. this._isRunning = false;
  101175. };
  101176. /**
  101177. * Reset the optimizer to initial step (current priority level = 0)
  101178. */
  101179. SceneOptimizer.prototype.reset = function () {
  101180. this._currentPriorityLevel = 0;
  101181. };
  101182. /**
  101183. * Start the optimizer. By default it will try to reach a specific framerate
  101184. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  101185. */
  101186. SceneOptimizer.prototype.start = function () {
  101187. var _this = this;
  101188. if (this._isRunning) {
  101189. return;
  101190. }
  101191. this._isRunning = true;
  101192. // Let's wait for the scene to be ready before running our check
  101193. this._scene.executeWhenReady(function () {
  101194. setTimeout(function () {
  101195. _this._checkCurrentState();
  101196. }, _this._trackerDuration);
  101197. });
  101198. };
  101199. SceneOptimizer.prototype._checkCurrentState = function () {
  101200. var _this = this;
  101201. if (!this._isRunning) {
  101202. return;
  101203. }
  101204. var scene = this._scene;
  101205. var options = this._options;
  101206. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  101207. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  101208. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  101209. this._isRunning = false;
  101210. this.onSuccessObservable.notifyObservers(this);
  101211. return;
  101212. }
  101213. // Apply current level of optimizations
  101214. var allDone = true;
  101215. var noOptimizationApplied = true;
  101216. for (var index = 0; index < options.optimizations.length; index++) {
  101217. var optimization = options.optimizations[index];
  101218. if (optimization.priority === this._currentPriorityLevel) {
  101219. noOptimizationApplied = false;
  101220. allDone = allDone && optimization.apply(scene, this);
  101221. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  101222. }
  101223. }
  101224. // If no optimization was applied, this is a failure :(
  101225. if (noOptimizationApplied) {
  101226. this._isRunning = false;
  101227. this.onFailureObservable.notifyObservers(this);
  101228. return;
  101229. }
  101230. // If all optimizations were done, move to next level
  101231. if (allDone) {
  101232. this._currentPriorityLevel++;
  101233. }
  101234. // Let's the system running for a specific amount of time before checking FPS
  101235. scene.executeWhenReady(function () {
  101236. setTimeout(function () {
  101237. _this._checkCurrentState();
  101238. }, _this._trackerDuration);
  101239. });
  101240. };
  101241. /**
  101242. * Release all resources
  101243. */
  101244. SceneOptimizer.prototype.dispose = function () {
  101245. this.stop();
  101246. this.onSuccessObservable.clear();
  101247. this.onFailureObservable.clear();
  101248. this.onNewOptimizationAppliedObservable.clear();
  101249. if (this._sceneDisposeObserver) {
  101250. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  101251. }
  101252. };
  101253. /**
  101254. * Helper function to create a SceneOptimizer with one single line of code
  101255. * @param scene defines the scene to work on
  101256. * @param options defines the options to use with the SceneOptimizer
  101257. * @param onSuccess defines a callback to call on success
  101258. * @param onFailure defines a callback to call on failure
  101259. * @returns the new SceneOptimizer object
  101260. */
  101261. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  101262. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  101263. if (onSuccess) {
  101264. optimizer.onSuccessObservable.add(function () {
  101265. onSuccess();
  101266. });
  101267. }
  101268. if (onFailure) {
  101269. optimizer.onFailureObservable.add(function () {
  101270. onFailure();
  101271. });
  101272. }
  101273. optimizer.start();
  101274. return optimizer;
  101275. };
  101276. return SceneOptimizer;
  101277. }());
  101278. BABYLON.SceneOptimizer = SceneOptimizer;
  101279. })(BABYLON || (BABYLON = {}));
  101280. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  101281. var BABYLON;
  101282. (function (BABYLON) {
  101283. /**
  101284. * Gets the outline renderer associated with the scene
  101285. * @returns a OutlineRenderer
  101286. */
  101287. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  101288. if (!this._outlineRenderer) {
  101289. this._outlineRenderer = new OutlineRenderer(this);
  101290. }
  101291. return this._outlineRenderer;
  101292. };
  101293. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  101294. get: function () {
  101295. return this._renderOutline;
  101296. },
  101297. set: function (value) {
  101298. if (value) {
  101299. // Lazy Load the component.
  101300. this.getScene().getOutlineRenderer();
  101301. }
  101302. this._renderOutline = value;
  101303. },
  101304. enumerable: true,
  101305. configurable: true
  101306. });
  101307. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  101308. get: function () {
  101309. return this._renderOverlay;
  101310. },
  101311. set: function (value) {
  101312. if (value) {
  101313. // Lazy Load the component.
  101314. this.getScene().getOutlineRenderer();
  101315. }
  101316. this._renderOverlay = value;
  101317. },
  101318. enumerable: true,
  101319. configurable: true
  101320. });
  101321. /**
  101322. * This class is responsible to draw bothe outline/overlay of meshes.
  101323. * It should not be used directly but through the available method on mesh.
  101324. */
  101325. var OutlineRenderer = /** @class */ (function () {
  101326. /**
  101327. * Instantiates a new outline renderer. (There could be only one per scene).
  101328. * @param scene Defines the scene it belongs to
  101329. */
  101330. function OutlineRenderer(scene) {
  101331. /**
  101332. * The name of the component. Each component must have a unique name.
  101333. */
  101334. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  101335. /**
  101336. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  101337. */
  101338. this.zOffset = 1;
  101339. this.scene = scene;
  101340. this._engine = scene.getEngine();
  101341. this.scene._addComponent(this);
  101342. }
  101343. /**
  101344. * Register the component to one instance of a scene.
  101345. */
  101346. OutlineRenderer.prototype.register = function () {
  101347. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  101348. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  101349. };
  101350. /**
  101351. * Rebuilds the elements related to this component in case of
  101352. * context lost for instance.
  101353. */
  101354. OutlineRenderer.prototype.rebuild = function () {
  101355. // Nothing to do here.
  101356. };
  101357. /**
  101358. * Disposes the component and the associated ressources.
  101359. */
  101360. OutlineRenderer.prototype.dispose = function () {
  101361. // Nothing to do here.
  101362. };
  101363. /**
  101364. * Renders the outline in the canvas.
  101365. * @param subMesh Defines the sumesh to render
  101366. * @param batch Defines the batch of meshes in case of instances
  101367. * @param useOverlay Defines if the rendering is for the overlay or the outline
  101368. */
  101369. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  101370. var _this = this;
  101371. if (useOverlay === void 0) { useOverlay = false; }
  101372. var scene = this.scene;
  101373. var engine = scene.getEngine();
  101374. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  101375. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  101376. return;
  101377. }
  101378. var mesh = subMesh.getRenderingMesh();
  101379. var material = subMesh.getMaterial();
  101380. if (!material || !scene.activeCamera) {
  101381. return;
  101382. }
  101383. engine.enableEffect(this._effect);
  101384. // Logarithmic depth
  101385. if (material.useLogarithmicDepth) {
  101386. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  101387. }
  101388. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  101389. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  101390. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  101391. // Bones
  101392. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  101393. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  101394. }
  101395. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  101396. // Alpha test
  101397. if (material && material.needAlphaTesting()) {
  101398. var alphaTexture = material.getAlphaTestTexture();
  101399. if (alphaTexture) {
  101400. this._effect.setTexture("diffuseSampler", alphaTexture);
  101401. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  101402. }
  101403. }
  101404. engine.setZOffset(-this.zOffset);
  101405. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  101406. engine.setZOffset(0);
  101407. };
  101408. /**
  101409. * Returns whether or not the outline renderer is ready for a given submesh.
  101410. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  101411. * @param subMesh Defines the submesh to check readyness for
  101412. * @param useInstances Defines wheter wee are trying to render instances or not
  101413. * @returns true if ready otherwise false
  101414. */
  101415. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  101416. var defines = [];
  101417. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  101418. var mesh = subMesh.getMesh();
  101419. var material = subMesh.getMaterial();
  101420. if (material) {
  101421. // Alpha test
  101422. if (material.needAlphaTesting()) {
  101423. defines.push("#define ALPHATEST");
  101424. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  101425. attribs.push(BABYLON.VertexBuffer.UVKind);
  101426. defines.push("#define UV1");
  101427. }
  101428. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  101429. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  101430. defines.push("#define UV2");
  101431. }
  101432. }
  101433. //Logarithmic depth
  101434. if (material.useLogarithmicDepth) {
  101435. defines.push("#define LOGARITHMICDEPTH");
  101436. }
  101437. }
  101438. // Bones
  101439. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  101440. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  101441. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  101442. if (mesh.numBoneInfluencers > 4) {
  101443. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  101444. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  101445. }
  101446. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  101447. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  101448. }
  101449. else {
  101450. defines.push("#define NUM_BONE_INFLUENCERS 0");
  101451. }
  101452. // Instances
  101453. if (useInstances) {
  101454. defines.push("#define INSTANCES");
  101455. attribs.push("world0");
  101456. attribs.push("world1");
  101457. attribs.push("world2");
  101458. attribs.push("world3");
  101459. }
  101460. // Get correct effect
  101461. var join = defines.join("\n");
  101462. if (this._cachedDefines !== join) {
  101463. this._cachedDefines = join;
  101464. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  101465. }
  101466. return this._effect.isReady();
  101467. };
  101468. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  101469. // Outline - step 1
  101470. this._savedDepthWrite = this._engine.getDepthWrite();
  101471. if (mesh.renderOutline) {
  101472. this._engine.setDepthWrite(false);
  101473. this.render(subMesh, batch);
  101474. this._engine.setDepthWrite(this._savedDepthWrite);
  101475. }
  101476. };
  101477. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  101478. // Outline - step 2
  101479. if (mesh.renderOutline && this._savedDepthWrite) {
  101480. this._engine.setDepthWrite(true);
  101481. this._engine.setColorWrite(false);
  101482. this.render(subMesh, batch);
  101483. this._engine.setColorWrite(true);
  101484. }
  101485. // Overlay
  101486. if (mesh.renderOverlay) {
  101487. var currentMode = this._engine.getAlphaMode();
  101488. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  101489. this.render(subMesh, batch, true);
  101490. this._engine.setAlphaMode(currentMode);
  101491. }
  101492. };
  101493. return OutlineRenderer;
  101494. }());
  101495. BABYLON.OutlineRenderer = OutlineRenderer;
  101496. })(BABYLON || (BABYLON = {}));
  101497. //# sourceMappingURL=babylon.outlineRenderer.js.map
  101498. var BABYLON;
  101499. (function (BABYLON) {
  101500. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  101501. if (this._edgesRenderer) {
  101502. this._edgesRenderer.dispose();
  101503. this._edgesRenderer = null;
  101504. }
  101505. return this;
  101506. };
  101507. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  101508. if (epsilon === void 0) { epsilon = 0.95; }
  101509. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101510. this.disableEdgesRendering();
  101511. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  101512. return this;
  101513. };
  101514. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  101515. get: function () {
  101516. return this._edgesRenderer;
  101517. },
  101518. enumerable: true,
  101519. configurable: true
  101520. });
  101521. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  101522. if (epsilon === void 0) { epsilon = 0.95; }
  101523. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101524. this.disableEdgesRendering();
  101525. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  101526. return this;
  101527. };
  101528. /**
  101529. * FaceAdjacencies Helper class to generate edges
  101530. */
  101531. var FaceAdjacencies = /** @class */ (function () {
  101532. function FaceAdjacencies() {
  101533. this.edges = new Array();
  101534. this.edgesConnectedCount = 0;
  101535. }
  101536. return FaceAdjacencies;
  101537. }());
  101538. /**
  101539. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  101540. */
  101541. var EdgesRenderer = /** @class */ (function () {
  101542. /**
  101543. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  101544. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  101545. * @param source Mesh used to create edges
  101546. * @param epsilon sum of angles in adjacency to check for edge
  101547. * @param checkVerticesInsteadOfIndices
  101548. * @param generateEdgesLines - should generate Lines or only prepare resources.
  101549. */
  101550. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  101551. if (epsilon === void 0) { epsilon = 0.95; }
  101552. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101553. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  101554. var _this = this;
  101555. this.edgesWidthScalerForOrthographic = 1000.0;
  101556. this.edgesWidthScalerForPerspective = 50.0;
  101557. this._linesPositions = new Array();
  101558. this._linesNormals = new Array();
  101559. this._linesIndices = new Array();
  101560. this._buffers = {};
  101561. this._checkVerticesInsteadOfIndices = false;
  101562. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  101563. this.isEnabled = true;
  101564. this._source = source;
  101565. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  101566. this._epsilon = epsilon;
  101567. this._prepareRessources();
  101568. if (generateEdgesLines) {
  101569. this._generateEdgesLines();
  101570. }
  101571. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  101572. _this._rebuild();
  101573. });
  101574. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  101575. _this.dispose();
  101576. });
  101577. }
  101578. EdgesRenderer.prototype._prepareRessources = function () {
  101579. if (this._lineShader) {
  101580. return;
  101581. }
  101582. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  101583. attributes: ["position", "normal"],
  101584. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  101585. });
  101586. this._lineShader.disableDepthWrite = true;
  101587. this._lineShader.backFaceCulling = false;
  101588. };
  101589. /** @hidden */
  101590. EdgesRenderer.prototype._rebuild = function () {
  101591. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  101592. if (buffer) {
  101593. buffer._rebuild();
  101594. }
  101595. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  101596. if (buffer) {
  101597. buffer._rebuild();
  101598. }
  101599. var scene = this._source.getScene();
  101600. var engine = scene.getEngine();
  101601. this._ib = engine.createIndexBuffer(this._linesIndices);
  101602. };
  101603. /**
  101604. * Releases the required resources for the edges renderer
  101605. */
  101606. EdgesRenderer.prototype.dispose = function () {
  101607. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  101608. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  101609. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  101610. if (buffer) {
  101611. buffer.dispose();
  101612. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  101613. }
  101614. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  101615. if (buffer) {
  101616. buffer.dispose();
  101617. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  101618. }
  101619. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  101620. this._lineShader.dispose();
  101621. };
  101622. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  101623. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  101624. return 0;
  101625. }
  101626. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  101627. return 1;
  101628. }
  101629. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  101630. return 2;
  101631. }
  101632. return -1;
  101633. };
  101634. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  101635. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  101636. return 0;
  101637. }
  101638. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  101639. return 1;
  101640. }
  101641. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  101642. return 2;
  101643. }
  101644. return -1;
  101645. };
  101646. /**
  101647. * Checks if the pair of p0 and p1 is en edge
  101648. * @param faceIndex
  101649. * @param edge
  101650. * @param faceNormals
  101651. * @param p0
  101652. * @param p1
  101653. * @private
  101654. */
  101655. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  101656. var needToCreateLine;
  101657. if (edge === undefined) {
  101658. needToCreateLine = true;
  101659. }
  101660. else {
  101661. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  101662. needToCreateLine = dotProduct < this._epsilon;
  101663. }
  101664. if (needToCreateLine) {
  101665. var offset = this._linesPositions.length / 3;
  101666. var normal = p0.subtract(p1);
  101667. normal.normalize();
  101668. // Positions
  101669. this._linesPositions.push(p0.x);
  101670. this._linesPositions.push(p0.y);
  101671. this._linesPositions.push(p0.z);
  101672. this._linesPositions.push(p0.x);
  101673. this._linesPositions.push(p0.y);
  101674. this._linesPositions.push(p0.z);
  101675. this._linesPositions.push(p1.x);
  101676. this._linesPositions.push(p1.y);
  101677. this._linesPositions.push(p1.z);
  101678. this._linesPositions.push(p1.x);
  101679. this._linesPositions.push(p1.y);
  101680. this._linesPositions.push(p1.z);
  101681. // Normals
  101682. this._linesNormals.push(p1.x);
  101683. this._linesNormals.push(p1.y);
  101684. this._linesNormals.push(p1.z);
  101685. this._linesNormals.push(-1);
  101686. this._linesNormals.push(p1.x);
  101687. this._linesNormals.push(p1.y);
  101688. this._linesNormals.push(p1.z);
  101689. this._linesNormals.push(1);
  101690. this._linesNormals.push(p0.x);
  101691. this._linesNormals.push(p0.y);
  101692. this._linesNormals.push(p0.z);
  101693. this._linesNormals.push(-1);
  101694. this._linesNormals.push(p0.x);
  101695. this._linesNormals.push(p0.y);
  101696. this._linesNormals.push(p0.z);
  101697. this._linesNormals.push(1);
  101698. // Indices
  101699. this._linesIndices.push(offset);
  101700. this._linesIndices.push(offset + 1);
  101701. this._linesIndices.push(offset + 2);
  101702. this._linesIndices.push(offset);
  101703. this._linesIndices.push(offset + 2);
  101704. this._linesIndices.push(offset + 3);
  101705. }
  101706. };
  101707. /**
  101708. * Generates lines edges from adjacencjes
  101709. * @private
  101710. */
  101711. EdgesRenderer.prototype._generateEdgesLines = function () {
  101712. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  101713. var indices = this._source.getIndices();
  101714. if (!indices || !positions) {
  101715. return;
  101716. }
  101717. // First let's find adjacencies
  101718. var adjacencies = new Array();
  101719. var faceNormals = new Array();
  101720. var index;
  101721. var faceAdjacencies;
  101722. // Prepare faces
  101723. for (index = 0; index < indices.length; index += 3) {
  101724. faceAdjacencies = new FaceAdjacencies();
  101725. var p0Index = indices[index];
  101726. var p1Index = indices[index + 1];
  101727. var p2Index = indices[index + 2];
  101728. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  101729. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  101730. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  101731. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  101732. faceNormal.normalize();
  101733. faceNormals.push(faceNormal);
  101734. adjacencies.push(faceAdjacencies);
  101735. }
  101736. // Scan
  101737. for (index = 0; index < adjacencies.length; index++) {
  101738. faceAdjacencies = adjacencies[index];
  101739. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  101740. var otherFaceAdjacencies = adjacencies[otherIndex];
  101741. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  101742. break;
  101743. }
  101744. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  101745. continue;
  101746. }
  101747. var otherP0 = indices[otherIndex * 3];
  101748. var otherP1 = indices[otherIndex * 3 + 1];
  101749. var otherP2 = indices[otherIndex * 3 + 2];
  101750. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  101751. var otherEdgeIndex = 0;
  101752. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  101753. continue;
  101754. }
  101755. switch (edgeIndex) {
  101756. case 0:
  101757. if (this._checkVerticesInsteadOfIndices) {
  101758. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  101759. }
  101760. else {
  101761. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  101762. }
  101763. break;
  101764. case 1:
  101765. if (this._checkVerticesInsteadOfIndices) {
  101766. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  101767. }
  101768. else {
  101769. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  101770. }
  101771. break;
  101772. case 2:
  101773. if (this._checkVerticesInsteadOfIndices) {
  101774. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  101775. }
  101776. else {
  101777. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  101778. }
  101779. break;
  101780. }
  101781. if (otherEdgeIndex === -1) {
  101782. continue;
  101783. }
  101784. faceAdjacencies.edges[edgeIndex] = otherIndex;
  101785. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  101786. faceAdjacencies.edgesConnectedCount++;
  101787. otherFaceAdjacencies.edgesConnectedCount++;
  101788. if (faceAdjacencies.edgesConnectedCount === 3) {
  101789. break;
  101790. }
  101791. }
  101792. }
  101793. }
  101794. // Create lines
  101795. for (index = 0; index < adjacencies.length; index++) {
  101796. // 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
  101797. var current = adjacencies[index];
  101798. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  101799. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  101800. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  101801. }
  101802. // Merge into a single mesh
  101803. var engine = this._source.getScene().getEngine();
  101804. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  101805. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  101806. this._ib = engine.createIndexBuffer(this._linesIndices);
  101807. this._indicesCount = this._linesIndices.length;
  101808. };
  101809. /**
  101810. * Checks wether or not the edges renderer is ready to render.
  101811. * @return true if ready, otherwise false.
  101812. */
  101813. EdgesRenderer.prototype.isReady = function () {
  101814. return this._lineShader.isReady();
  101815. };
  101816. /**
  101817. * Renders the edges of the attached mesh,
  101818. */
  101819. EdgesRenderer.prototype.render = function () {
  101820. var scene = this._source.getScene();
  101821. if (!this.isReady() || !scene.activeCamera) {
  101822. return;
  101823. }
  101824. var engine = scene.getEngine();
  101825. this._lineShader._preBind();
  101826. if (this._source.edgesColor.a !== 1) {
  101827. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  101828. }
  101829. else {
  101830. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  101831. }
  101832. // VBOs
  101833. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  101834. scene.resetCachedMaterial();
  101835. this._lineShader.setColor4("color", this._source.edgesColor);
  101836. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  101837. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  101838. }
  101839. else {
  101840. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  101841. }
  101842. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  101843. this._lineShader.bind(this._source.getWorldMatrix());
  101844. // Draw order
  101845. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  101846. this._lineShader.unbind();
  101847. };
  101848. return EdgesRenderer;
  101849. }());
  101850. BABYLON.EdgesRenderer = EdgesRenderer;
  101851. })(BABYLON || (BABYLON = {}));
  101852. //# sourceMappingURL=babylon.edgesRenderer.js.map
  101853. var BABYLON;
  101854. (function (BABYLON) {
  101855. /**
  101856. * FaceAdjacencies Helper class to generate edges
  101857. */
  101858. var FaceAdjacencies = /** @class */ (function () {
  101859. function FaceAdjacencies() {
  101860. this.edges = new Array();
  101861. this.edgesConnectedCount = 0;
  101862. }
  101863. return FaceAdjacencies;
  101864. }());
  101865. /**
  101866. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  101867. */
  101868. var LineEdgesRenderer = /** @class */ (function (_super) {
  101869. __extends(LineEdgesRenderer, _super);
  101870. /**
  101871. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  101872. * @param source LineMesh used to generate edges
  101873. * @param epsilon not important (specified angle for edge detection)
  101874. * @param checkVerticesInsteadOfIndices not important for LineMesh
  101875. */
  101876. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  101877. if (epsilon === void 0) { epsilon = 0.95; }
  101878. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101879. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  101880. _this._generateEdgesLines();
  101881. return _this;
  101882. }
  101883. /**
  101884. * Always create the edge since its a line so only important things are p0 and p1
  101885. * @param faceIndex not important for LineMesh
  101886. * @param edge not important for LineMesh
  101887. * @param faceNormals not important for LineMesh
  101888. * @param p0 beginnig of line
  101889. * @param p1 end of line
  101890. */
  101891. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  101892. var offset = this._linesPositions.length / 3;
  101893. var normal = p0.subtract(p1);
  101894. normal.normalize();
  101895. // Positions
  101896. this._linesPositions.push(p0.x);
  101897. this._linesPositions.push(p0.y);
  101898. this._linesPositions.push(p0.z);
  101899. this._linesPositions.push(p0.x);
  101900. this._linesPositions.push(p0.y);
  101901. this._linesPositions.push(p0.z);
  101902. this._linesPositions.push(p1.x);
  101903. this._linesPositions.push(p1.y);
  101904. this._linesPositions.push(p1.z);
  101905. this._linesPositions.push(p1.x);
  101906. this._linesPositions.push(p1.y);
  101907. this._linesPositions.push(p1.z);
  101908. // Normals
  101909. this._linesNormals.push(p1.x);
  101910. this._linesNormals.push(p1.y);
  101911. this._linesNormals.push(p1.z);
  101912. this._linesNormals.push(-1);
  101913. this._linesNormals.push(p1.x);
  101914. this._linesNormals.push(p1.y);
  101915. this._linesNormals.push(p1.z);
  101916. this._linesNormals.push(1);
  101917. this._linesNormals.push(p0.x);
  101918. this._linesNormals.push(p0.y);
  101919. this._linesNormals.push(p0.z);
  101920. this._linesNormals.push(-1);
  101921. this._linesNormals.push(p0.x);
  101922. this._linesNormals.push(p0.y);
  101923. this._linesNormals.push(p0.z);
  101924. this._linesNormals.push(1);
  101925. // Indices
  101926. this._linesIndices.push(offset);
  101927. this._linesIndices.push(offset + 1);
  101928. this._linesIndices.push(offset + 2);
  101929. this._linesIndices.push(offset);
  101930. this._linesIndices.push(offset + 2);
  101931. this._linesIndices.push(offset + 3);
  101932. };
  101933. /**
  101934. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  101935. */
  101936. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  101937. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  101938. var indices = this._source.getIndices();
  101939. if (!indices || !positions) {
  101940. return;
  101941. }
  101942. // First let's find adjacencies
  101943. var adjacencies = new Array();
  101944. var faceNormals = new Array();
  101945. var index;
  101946. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  101947. var currentAdjecancy = new FaceAdjacencies();
  101948. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  101949. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  101950. adjacencies.push(currentAdjecancy);
  101951. }
  101952. // Create lines
  101953. for (index = 0; index < adjacencies.length; index++) {
  101954. // 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
  101955. var current = adjacencies[index];
  101956. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  101957. }
  101958. // Merge into a single mesh
  101959. var engine = this._source.getScene().getEngine();
  101960. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  101961. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  101962. this._ib = engine.createIndexBuffer(this._linesIndices);
  101963. this._indicesCount = this._linesIndices.length;
  101964. };
  101965. return LineEdgesRenderer;
  101966. }(BABYLON.EdgesRenderer));
  101967. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  101968. })(BABYLON || (BABYLON = {}));
  101969. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  101970. var BABYLON;
  101971. (function (BABYLON) {
  101972. // Adds the parser to the scene parsers.
  101973. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  101974. if (parsedData.effectLayers) {
  101975. if (!container.effectLayers) {
  101976. container.effectLayers = new Array();
  101977. }
  101978. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  101979. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  101980. container.effectLayers.push(effectLayer);
  101981. }
  101982. }
  101983. });
  101984. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  101985. var index = this.effectLayers.indexOf(toRemove);
  101986. if (index !== -1) {
  101987. this.effectLayers.splice(index, 1);
  101988. }
  101989. return index;
  101990. };
  101991. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  101992. this.effectLayers.push(newEffectLayer);
  101993. };
  101994. /**
  101995. * Defines the layer scene component responsible to manage any effect layers
  101996. * in a given scene.
  101997. */
  101998. var EffectLayerSceneComponent = /** @class */ (function () {
  101999. /**
  102000. * Creates a new instance of the component for the given scene
  102001. * @param scene Defines the scene to register the component in
  102002. */
  102003. function EffectLayerSceneComponent(scene) {
  102004. /**
  102005. * The component name helpfull to identify the component in the list of scene components.
  102006. */
  102007. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  102008. this._renderEffects = false;
  102009. this._needStencil = false;
  102010. this._previousStencilState = false;
  102011. this.scene = scene;
  102012. this._engine = scene.getEngine();
  102013. scene.effectLayers = new Array();
  102014. }
  102015. /**
  102016. * Registers the component in a given scene
  102017. */
  102018. EffectLayerSceneComponent.prototype.register = function () {
  102019. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  102020. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  102021. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  102022. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  102023. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  102024. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  102025. };
  102026. /**
  102027. * Rebuilds the elements related to this component in case of
  102028. * context lost for instance.
  102029. */
  102030. EffectLayerSceneComponent.prototype.rebuild = function () {
  102031. var layers = this.scene.effectLayers;
  102032. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  102033. var effectLayer = layers_1[_i];
  102034. effectLayer._rebuild();
  102035. }
  102036. };
  102037. /**
  102038. * Serializes the component data to the specified json object
  102039. * @param serializationObject The object to serialize to
  102040. */
  102041. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  102042. // Effect layers
  102043. serializationObject.effectLayers = [];
  102044. var layers = this.scene.effectLayers;
  102045. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  102046. var effectLayer = layers_2[_i];
  102047. if (effectLayer.serialize) {
  102048. serializationObject.effectLayers.push(effectLayer.serialize());
  102049. }
  102050. }
  102051. };
  102052. /**
  102053. * Adds all the element from the container to the scene
  102054. * @param container the container holding the elements
  102055. */
  102056. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  102057. var _this = this;
  102058. if (!container.effectLayers) {
  102059. return;
  102060. }
  102061. container.effectLayers.forEach(function (o) {
  102062. _this.scene.addEffectLayer(o);
  102063. });
  102064. };
  102065. /**
  102066. * Removes all the elements in the container from the scene
  102067. * @param container contains the elements to remove
  102068. */
  102069. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  102070. var _this = this;
  102071. if (!container.effectLayers) {
  102072. return;
  102073. }
  102074. container.effectLayers.forEach(function (o) {
  102075. _this.scene.removeEffectLayer(o);
  102076. });
  102077. };
  102078. /**
  102079. * Disposes the component and the associated ressources.
  102080. */
  102081. EffectLayerSceneComponent.prototype.dispose = function () {
  102082. var layers = this.scene.effectLayers;
  102083. while (layers.length) {
  102084. layers[0].dispose();
  102085. }
  102086. };
  102087. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  102088. var layers = this.scene.effectLayers;
  102089. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  102090. var layer = layers_3[_i];
  102091. if (!layer.hasMesh(mesh)) {
  102092. continue;
  102093. }
  102094. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  102095. var subMesh = _b[_a];
  102096. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  102097. return false;
  102098. }
  102099. }
  102100. }
  102101. return true;
  102102. };
  102103. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  102104. this._renderEffects = false;
  102105. this._needStencil = false;
  102106. var layers = this.scene.effectLayers;
  102107. if (layers && layers.length > 0) {
  102108. this._previousStencilState = this._engine.getStencilBuffer();
  102109. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  102110. var effectLayer = layers_4[_i];
  102111. if (effectLayer.shouldRender() &&
  102112. (!effectLayer.camera ||
  102113. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  102114. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  102115. this._renderEffects = true;
  102116. this._needStencil = this._needStencil || effectLayer.needStencil();
  102117. var renderTarget = effectLayer._mainTexture;
  102118. if (renderTarget._shouldRender()) {
  102119. this.scene.incrementRenderId();
  102120. renderTarget.render(false, false);
  102121. }
  102122. }
  102123. }
  102124. this.scene.incrementRenderId();
  102125. }
  102126. };
  102127. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  102128. // Activate effect Layer stencil
  102129. if (this._needStencil) {
  102130. this._engine.setStencilBuffer(true);
  102131. }
  102132. };
  102133. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  102134. // Restore effect Layer stencil
  102135. if (this._needStencil) {
  102136. this._engine.setStencilBuffer(this._previousStencilState);
  102137. }
  102138. };
  102139. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  102140. if (this._renderEffects) {
  102141. this._engine.setDepthBuffer(false);
  102142. var layers = this.scene.effectLayers;
  102143. for (var i = 0; i < layers.length; i++) {
  102144. var effectLayer = layers[i];
  102145. if (effectLayer.renderingGroupId === renderingGroupId) {
  102146. if (effectLayer.shouldRender()) {
  102147. effectLayer.render();
  102148. }
  102149. }
  102150. }
  102151. this._engine.setDepthBuffer(true);
  102152. }
  102153. };
  102154. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  102155. if (this._renderEffects) {
  102156. this._draw(-1);
  102157. }
  102158. };
  102159. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  102160. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  102161. this._draw(index);
  102162. }
  102163. };
  102164. return EffectLayerSceneComponent;
  102165. }());
  102166. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  102167. })(BABYLON || (BABYLON = {}));
  102168. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  102169. var __assign = (this && this.__assign) || function () {
  102170. __assign = Object.assign || function(t) {
  102171. for (var s, i = 1, n = arguments.length; i < n; i++) {
  102172. s = arguments[i];
  102173. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  102174. t[p] = s[p];
  102175. }
  102176. return t;
  102177. };
  102178. return __assign.apply(this, arguments);
  102179. };
  102180. var BABYLON;
  102181. (function (BABYLON) {
  102182. /**
  102183. * The effect layer Helps adding post process effect blended with the main pass.
  102184. *
  102185. * This can be for instance use to generate glow or higlight effects on the scene.
  102186. *
  102187. * The effect layer class can not be used directly and is intented to inherited from to be
  102188. * customized per effects.
  102189. */
  102190. var EffectLayer = /** @class */ (function () {
  102191. /**
  102192. * Instantiates a new effect Layer and references it in the scene.
  102193. * @param name The name of the layer
  102194. * @param scene The scene to use the layer in
  102195. */
  102196. function EffectLayer(
  102197. /** The Friendly of the effect in the scene */
  102198. name, scene) {
  102199. this._vertexBuffers = {};
  102200. this._maxSize = 0;
  102201. this._mainTextureDesiredSize = { width: 0, height: 0 };
  102202. this._shouldRender = true;
  102203. this._postProcesses = [];
  102204. this._textures = [];
  102205. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  102206. /**
  102207. * The clear color of the texture used to generate the glow map.
  102208. */
  102209. this.neutralColor = new BABYLON.Color4();
  102210. /**
  102211. * Specifies wether the highlight layer is enabled or not.
  102212. */
  102213. this.isEnabled = true;
  102214. /**
  102215. * An event triggered when the effect layer has been disposed.
  102216. */
  102217. this.onDisposeObservable = new BABYLON.Observable();
  102218. /**
  102219. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  102220. */
  102221. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  102222. /**
  102223. * An event triggered when the generated texture is being merged in the scene.
  102224. */
  102225. this.onBeforeComposeObservable = new BABYLON.Observable();
  102226. /**
  102227. * An event triggered when the generated texture has been merged in the scene.
  102228. */
  102229. this.onAfterComposeObservable = new BABYLON.Observable();
  102230. /**
  102231. * An event triggered when the efffect layer changes its size.
  102232. */
  102233. this.onSizeChangedObservable = new BABYLON.Observable();
  102234. this.name = name;
  102235. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  102236. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  102237. if (!component) {
  102238. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  102239. this._scene._addComponent(component);
  102240. }
  102241. this._engine = this._scene.getEngine();
  102242. this._maxSize = this._engine.getCaps().maxTextureSize;
  102243. this._scene.effectLayers.push(this);
  102244. // Generate Buffers
  102245. this._generateIndexBuffer();
  102246. this._genrateVertexBuffer();
  102247. }
  102248. Object.defineProperty(EffectLayer.prototype, "camera", {
  102249. /**
  102250. * Gets the camera attached to the layer.
  102251. */
  102252. get: function () {
  102253. return this._effectLayerOptions.camera;
  102254. },
  102255. enumerable: true,
  102256. configurable: true
  102257. });
  102258. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  102259. /**
  102260. * Gets the rendering group id the layer should render in.
  102261. */
  102262. get: function () {
  102263. return this._effectLayerOptions.renderingGroupId;
  102264. },
  102265. enumerable: true,
  102266. configurable: true
  102267. });
  102268. /**
  102269. * Initializes the effect layer with the required options.
  102270. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  102271. */
  102272. EffectLayer.prototype._init = function (options) {
  102273. // Adapt options
  102274. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  102275. this._setMainTextureSize();
  102276. this._createMainTexture();
  102277. this._createTextureAndPostProcesses();
  102278. this._mergeEffect = this._createMergeEffect();
  102279. };
  102280. /**
  102281. * Generates the index buffer of the full screen quad blending to the main canvas.
  102282. */
  102283. EffectLayer.prototype._generateIndexBuffer = function () {
  102284. // Indices
  102285. var indices = [];
  102286. indices.push(0);
  102287. indices.push(1);
  102288. indices.push(2);
  102289. indices.push(0);
  102290. indices.push(2);
  102291. indices.push(3);
  102292. this._indexBuffer = this._engine.createIndexBuffer(indices);
  102293. };
  102294. /**
  102295. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  102296. */
  102297. EffectLayer.prototype._genrateVertexBuffer = function () {
  102298. // VBO
  102299. var vertices = [];
  102300. vertices.push(1, 1);
  102301. vertices.push(-1, 1);
  102302. vertices.push(-1, -1);
  102303. vertices.push(1, -1);
  102304. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  102305. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  102306. };
  102307. /**
  102308. * Sets the main texture desired size which is the closest power of two
  102309. * of the engine canvas size.
  102310. */
  102311. EffectLayer.prototype._setMainTextureSize = function () {
  102312. if (this._effectLayerOptions.mainTextureFixedSize) {
  102313. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  102314. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  102315. }
  102316. else {
  102317. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  102318. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  102319. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  102320. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  102321. }
  102322. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  102323. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  102324. };
  102325. /**
  102326. * Creates the main texture for the effect layer.
  102327. */
  102328. EffectLayer.prototype._createMainTexture = function () {
  102329. var _this = this;
  102330. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  102331. width: this._mainTextureDesiredSize.width,
  102332. height: this._mainTextureDesiredSize.height
  102333. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  102334. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  102335. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102336. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102337. this._mainTexture.anisotropicFilteringLevel = 1;
  102338. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  102339. this._mainTexture.renderParticles = false;
  102340. this._mainTexture.renderList = null;
  102341. this._mainTexture.ignoreCameraViewport = true;
  102342. // Custom render function
  102343. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  102344. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  102345. var index;
  102346. var engine = _this._scene.getEngine();
  102347. if (depthOnlySubMeshes.length) {
  102348. engine.setColorWrite(false);
  102349. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  102350. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  102351. }
  102352. engine.setColorWrite(true);
  102353. }
  102354. for (index = 0; index < opaqueSubMeshes.length; index++) {
  102355. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  102356. }
  102357. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  102358. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  102359. }
  102360. for (index = 0; index < transparentSubMeshes.length; index++) {
  102361. _this._renderSubMesh(transparentSubMeshes.data[index]);
  102362. }
  102363. };
  102364. this._mainTexture.onClearObservable.add(function (engine) {
  102365. engine.clear(_this.neutralColor, true, true, true);
  102366. });
  102367. };
  102368. /**
  102369. * Checks for the readiness of the element composing the layer.
  102370. * @param subMesh the mesh to check for
  102371. * @param useInstances specify wether or not to use instances to render the mesh
  102372. * @param emissiveTexture the associated emissive texture used to generate the glow
  102373. * @return true if ready otherwise, false
  102374. */
  102375. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  102376. var material = subMesh.getMaterial();
  102377. if (!material) {
  102378. return false;
  102379. }
  102380. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  102381. return false;
  102382. }
  102383. var defines = [];
  102384. var attribs = [BABYLON.VertexBuffer.PositionKind];
  102385. var mesh = subMesh.getMesh();
  102386. var uv1 = false;
  102387. var uv2 = false;
  102388. // Alpha test
  102389. if (material && material.needAlphaTesting()) {
  102390. var alphaTexture = material.getAlphaTestTexture();
  102391. if (alphaTexture) {
  102392. defines.push("#define ALPHATEST");
  102393. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  102394. alphaTexture.coordinatesIndex === 1) {
  102395. defines.push("#define DIFFUSEUV2");
  102396. uv2 = true;
  102397. }
  102398. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  102399. defines.push("#define DIFFUSEUV1");
  102400. uv1 = true;
  102401. }
  102402. }
  102403. }
  102404. // Emissive
  102405. if (emissiveTexture) {
  102406. defines.push("#define EMISSIVE");
  102407. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  102408. emissiveTexture.coordinatesIndex === 1) {
  102409. defines.push("#define EMISSIVEUV2");
  102410. uv2 = true;
  102411. }
  102412. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  102413. defines.push("#define EMISSIVEUV1");
  102414. uv1 = true;
  102415. }
  102416. }
  102417. if (uv1) {
  102418. attribs.push(BABYLON.VertexBuffer.UVKind);
  102419. defines.push("#define UV1");
  102420. }
  102421. if (uv2) {
  102422. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  102423. defines.push("#define UV2");
  102424. }
  102425. // Bones
  102426. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  102427. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  102428. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  102429. if (mesh.numBoneInfluencers > 4) {
  102430. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  102431. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  102432. }
  102433. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  102434. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  102435. }
  102436. else {
  102437. defines.push("#define NUM_BONE_INFLUENCERS 0");
  102438. }
  102439. // Morph targets
  102440. var manager = mesh.morphTargetManager;
  102441. var morphInfluencers = 0;
  102442. if (manager) {
  102443. if (manager.numInfluencers > 0) {
  102444. defines.push("#define MORPHTARGETS");
  102445. morphInfluencers = manager.numInfluencers;
  102446. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  102447. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  102448. }
  102449. }
  102450. // Instances
  102451. if (useInstances) {
  102452. defines.push("#define INSTANCES");
  102453. attribs.push("world0");
  102454. attribs.push("world1");
  102455. attribs.push("world2");
  102456. attribs.push("world3");
  102457. }
  102458. // Get correct effect
  102459. var join = defines.join("\n");
  102460. if (this._cachedDefines !== join) {
  102461. this._cachedDefines = join;
  102462. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  102463. }
  102464. return this._effectLayerMapGenerationEffect.isReady();
  102465. };
  102466. /**
  102467. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  102468. */
  102469. EffectLayer.prototype.render = function () {
  102470. var currentEffect = this._mergeEffect;
  102471. // Check
  102472. if (!currentEffect.isReady())
  102473. return;
  102474. for (var i = 0; i < this._postProcesses.length; i++) {
  102475. if (!this._postProcesses[i].isReady()) {
  102476. return;
  102477. }
  102478. }
  102479. var engine = this._scene.getEngine();
  102480. this.onBeforeComposeObservable.notifyObservers(this);
  102481. // Render
  102482. engine.enableEffect(currentEffect);
  102483. engine.setState(false);
  102484. // VBOs
  102485. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  102486. // Cache
  102487. var previousAlphaMode = engine.getAlphaMode();
  102488. // Go Blend.
  102489. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  102490. // Blends the map on the main canvas.
  102491. this._internalRender(currentEffect);
  102492. // Restore Alpha
  102493. engine.setAlphaMode(previousAlphaMode);
  102494. this.onAfterComposeObservable.notifyObservers(this);
  102495. // Handle size changes.
  102496. var size = this._mainTexture.getSize();
  102497. this._setMainTextureSize();
  102498. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  102499. // Recreate RTT and post processes on size change.
  102500. this.onSizeChangedObservable.notifyObservers(this);
  102501. this._disposeTextureAndPostProcesses();
  102502. this._createMainTexture();
  102503. this._createTextureAndPostProcesses();
  102504. }
  102505. };
  102506. /**
  102507. * Determine if a given mesh will be used in the current effect.
  102508. * @param mesh mesh to test
  102509. * @returns true if the mesh will be used
  102510. */
  102511. EffectLayer.prototype.hasMesh = function (mesh) {
  102512. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  102513. return true;
  102514. }
  102515. return false;
  102516. };
  102517. /**
  102518. * Returns true if the layer contains information to display, otherwise false.
  102519. * @returns true if the glow layer should be rendered
  102520. */
  102521. EffectLayer.prototype.shouldRender = function () {
  102522. return this.isEnabled && this._shouldRender;
  102523. };
  102524. /**
  102525. * Returns true if the mesh should render, otherwise false.
  102526. * @param mesh The mesh to render
  102527. * @returns true if it should render otherwise false
  102528. */
  102529. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  102530. return true;
  102531. };
  102532. /**
  102533. * Returns true if the mesh should render, otherwise false.
  102534. * @param mesh The mesh to render
  102535. * @returns true if it should render otherwise false
  102536. */
  102537. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  102538. return true;
  102539. };
  102540. /**
  102541. * Renders the submesh passed in parameter to the generation map.
  102542. */
  102543. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  102544. var _this = this;
  102545. if (!this.shouldRender()) {
  102546. return;
  102547. }
  102548. var material = subMesh.getMaterial();
  102549. var mesh = subMesh.getRenderingMesh();
  102550. var scene = this._scene;
  102551. var engine = scene.getEngine();
  102552. if (!material) {
  102553. return;
  102554. }
  102555. // Do not block in blend mode.
  102556. if (material.needAlphaBlendingForMesh(mesh)) {
  102557. return;
  102558. }
  102559. // Culling
  102560. engine.setState(material.backFaceCulling);
  102561. // Managing instances
  102562. var batch = mesh._getInstancesRenderList(subMesh._id);
  102563. if (batch.mustReturn) {
  102564. return;
  102565. }
  102566. // Early Exit per mesh
  102567. if (!this._shouldRenderMesh(mesh)) {
  102568. return;
  102569. }
  102570. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  102571. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  102572. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  102573. engine.enableEffect(this._effectLayerMapGenerationEffect);
  102574. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  102575. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  102576. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  102577. // Alpha test
  102578. if (material && material.needAlphaTesting()) {
  102579. var alphaTexture = material.getAlphaTestTexture();
  102580. if (alphaTexture) {
  102581. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  102582. var textureMatrix = alphaTexture.getTextureMatrix();
  102583. if (textureMatrix) {
  102584. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  102585. }
  102586. }
  102587. }
  102588. // Glow emissive only
  102589. if (this._emissiveTextureAndColor.texture) {
  102590. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  102591. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  102592. }
  102593. // Bones
  102594. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  102595. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  102596. }
  102597. // Morph targets
  102598. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  102599. // Draw
  102600. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  102601. }
  102602. else {
  102603. // Need to reset refresh rate of the main map
  102604. this._mainTexture.resetRefreshCounter();
  102605. }
  102606. };
  102607. /**
  102608. * Rebuild the required buffers.
  102609. * @hidden Internal use only.
  102610. */
  102611. EffectLayer.prototype._rebuild = function () {
  102612. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102613. if (vb) {
  102614. vb._rebuild();
  102615. }
  102616. this._generateIndexBuffer();
  102617. };
  102618. /**
  102619. * Dispose only the render target textures and post process.
  102620. */
  102621. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  102622. this._mainTexture.dispose();
  102623. for (var i = 0; i < this._postProcesses.length; i++) {
  102624. if (this._postProcesses[i]) {
  102625. this._postProcesses[i].dispose();
  102626. }
  102627. }
  102628. this._postProcesses = [];
  102629. for (var i = 0; i < this._textures.length; i++) {
  102630. if (this._textures[i]) {
  102631. this._textures[i].dispose();
  102632. }
  102633. }
  102634. this._textures = [];
  102635. };
  102636. /**
  102637. * Dispose the highlight layer and free resources.
  102638. */
  102639. EffectLayer.prototype.dispose = function () {
  102640. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102641. if (vertexBuffer) {
  102642. vertexBuffer.dispose();
  102643. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  102644. }
  102645. if (this._indexBuffer) {
  102646. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  102647. this._indexBuffer = null;
  102648. }
  102649. // Clean textures and post processes
  102650. this._disposeTextureAndPostProcesses();
  102651. // Remove from scene
  102652. var index = this._scene.effectLayers.indexOf(this, 0);
  102653. if (index > -1) {
  102654. this._scene.effectLayers.splice(index, 1);
  102655. }
  102656. // Callback
  102657. this.onDisposeObservable.notifyObservers(this);
  102658. this.onDisposeObservable.clear();
  102659. this.onBeforeRenderMainTextureObservable.clear();
  102660. this.onBeforeComposeObservable.clear();
  102661. this.onAfterComposeObservable.clear();
  102662. this.onSizeChangedObservable.clear();
  102663. };
  102664. /**
  102665. * Gets the class name of the effect layer
  102666. * @returns the string with the class name of the effect layer
  102667. */
  102668. EffectLayer.prototype.getClassName = function () {
  102669. return "EffectLayer";
  102670. };
  102671. /**
  102672. * Creates an effect layer from parsed effect layer data
  102673. * @param parsedEffectLayer defines effect layer data
  102674. * @param scene defines the current scene
  102675. * @param rootUrl defines the root URL containing the effect layer information
  102676. * @returns a parsed effect Layer
  102677. */
  102678. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  102679. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  102680. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  102681. };
  102682. __decorate([
  102683. BABYLON.serialize()
  102684. ], EffectLayer.prototype, "name", void 0);
  102685. __decorate([
  102686. BABYLON.serializeAsColor4()
  102687. ], EffectLayer.prototype, "neutralColor", void 0);
  102688. __decorate([
  102689. BABYLON.serialize()
  102690. ], EffectLayer.prototype, "isEnabled", void 0);
  102691. __decorate([
  102692. BABYLON.serializeAsCameraReference()
  102693. ], EffectLayer.prototype, "camera", null);
  102694. __decorate([
  102695. BABYLON.serialize()
  102696. ], EffectLayer.prototype, "renderingGroupId", null);
  102697. return EffectLayer;
  102698. }());
  102699. BABYLON.EffectLayer = EffectLayer;
  102700. })(BABYLON || (BABYLON = {}));
  102701. //# sourceMappingURL=babylon.effectLayer.js.map
  102702. var BABYLON;
  102703. (function (BABYLON) {
  102704. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  102705. for (var index = 0; index < this.effectLayers.length; index++) {
  102706. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  102707. return this.effectLayers[index];
  102708. }
  102709. }
  102710. return null;
  102711. };
  102712. /**
  102713. * Special Glow Blur post process only blurring the alpha channel
  102714. * It enforces keeping the most luminous color in the color channel.
  102715. */
  102716. var GlowBlurPostProcess = /** @class */ (function (_super) {
  102717. __extends(GlowBlurPostProcess, _super);
  102718. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  102719. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  102720. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  102721. _this.direction = direction;
  102722. _this.kernel = kernel;
  102723. _this.onApplyObservable.add(function (effect) {
  102724. effect.setFloat2("screenSize", _this.width, _this.height);
  102725. effect.setVector2("direction", _this.direction);
  102726. effect.setFloat("blurWidth", _this.kernel);
  102727. });
  102728. return _this;
  102729. }
  102730. return GlowBlurPostProcess;
  102731. }(BABYLON.PostProcess));
  102732. /**
  102733. * The highlight layer Helps adding a glow effect around a mesh.
  102734. *
  102735. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  102736. * glowy meshes to your scene.
  102737. *
  102738. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  102739. */
  102740. var HighlightLayer = /** @class */ (function (_super) {
  102741. __extends(HighlightLayer, _super);
  102742. /**
  102743. * Instantiates a new highlight Layer and references it to the scene..
  102744. * @param name The name of the layer
  102745. * @param scene The scene to use the layer in
  102746. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  102747. */
  102748. function HighlightLayer(name, scene, options) {
  102749. var _this = _super.call(this, name, scene) || this;
  102750. _this.name = name;
  102751. /**
  102752. * Specifies whether or not the inner glow is ACTIVE in the layer.
  102753. */
  102754. _this.innerGlow = true;
  102755. /**
  102756. * Specifies whether or not the outer glow is ACTIVE in the layer.
  102757. */
  102758. _this.outerGlow = true;
  102759. /**
  102760. * An event triggered when the highlight layer is being blurred.
  102761. */
  102762. _this.onBeforeBlurObservable = new BABYLON.Observable();
  102763. /**
  102764. * An event triggered when the highlight layer has been blurred.
  102765. */
  102766. _this.onAfterBlurObservable = new BABYLON.Observable();
  102767. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  102768. _this._meshes = {};
  102769. _this._excludedMeshes = {};
  102770. _this.neutralColor = HighlightLayer.NeutralColor;
  102771. // Warn on stencil
  102772. if (!_this._engine.isStencilEnable) {
  102773. 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 }");
  102774. }
  102775. // Adapt options
  102776. _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);
  102777. // Initialize the layer
  102778. _this._init({
  102779. alphaBlendingMode: _this._options.alphaBlendingMode,
  102780. camera: _this._options.camera,
  102781. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  102782. mainTextureRatio: _this._options.mainTextureRatio,
  102783. renderingGroupId: _this._options.renderingGroupId
  102784. });
  102785. // Do not render as long as no meshes have been added
  102786. _this._shouldRender = false;
  102787. return _this;
  102788. }
  102789. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  102790. /**
  102791. * Gets the horizontal size of the blur.
  102792. */
  102793. get: function () {
  102794. return this._horizontalBlurPostprocess.kernel;
  102795. },
  102796. /**
  102797. * Specifies the horizontal size of the blur.
  102798. */
  102799. set: function (value) {
  102800. this._horizontalBlurPostprocess.kernel = value;
  102801. },
  102802. enumerable: true,
  102803. configurable: true
  102804. });
  102805. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  102806. /**
  102807. * Gets the vertical size of the blur.
  102808. */
  102809. get: function () {
  102810. return this._verticalBlurPostprocess.kernel;
  102811. },
  102812. /**
  102813. * Specifies the vertical size of the blur.
  102814. */
  102815. set: function (value) {
  102816. this._verticalBlurPostprocess.kernel = value;
  102817. },
  102818. enumerable: true,
  102819. configurable: true
  102820. });
  102821. /**
  102822. * Get the effect name of the layer.
  102823. * @return The effect name
  102824. */
  102825. HighlightLayer.prototype.getEffectName = function () {
  102826. return HighlightLayer.EffectName;
  102827. };
  102828. /**
  102829. * Create the merge effect. This is the shader use to blit the information back
  102830. * to the main canvas at the end of the scene rendering.
  102831. */
  102832. HighlightLayer.prototype._createMergeEffect = function () {
  102833. // Effect
  102834. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  102835. };
  102836. /**
  102837. * Creates the render target textures and post processes used in the highlight layer.
  102838. */
  102839. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  102840. var _this = this;
  102841. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  102842. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  102843. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  102844. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  102845. var textureType = 0;
  102846. if (this._engine.getCaps().textureHalfFloatRender) {
  102847. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  102848. }
  102849. else {
  102850. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  102851. }
  102852. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  102853. width: blurTextureWidth,
  102854. height: blurTextureHeight
  102855. }, this._scene, false, true, textureType);
  102856. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102857. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102858. this._blurTexture.anisotropicFilteringLevel = 16;
  102859. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  102860. this._blurTexture.renderParticles = false;
  102861. this._blurTexture.ignoreCameraViewport = true;
  102862. this._textures = [this._blurTexture];
  102863. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  102864. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  102865. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  102866. effect.setTexture("textureSampler", _this._mainTexture);
  102867. });
  102868. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  102869. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  102870. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  102871. });
  102872. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  102873. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  102874. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  102875. });
  102876. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  102877. }
  102878. else {
  102879. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  102880. width: blurTextureWidth,
  102881. height: blurTextureHeight
  102882. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102883. this._horizontalBlurPostprocess.width = blurTextureWidth;
  102884. this._horizontalBlurPostprocess.height = blurTextureHeight;
  102885. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  102886. effect.setTexture("textureSampler", _this._mainTexture);
  102887. });
  102888. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  102889. width: blurTextureWidth,
  102890. height: blurTextureHeight
  102891. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102892. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  102893. }
  102894. this._mainTexture.onAfterUnbindObservable.add(function () {
  102895. _this.onBeforeBlurObservable.notifyObservers(_this);
  102896. var internalTexture = _this._blurTexture.getInternalTexture();
  102897. if (internalTexture) {
  102898. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  102899. }
  102900. _this.onAfterBlurObservable.notifyObservers(_this);
  102901. });
  102902. // Prevent autoClear.
  102903. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  102904. };
  102905. /**
  102906. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  102907. */
  102908. HighlightLayer.prototype.needStencil = function () {
  102909. return true;
  102910. };
  102911. /**
  102912. * Checks for the readiness of the element composing the layer.
  102913. * @param subMesh the mesh to check for
  102914. * @param useInstances specify wether or not to use instances to render the mesh
  102915. * @param emissiveTexture the associated emissive texture used to generate the glow
  102916. * @return true if ready otherwise, false
  102917. */
  102918. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  102919. var material = subMesh.getMaterial();
  102920. var mesh = subMesh.getRenderingMesh();
  102921. if (!material || !mesh || !this._meshes) {
  102922. return false;
  102923. }
  102924. var emissiveTexture = null;
  102925. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  102926. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  102927. emissiveTexture = material.emissiveTexture;
  102928. }
  102929. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  102930. };
  102931. /**
  102932. * Implementation specific of rendering the generating effect on the main canvas.
  102933. * @param effect The effect used to render through
  102934. */
  102935. HighlightLayer.prototype._internalRender = function (effect) {
  102936. // Texture
  102937. effect.setTexture("textureSampler", this._blurTexture);
  102938. // Cache
  102939. var engine = this._engine;
  102940. var previousStencilBuffer = engine.getStencilBuffer();
  102941. var previousStencilFunction = engine.getStencilFunction();
  102942. var previousStencilMask = engine.getStencilMask();
  102943. var previousStencilOperationPass = engine.getStencilOperationPass();
  102944. var previousStencilOperationFail = engine.getStencilOperationFail();
  102945. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  102946. var previousStencilReference = engine.getStencilFunctionReference();
  102947. // Stencil operations
  102948. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  102949. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  102950. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  102951. // Draw order
  102952. engine.setStencilMask(0x00);
  102953. engine.setStencilBuffer(true);
  102954. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  102955. // 2 passes inner outer
  102956. if (this.outerGlow) {
  102957. effect.setFloat("offset", 0);
  102958. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  102959. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102960. }
  102961. if (this.innerGlow) {
  102962. effect.setFloat("offset", 1);
  102963. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  102964. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102965. }
  102966. // Restore Cache
  102967. engine.setStencilFunction(previousStencilFunction);
  102968. engine.setStencilMask(previousStencilMask);
  102969. engine.setStencilBuffer(previousStencilBuffer);
  102970. engine.setStencilOperationPass(previousStencilOperationPass);
  102971. engine.setStencilOperationFail(previousStencilOperationFail);
  102972. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  102973. engine.setStencilFunctionReference(previousStencilReference);
  102974. };
  102975. /**
  102976. * Returns true if the layer contains information to display, otherwise false.
  102977. */
  102978. HighlightLayer.prototype.shouldRender = function () {
  102979. if (_super.prototype.shouldRender.call(this)) {
  102980. return this._meshes ? true : false;
  102981. }
  102982. return false;
  102983. };
  102984. /**
  102985. * Returns true if the mesh should render, otherwise false.
  102986. * @param mesh The mesh to render
  102987. * @returns true if it should render otherwise false
  102988. */
  102989. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  102990. // Excluded Mesh
  102991. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  102992. return false;
  102993. }
  102994. ;
  102995. if (!_super.prototype.hasMesh.call(this, mesh)) {
  102996. return false;
  102997. }
  102998. return true;
  102999. };
  103000. /**
  103001. * Sets the required values for both the emissive texture and and the main color.
  103002. */
  103003. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  103004. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  103005. if (highlightLayerMesh) {
  103006. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  103007. }
  103008. else {
  103009. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  103010. }
  103011. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  103012. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  103013. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  103014. }
  103015. else {
  103016. this._emissiveTextureAndColor.texture = null;
  103017. }
  103018. };
  103019. /**
  103020. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  103021. * @param mesh The mesh to exclude from the highlight layer
  103022. */
  103023. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  103024. if (!this._excludedMeshes) {
  103025. return;
  103026. }
  103027. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  103028. if (!meshExcluded) {
  103029. this._excludedMeshes[mesh.uniqueId] = {
  103030. mesh: mesh,
  103031. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  103032. mesh.getEngine().setStencilBuffer(false);
  103033. }),
  103034. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  103035. mesh.getEngine().setStencilBuffer(true);
  103036. }),
  103037. };
  103038. }
  103039. };
  103040. /**
  103041. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  103042. * @param mesh The mesh to highlight
  103043. */
  103044. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  103045. if (!this._excludedMeshes) {
  103046. return;
  103047. }
  103048. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  103049. if (meshExcluded) {
  103050. if (meshExcluded.beforeRender) {
  103051. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  103052. }
  103053. if (meshExcluded.afterRender) {
  103054. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  103055. }
  103056. }
  103057. this._excludedMeshes[mesh.uniqueId] = null;
  103058. };
  103059. /**
  103060. * Determine if a given mesh will be highlighted by the current HighlightLayer
  103061. * @param mesh mesh to test
  103062. * @returns true if the mesh will be highlighted by the current HighlightLayer
  103063. */
  103064. HighlightLayer.prototype.hasMesh = function (mesh) {
  103065. if (!this._meshes) {
  103066. return false;
  103067. }
  103068. if (!_super.prototype.hasMesh.call(this, mesh)) {
  103069. return false;
  103070. }
  103071. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  103072. };
  103073. /**
  103074. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  103075. * @param mesh The mesh to highlight
  103076. * @param color The color of the highlight
  103077. * @param glowEmissiveOnly Extract the glow from the emissive texture
  103078. */
  103079. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  103080. var _this = this;
  103081. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  103082. if (!this._meshes) {
  103083. return;
  103084. }
  103085. var meshHighlight = this._meshes[mesh.uniqueId];
  103086. if (meshHighlight) {
  103087. meshHighlight.color = color;
  103088. }
  103089. else {
  103090. this._meshes[mesh.uniqueId] = {
  103091. mesh: mesh,
  103092. color: color,
  103093. // Lambda required for capture due to Observable this context
  103094. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  103095. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  103096. _this._defaultStencilReference(mesh);
  103097. }
  103098. else {
  103099. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  103100. }
  103101. }),
  103102. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  103103. glowEmissiveOnly: glowEmissiveOnly
  103104. };
  103105. mesh.onDisposeObservable.add(function () {
  103106. _this._disposeMesh(mesh);
  103107. });
  103108. }
  103109. this._shouldRender = true;
  103110. };
  103111. /**
  103112. * Remove a mesh from the highlight layer in order to make it stop glowing.
  103113. * @param mesh The mesh to highlight
  103114. */
  103115. HighlightLayer.prototype.removeMesh = function (mesh) {
  103116. if (!this._meshes) {
  103117. return;
  103118. }
  103119. var meshHighlight = this._meshes[mesh.uniqueId];
  103120. if (meshHighlight) {
  103121. if (meshHighlight.observerHighlight) {
  103122. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  103123. }
  103124. if (meshHighlight.observerDefault) {
  103125. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  103126. }
  103127. delete this._meshes[mesh.uniqueId];
  103128. }
  103129. this._shouldRender = false;
  103130. for (var meshHighlightToCheck in this._meshes) {
  103131. if (this._meshes[meshHighlightToCheck]) {
  103132. this._shouldRender = true;
  103133. break;
  103134. }
  103135. }
  103136. };
  103137. /**
  103138. * Force the stencil to the normal expected value for none glowing parts
  103139. */
  103140. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  103141. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  103142. };
  103143. /**
  103144. * Free any resources and references associated to a mesh.
  103145. * Internal use
  103146. * @param mesh The mesh to free.
  103147. * @hidden
  103148. */
  103149. HighlightLayer.prototype._disposeMesh = function (mesh) {
  103150. this.removeMesh(mesh);
  103151. this.removeExcludedMesh(mesh);
  103152. };
  103153. /**
  103154. * Dispose the highlight layer and free resources.
  103155. */
  103156. HighlightLayer.prototype.dispose = function () {
  103157. if (this._meshes) {
  103158. // Clean mesh references
  103159. for (var id in this._meshes) {
  103160. var meshHighlight = this._meshes[id];
  103161. if (meshHighlight && meshHighlight.mesh) {
  103162. if (meshHighlight.observerHighlight) {
  103163. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  103164. }
  103165. if (meshHighlight.observerDefault) {
  103166. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  103167. }
  103168. }
  103169. }
  103170. this._meshes = null;
  103171. }
  103172. if (this._excludedMeshes) {
  103173. for (var id in this._excludedMeshes) {
  103174. var meshHighlight = this._excludedMeshes[id];
  103175. if (meshHighlight) {
  103176. if (meshHighlight.beforeRender) {
  103177. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  103178. }
  103179. if (meshHighlight.afterRender) {
  103180. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  103181. }
  103182. }
  103183. }
  103184. this._excludedMeshes = null;
  103185. }
  103186. _super.prototype.dispose.call(this);
  103187. };
  103188. /**
  103189. * Gets the class name of the effect layer
  103190. * @returns the string with the class name of the effect layer
  103191. */
  103192. HighlightLayer.prototype.getClassName = function () {
  103193. return "HighlightLayer";
  103194. };
  103195. /**
  103196. * Serializes this Highlight layer
  103197. * @returns a serialized Highlight layer object
  103198. */
  103199. HighlightLayer.prototype.serialize = function () {
  103200. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  103201. serializationObject.customType = "BABYLON.HighlightLayer";
  103202. // Highlighted meshes
  103203. serializationObject.meshes = [];
  103204. if (this._meshes) {
  103205. for (var m in this._meshes) {
  103206. var mesh = this._meshes[m];
  103207. if (mesh) {
  103208. serializationObject.meshes.push({
  103209. glowEmissiveOnly: mesh.glowEmissiveOnly,
  103210. color: mesh.color.asArray(),
  103211. meshId: mesh.mesh.id
  103212. });
  103213. }
  103214. }
  103215. }
  103216. // Excluded meshes
  103217. serializationObject.excludedMeshes = [];
  103218. if (this._excludedMeshes) {
  103219. for (var e in this._excludedMeshes) {
  103220. var excludedMesh = this._excludedMeshes[e];
  103221. if (excludedMesh) {
  103222. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  103223. }
  103224. }
  103225. }
  103226. return serializationObject;
  103227. };
  103228. /**
  103229. * Creates a Highlight layer from parsed Highlight layer data
  103230. * @param parsedHightlightLayer defines the Highlight layer data
  103231. * @param scene defines the current scene
  103232. * @param rootUrl defines the root URL containing the Highlight layer information
  103233. * @returns a parsed Highlight layer
  103234. */
  103235. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  103236. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  103237. var index;
  103238. // Excluded meshes
  103239. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  103240. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  103241. if (mesh) {
  103242. hl.addExcludedMesh(mesh);
  103243. }
  103244. }
  103245. // Included meshes
  103246. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  103247. var highlightedMesh = parsedHightlightLayer.meshes[index];
  103248. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  103249. if (mesh) {
  103250. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  103251. }
  103252. }
  103253. return hl;
  103254. };
  103255. /**
  103256. * Effect Name of the highlight layer.
  103257. */
  103258. HighlightLayer.EffectName = "HighlightLayer";
  103259. /**
  103260. * The neutral color used during the preparation of the glow effect.
  103261. * This is black by default as the blend operation is a blend operation.
  103262. */
  103263. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  103264. /**
  103265. * Stencil value used for glowing meshes.
  103266. */
  103267. HighlightLayer.GlowingMeshStencilReference = 0x02;
  103268. /**
  103269. * Stencil value used for the other meshes in the scene.
  103270. */
  103271. HighlightLayer.NormalMeshStencilReference = 0x01;
  103272. __decorate([
  103273. BABYLON.serialize()
  103274. ], HighlightLayer.prototype, "innerGlow", void 0);
  103275. __decorate([
  103276. BABYLON.serialize()
  103277. ], HighlightLayer.prototype, "outerGlow", void 0);
  103278. __decorate([
  103279. BABYLON.serialize()
  103280. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  103281. __decorate([
  103282. BABYLON.serialize()
  103283. ], HighlightLayer.prototype, "blurVerticalSize", null);
  103284. __decorate([
  103285. BABYLON.serialize("options")
  103286. ], HighlightLayer.prototype, "_options", void 0);
  103287. return HighlightLayer;
  103288. }(BABYLON.EffectLayer));
  103289. BABYLON.HighlightLayer = HighlightLayer;
  103290. })(BABYLON || (BABYLON = {}));
  103291. //# sourceMappingURL=babylon.highlightLayer.js.map
  103292. var BABYLON;
  103293. (function (BABYLON) {
  103294. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  103295. for (var index = 0; index < this.effectLayers.length; index++) {
  103296. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  103297. return this.effectLayers[index];
  103298. }
  103299. }
  103300. return null;
  103301. };
  103302. /**
  103303. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  103304. *
  103305. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  103306. * glowy meshes to your scene.
  103307. *
  103308. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  103309. */
  103310. var GlowLayer = /** @class */ (function (_super) {
  103311. __extends(GlowLayer, _super);
  103312. /**
  103313. * Instantiates a new glow Layer and references it to the scene.
  103314. * @param name The name of the layer
  103315. * @param scene The scene to use the layer in
  103316. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  103317. */
  103318. function GlowLayer(name, scene, options) {
  103319. var _this = _super.call(this, name, scene) || this;
  103320. _this._intensity = 1.0;
  103321. _this._includedOnlyMeshes = [];
  103322. _this._excludedMeshes = [];
  103323. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  103324. // Adapt options
  103325. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  103326. // Initialize the layer
  103327. _this._init({
  103328. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  103329. camera: _this._options.camera,
  103330. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  103331. mainTextureRatio: _this._options.mainTextureRatio,
  103332. renderingGroupId: _this._options.renderingGroupId
  103333. });
  103334. return _this;
  103335. }
  103336. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  103337. /**
  103338. * Gets the kernel size of the blur.
  103339. */
  103340. get: function () {
  103341. return this._horizontalBlurPostprocess1.kernel;
  103342. },
  103343. /**
  103344. * Sets the kernel size of the blur.
  103345. */
  103346. set: function (value) {
  103347. this._horizontalBlurPostprocess1.kernel = value;
  103348. this._verticalBlurPostprocess1.kernel = value;
  103349. this._horizontalBlurPostprocess2.kernel = value;
  103350. this._verticalBlurPostprocess2.kernel = value;
  103351. },
  103352. enumerable: true,
  103353. configurable: true
  103354. });
  103355. Object.defineProperty(GlowLayer.prototype, "intensity", {
  103356. /**
  103357. * Gets the glow intensity.
  103358. */
  103359. get: function () {
  103360. return this._intensity;
  103361. },
  103362. /**
  103363. * Sets the glow intensity.
  103364. */
  103365. set: function (value) {
  103366. this._intensity = value;
  103367. },
  103368. enumerable: true,
  103369. configurable: true
  103370. });
  103371. /**
  103372. * Get the effect name of the layer.
  103373. * @return The effect name
  103374. */
  103375. GlowLayer.prototype.getEffectName = function () {
  103376. return GlowLayer.EffectName;
  103377. };
  103378. /**
  103379. * Create the merge effect. This is the shader use to blit the information back
  103380. * to the main canvas at the end of the scene rendering.
  103381. */
  103382. GlowLayer.prototype._createMergeEffect = function () {
  103383. // Effect
  103384. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  103385. };
  103386. /**
  103387. * Creates the render target textures and post processes used in the glow layer.
  103388. */
  103389. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  103390. var _this = this;
  103391. var blurTextureWidth = this._mainTextureDesiredSize.width;
  103392. var blurTextureHeight = this._mainTextureDesiredSize.height;
  103393. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  103394. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  103395. var textureType = 0;
  103396. if (this._engine.getCaps().textureHalfFloatRender) {
  103397. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  103398. }
  103399. else {
  103400. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  103401. }
  103402. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  103403. width: blurTextureWidth,
  103404. height: blurTextureHeight
  103405. }, this._scene, false, true, textureType);
  103406. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103407. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103408. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  103409. this._blurTexture1.renderParticles = false;
  103410. this._blurTexture1.ignoreCameraViewport = true;
  103411. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  103412. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  103413. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  103414. width: blurTextureWidth2,
  103415. height: blurTextureHeight2
  103416. }, this._scene, false, true, textureType);
  103417. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103418. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103419. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  103420. this._blurTexture2.renderParticles = false;
  103421. this._blurTexture2.ignoreCameraViewport = true;
  103422. this._textures = [this._blurTexture1, this._blurTexture2];
  103423. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  103424. width: blurTextureWidth,
  103425. height: blurTextureHeight
  103426. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103427. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  103428. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  103429. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  103430. effect.setTexture("textureSampler", _this._mainTexture);
  103431. });
  103432. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  103433. width: blurTextureWidth,
  103434. height: blurTextureHeight
  103435. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103436. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  103437. width: blurTextureWidth2,
  103438. height: blurTextureHeight2
  103439. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103440. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  103441. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  103442. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  103443. effect.setTexture("textureSampler", _this._blurTexture1);
  103444. });
  103445. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  103446. width: blurTextureWidth2,
  103447. height: blurTextureHeight2
  103448. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  103449. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  103450. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  103451. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  103452. this._mainTexture.samples = this._options.mainTextureSamples;
  103453. this._mainTexture.onAfterUnbindObservable.add(function () {
  103454. var internalTexture = _this._blurTexture1.getInternalTexture();
  103455. if (internalTexture) {
  103456. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  103457. internalTexture = _this._blurTexture2.getInternalTexture();
  103458. if (internalTexture) {
  103459. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  103460. }
  103461. }
  103462. });
  103463. // Prevent autoClear.
  103464. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  103465. };
  103466. /**
  103467. * Checks for the readiness of the element composing the layer.
  103468. * @param subMesh the mesh to check for
  103469. * @param useInstances specify wether or not to use instances to render the mesh
  103470. * @param emissiveTexture the associated emissive texture used to generate the glow
  103471. * @return true if ready otherwise, false
  103472. */
  103473. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  103474. var material = subMesh.getMaterial();
  103475. var mesh = subMesh.getRenderingMesh();
  103476. if (!material || !mesh) {
  103477. return false;
  103478. }
  103479. var emissiveTexture = material.emissiveTexture;
  103480. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  103481. };
  103482. /**
  103483. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  103484. */
  103485. GlowLayer.prototype.needStencil = function () {
  103486. return false;
  103487. };
  103488. /**
  103489. * Implementation specific of rendering the generating effect on the main canvas.
  103490. * @param effect The effect used to render through
  103491. */
  103492. GlowLayer.prototype._internalRender = function (effect) {
  103493. // Texture
  103494. effect.setTexture("textureSampler", this._blurTexture1);
  103495. effect.setTexture("textureSampler2", this._blurTexture2);
  103496. effect.setFloat("offset", this._intensity);
  103497. // Cache
  103498. var engine = this._engine;
  103499. var previousStencilBuffer = engine.getStencilBuffer();
  103500. // Draw order
  103501. engine.setStencilBuffer(false);
  103502. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  103503. // Draw order
  103504. engine.setStencilBuffer(previousStencilBuffer);
  103505. };
  103506. /**
  103507. * Sets the required values for both the emissive texture and and the main color.
  103508. */
  103509. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  103510. var textureLevel = 1.0;
  103511. if (this.customEmissiveTextureSelector) {
  103512. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  103513. }
  103514. else {
  103515. if (material) {
  103516. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  103517. if (this._emissiveTextureAndColor.texture) {
  103518. textureLevel = this._emissiveTextureAndColor.texture.level;
  103519. }
  103520. }
  103521. else {
  103522. this._emissiveTextureAndColor.texture = null;
  103523. }
  103524. }
  103525. if (this.customEmissiveColorSelector) {
  103526. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  103527. }
  103528. else {
  103529. if (material.emissiveColor) {
  103530. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  103531. }
  103532. else {
  103533. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  103534. }
  103535. }
  103536. };
  103537. /**
  103538. * Returns true if the mesh should render, otherwise false.
  103539. * @param mesh The mesh to render
  103540. * @returns true if it should render otherwise false
  103541. */
  103542. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  103543. return this.hasMesh(mesh);
  103544. };
  103545. /**
  103546. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  103547. * @param mesh The mesh to exclude from the glow layer
  103548. */
  103549. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  103550. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  103551. this._excludedMeshes.push(mesh.uniqueId);
  103552. }
  103553. };
  103554. /**
  103555. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  103556. * @param mesh The mesh to remove
  103557. */
  103558. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  103559. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  103560. if (index !== -1) {
  103561. this._excludedMeshes.splice(index, 1);
  103562. }
  103563. };
  103564. /**
  103565. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  103566. * @param mesh The mesh to include in the glow layer
  103567. */
  103568. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  103569. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  103570. this._includedOnlyMeshes.push(mesh.uniqueId);
  103571. }
  103572. };
  103573. /**
  103574. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  103575. * @param mesh The mesh to remove
  103576. */
  103577. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  103578. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  103579. if (index !== -1) {
  103580. this._includedOnlyMeshes.splice(index, 1);
  103581. }
  103582. };
  103583. /**
  103584. * Determine if a given mesh will be used in the glow layer
  103585. * @param mesh The mesh to test
  103586. * @returns true if the mesh will be highlighted by the current glow layer
  103587. */
  103588. GlowLayer.prototype.hasMesh = function (mesh) {
  103589. if (!_super.prototype.hasMesh.call(this, mesh)) {
  103590. return false;
  103591. }
  103592. // Included Mesh
  103593. if (this._includedOnlyMeshes.length) {
  103594. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  103595. }
  103596. ;
  103597. // Excluded Mesh
  103598. if (this._excludedMeshes.length) {
  103599. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  103600. }
  103601. ;
  103602. return true;
  103603. };
  103604. /**
  103605. * Free any resources and references associated to a mesh.
  103606. * Internal use
  103607. * @param mesh The mesh to free.
  103608. * @hidden
  103609. */
  103610. GlowLayer.prototype._disposeMesh = function (mesh) {
  103611. this.removeIncludedOnlyMesh(mesh);
  103612. this.removeExcludedMesh(mesh);
  103613. };
  103614. /**
  103615. * Gets the class name of the effect layer
  103616. * @returns the string with the class name of the effect layer
  103617. */
  103618. GlowLayer.prototype.getClassName = function () {
  103619. return "GlowLayer";
  103620. };
  103621. /**
  103622. * Serializes this glow layer
  103623. * @returns a serialized glow layer object
  103624. */
  103625. GlowLayer.prototype.serialize = function () {
  103626. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  103627. serializationObject.customType = "BABYLON.GlowLayer";
  103628. var index;
  103629. // Included meshes
  103630. serializationObject.includedMeshes = [];
  103631. if (this._includedOnlyMeshes.length) {
  103632. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  103633. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  103634. if (mesh) {
  103635. serializationObject.includedMeshes.push(mesh.id);
  103636. }
  103637. }
  103638. }
  103639. // Excluded meshes
  103640. serializationObject.excludedMeshes = [];
  103641. if (this._excludedMeshes.length) {
  103642. for (index = 0; index < this._excludedMeshes.length; index++) {
  103643. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  103644. if (mesh) {
  103645. serializationObject.excludedMeshes.push(mesh.id);
  103646. }
  103647. }
  103648. }
  103649. return serializationObject;
  103650. };
  103651. /**
  103652. * Creates a Glow Layer from parsed glow layer data
  103653. * @param parsedGlowLayer defines glow layer data
  103654. * @param scene defines the current scene
  103655. * @param rootUrl defines the root URL containing the glow layer information
  103656. * @returns a parsed Glow Layer
  103657. */
  103658. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  103659. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  103660. var index;
  103661. // Excluded meshes
  103662. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  103663. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  103664. if (mesh) {
  103665. gl.addExcludedMesh(mesh);
  103666. }
  103667. }
  103668. // Included meshes
  103669. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  103670. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  103671. if (mesh) {
  103672. gl.addIncludedOnlyMesh(mesh);
  103673. }
  103674. }
  103675. return gl;
  103676. };
  103677. /**
  103678. * Effect Name of the layer.
  103679. */
  103680. GlowLayer.EffectName = "GlowLayer";
  103681. /**
  103682. * The default blur kernel size used for the glow.
  103683. */
  103684. GlowLayer.DefaultBlurKernelSize = 32;
  103685. /**
  103686. * The default texture size ratio used for the glow.
  103687. */
  103688. GlowLayer.DefaultTextureRatio = 0.5;
  103689. __decorate([
  103690. BABYLON.serialize()
  103691. ], GlowLayer.prototype, "blurKernelSize", null);
  103692. __decorate([
  103693. BABYLON.serialize()
  103694. ], GlowLayer.prototype, "intensity", null);
  103695. __decorate([
  103696. BABYLON.serialize("options")
  103697. ], GlowLayer.prototype, "_options", void 0);
  103698. return GlowLayer;
  103699. }(BABYLON.EffectLayer));
  103700. BABYLON.GlowLayer = GlowLayer;
  103701. })(BABYLON || (BABYLON = {}));
  103702. //# sourceMappingURL=babylon.glowLayer.js.map
  103703. var BABYLON;
  103704. (function (BABYLON) {
  103705. /**
  103706. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  103707. */
  103708. var AssetTaskState;
  103709. (function (AssetTaskState) {
  103710. /**
  103711. * Initialization
  103712. */
  103713. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  103714. /**
  103715. * Running
  103716. */
  103717. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  103718. /**
  103719. * Done
  103720. */
  103721. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  103722. /**
  103723. * Error
  103724. */
  103725. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  103726. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  103727. /**
  103728. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  103729. */
  103730. var AbstractAssetTask = /** @class */ (function () {
  103731. /**
  103732. * Creates a new {BABYLON.AssetsManager}
  103733. * @param name defines the name of the task
  103734. */
  103735. function AbstractAssetTask(
  103736. /**
  103737. * Task name
  103738. */ name) {
  103739. this.name = name;
  103740. this._isCompleted = false;
  103741. this._taskState = AssetTaskState.INIT;
  103742. }
  103743. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  103744. /**
  103745. * Get if the task is completed
  103746. */
  103747. get: function () {
  103748. return this._isCompleted;
  103749. },
  103750. enumerable: true,
  103751. configurable: true
  103752. });
  103753. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  103754. /**
  103755. * Gets the current state of the task
  103756. */
  103757. get: function () {
  103758. return this._taskState;
  103759. },
  103760. enumerable: true,
  103761. configurable: true
  103762. });
  103763. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  103764. /**
  103765. * Gets the current error object (if task is in error)
  103766. */
  103767. get: function () {
  103768. return this._errorObject;
  103769. },
  103770. enumerable: true,
  103771. configurable: true
  103772. });
  103773. /**
  103774. * Internal only
  103775. * @hidden
  103776. */
  103777. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  103778. if (this._errorObject) {
  103779. return;
  103780. }
  103781. this._errorObject = {
  103782. message: message,
  103783. exception: exception
  103784. };
  103785. };
  103786. /**
  103787. * Execute the current task
  103788. * @param scene defines the scene where you want your assets to be loaded
  103789. * @param onSuccess is a callback called when the task is successfully executed
  103790. * @param onError is a callback called if an error occurs
  103791. */
  103792. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  103793. var _this = this;
  103794. this._taskState = AssetTaskState.RUNNING;
  103795. this.runTask(scene, function () {
  103796. _this.onDoneCallback(onSuccess, onError);
  103797. }, function (msg, exception) {
  103798. _this.onErrorCallback(onError, msg, exception);
  103799. });
  103800. };
  103801. /**
  103802. * Execute the current task
  103803. * @param scene defines the scene where you want your assets to be loaded
  103804. * @param onSuccess is a callback called when the task is successfully executed
  103805. * @param onError is a callback called if an error occurs
  103806. */
  103807. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103808. throw new Error("runTask is not implemented");
  103809. };
  103810. /**
  103811. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  103812. * This can be used with failed tasks that have the reason for failure fixed.
  103813. */
  103814. AbstractAssetTask.prototype.reset = function () {
  103815. this._taskState = AssetTaskState.INIT;
  103816. };
  103817. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  103818. this._taskState = AssetTaskState.ERROR;
  103819. this._errorObject = {
  103820. message: message,
  103821. exception: exception
  103822. };
  103823. if (this.onError) {
  103824. this.onError(this, message, exception);
  103825. }
  103826. onError();
  103827. };
  103828. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  103829. try {
  103830. this._taskState = AssetTaskState.DONE;
  103831. this._isCompleted = true;
  103832. if (this.onSuccess) {
  103833. this.onSuccess(this);
  103834. }
  103835. onSuccess();
  103836. }
  103837. catch (e) {
  103838. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  103839. }
  103840. };
  103841. return AbstractAssetTask;
  103842. }());
  103843. BABYLON.AbstractAssetTask = AbstractAssetTask;
  103844. /**
  103845. * Class used to share progress information about assets loading
  103846. */
  103847. var AssetsProgressEvent = /** @class */ (function () {
  103848. /**
  103849. * Creates a {BABYLON.AssetsProgressEvent}
  103850. * @param remainingCount defines the number of remaining tasks to process
  103851. * @param totalCount defines the total number of tasks
  103852. * @param task defines the task that was just processed
  103853. */
  103854. function AssetsProgressEvent(remainingCount, totalCount, task) {
  103855. this.remainingCount = remainingCount;
  103856. this.totalCount = totalCount;
  103857. this.task = task;
  103858. }
  103859. return AssetsProgressEvent;
  103860. }());
  103861. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  103862. /**
  103863. * Define a task used by {BABYLON.AssetsManager} to load meshes
  103864. */
  103865. var MeshAssetTask = /** @class */ (function (_super) {
  103866. __extends(MeshAssetTask, _super);
  103867. /**
  103868. * Creates a new {BABYLON.MeshAssetTask}
  103869. * @param name defines the name of the task
  103870. * @param meshesNames defines the list of mesh's names you want to load
  103871. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  103872. * @param sceneFilename defines the filename of the scene to load from
  103873. */
  103874. function MeshAssetTask(
  103875. /**
  103876. * Defines the name of the task
  103877. */
  103878. name,
  103879. /**
  103880. * Defines the list of mesh's names you want to load
  103881. */
  103882. meshesNames,
  103883. /**
  103884. * Defines the root url to use as a base to load your meshes and associated resources
  103885. */
  103886. rootUrl,
  103887. /**
  103888. * Defines the filename of the scene to load from
  103889. */
  103890. sceneFilename) {
  103891. var _this = _super.call(this, name) || this;
  103892. _this.name = name;
  103893. _this.meshesNames = meshesNames;
  103894. _this.rootUrl = rootUrl;
  103895. _this.sceneFilename = sceneFilename;
  103896. return _this;
  103897. }
  103898. /**
  103899. * Execute the current task
  103900. * @param scene defines the scene where you want your assets to be loaded
  103901. * @param onSuccess is a callback called when the task is successfully executed
  103902. * @param onError is a callback called if an error occurs
  103903. */
  103904. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103905. var _this = this;
  103906. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  103907. _this.loadedMeshes = meshes;
  103908. _this.loadedParticleSystems = particleSystems;
  103909. _this.loadedSkeletons = skeletons;
  103910. onSuccess();
  103911. }, null, function (scene, message, exception) {
  103912. onError(message, exception);
  103913. });
  103914. };
  103915. return MeshAssetTask;
  103916. }(AbstractAssetTask));
  103917. BABYLON.MeshAssetTask = MeshAssetTask;
  103918. /**
  103919. * Define a task used by {BABYLON.AssetsManager} to load text content
  103920. */
  103921. var TextFileAssetTask = /** @class */ (function (_super) {
  103922. __extends(TextFileAssetTask, _super);
  103923. /**
  103924. * Creates a new TextFileAssetTask object
  103925. * @param name defines the name of the task
  103926. * @param url defines the location of the file to load
  103927. */
  103928. function TextFileAssetTask(
  103929. /**
  103930. * Defines the name of the task
  103931. */
  103932. name,
  103933. /**
  103934. * Defines the location of the file to load
  103935. */
  103936. url) {
  103937. var _this = _super.call(this, name) || this;
  103938. _this.name = name;
  103939. _this.url = url;
  103940. return _this;
  103941. }
  103942. /**
  103943. * Execute the current task
  103944. * @param scene defines the scene where you want your assets to be loaded
  103945. * @param onSuccess is a callback called when the task is successfully executed
  103946. * @param onError is a callback called if an error occurs
  103947. */
  103948. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103949. var _this = this;
  103950. scene._loadFile(this.url, function (data) {
  103951. _this.text = data;
  103952. onSuccess();
  103953. }, undefined, false, false, function (request, exception) {
  103954. if (request) {
  103955. onError(request.status + " " + request.statusText, exception);
  103956. }
  103957. });
  103958. };
  103959. return TextFileAssetTask;
  103960. }(AbstractAssetTask));
  103961. BABYLON.TextFileAssetTask = TextFileAssetTask;
  103962. /**
  103963. * Define a task used by {BABYLON.AssetsManager} to load binary data
  103964. */
  103965. var BinaryFileAssetTask = /** @class */ (function (_super) {
  103966. __extends(BinaryFileAssetTask, _super);
  103967. /**
  103968. * Creates a new BinaryFileAssetTask object
  103969. * @param name defines the name of the new task
  103970. * @param url defines the location of the file to load
  103971. */
  103972. function BinaryFileAssetTask(
  103973. /**
  103974. * Defines the name of the task
  103975. */
  103976. name,
  103977. /**
  103978. * Defines the location of the file to load
  103979. */
  103980. url) {
  103981. var _this = _super.call(this, name) || this;
  103982. _this.name = name;
  103983. _this.url = url;
  103984. return _this;
  103985. }
  103986. /**
  103987. * Execute the current task
  103988. * @param scene defines the scene where you want your assets to be loaded
  103989. * @param onSuccess is a callback called when the task is successfully executed
  103990. * @param onError is a callback called if an error occurs
  103991. */
  103992. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103993. var _this = this;
  103994. scene._loadFile(this.url, function (data) {
  103995. _this.data = data;
  103996. onSuccess();
  103997. }, undefined, true, true, function (request, exception) {
  103998. if (request) {
  103999. onError(request.status + " " + request.statusText, exception);
  104000. }
  104001. });
  104002. };
  104003. return BinaryFileAssetTask;
  104004. }(AbstractAssetTask));
  104005. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  104006. /**
  104007. * Define a task used by {BABYLON.AssetsManager} to load images
  104008. */
  104009. var ImageAssetTask = /** @class */ (function (_super) {
  104010. __extends(ImageAssetTask, _super);
  104011. /**
  104012. * Creates a new ImageAssetTask
  104013. * @param name defines the name of the task
  104014. * @param url defines the location of the image to load
  104015. */
  104016. function ImageAssetTask(
  104017. /**
  104018. * Defines the name of the task
  104019. */
  104020. name,
  104021. /**
  104022. * Defines the location of the image to load
  104023. */
  104024. url) {
  104025. var _this = _super.call(this, name) || this;
  104026. _this.name = name;
  104027. _this.url = url;
  104028. return _this;
  104029. }
  104030. /**
  104031. * Execute the current task
  104032. * @param scene defines the scene where you want your assets to be loaded
  104033. * @param onSuccess is a callback called when the task is successfully executed
  104034. * @param onError is a callback called if an error occurs
  104035. */
  104036. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104037. var _this = this;
  104038. var img = new Image();
  104039. BABYLON.Tools.SetCorsBehavior(this.url, img);
  104040. img.onload = function () {
  104041. _this.image = img;
  104042. onSuccess();
  104043. };
  104044. img.onerror = function (err) {
  104045. onError("Error loading image", err);
  104046. };
  104047. img.src = this.url;
  104048. };
  104049. return ImageAssetTask;
  104050. }(AbstractAssetTask));
  104051. BABYLON.ImageAssetTask = ImageAssetTask;
  104052. /**
  104053. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  104054. */
  104055. var TextureAssetTask = /** @class */ (function (_super) {
  104056. __extends(TextureAssetTask, _super);
  104057. /**
  104058. * Creates a new TextureAssetTask object
  104059. * @param name defines the name of the task
  104060. * @param url defines the location of the file to load
  104061. * @param noMipmap defines if mipmap should not be generated (default is false)
  104062. * @param invertY defines if texture must be inverted on Y axis (default is false)
  104063. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  104064. */
  104065. function TextureAssetTask(
  104066. /**
  104067. * Defines the name of the task
  104068. */
  104069. name,
  104070. /**
  104071. * Defines the location of the file to load
  104072. */
  104073. url,
  104074. /**
  104075. * Defines if mipmap should not be generated (default is false)
  104076. */
  104077. noMipmap,
  104078. /**
  104079. * Defines if texture must be inverted on Y axis (default is false)
  104080. */
  104081. invertY,
  104082. /**
  104083. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  104084. */
  104085. samplingMode) {
  104086. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  104087. var _this = _super.call(this, name) || this;
  104088. _this.name = name;
  104089. _this.url = url;
  104090. _this.noMipmap = noMipmap;
  104091. _this.invertY = invertY;
  104092. _this.samplingMode = samplingMode;
  104093. return _this;
  104094. }
  104095. /**
  104096. * Execute the current task
  104097. * @param scene defines the scene where you want your assets to be loaded
  104098. * @param onSuccess is a callback called when the task is successfully executed
  104099. * @param onError is a callback called if an error occurs
  104100. */
  104101. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104102. var onload = function () {
  104103. onSuccess();
  104104. };
  104105. var onerror = function (message, exception) {
  104106. onError(message, exception);
  104107. };
  104108. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  104109. };
  104110. return TextureAssetTask;
  104111. }(AbstractAssetTask));
  104112. BABYLON.TextureAssetTask = TextureAssetTask;
  104113. /**
  104114. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  104115. */
  104116. var CubeTextureAssetTask = /** @class */ (function (_super) {
  104117. __extends(CubeTextureAssetTask, _super);
  104118. /**
  104119. * Creates a new CubeTextureAssetTask
  104120. * @param name defines the name of the task
  104121. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  104122. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  104123. * @param noMipmap defines if mipmaps should not be generated (default is false)
  104124. * @param files defines the explicit list of files (undefined by default)
  104125. */
  104126. function CubeTextureAssetTask(
  104127. /**
  104128. * Defines the name of the task
  104129. */
  104130. name,
  104131. /**
  104132. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  104133. */
  104134. url,
  104135. /**
  104136. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  104137. */
  104138. extensions,
  104139. /**
  104140. * Defines if mipmaps should not be generated (default is false)
  104141. */
  104142. noMipmap,
  104143. /**
  104144. * Defines the explicit list of files (undefined by default)
  104145. */
  104146. files) {
  104147. var _this = _super.call(this, name) || this;
  104148. _this.name = name;
  104149. _this.url = url;
  104150. _this.extensions = extensions;
  104151. _this.noMipmap = noMipmap;
  104152. _this.files = files;
  104153. return _this;
  104154. }
  104155. /**
  104156. * Execute the current task
  104157. * @param scene defines the scene where you want your assets to be loaded
  104158. * @param onSuccess is a callback called when the task is successfully executed
  104159. * @param onError is a callback called if an error occurs
  104160. */
  104161. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  104162. var onload = function () {
  104163. onSuccess();
  104164. };
  104165. var onerror = function (message, exception) {
  104166. onError(message, exception);
  104167. };
  104168. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  104169. };
  104170. return CubeTextureAssetTask;
  104171. }(AbstractAssetTask));
  104172. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  104173. /**
  104174. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  104175. */
  104176. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  104177. __extends(HDRCubeTextureAssetTask, _super);
  104178. /**
  104179. * Creates a new HDRCubeTextureAssetTask object
  104180. * @param name defines the name of the task
  104181. * @param url defines the location of the file to load
  104182. * @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.
  104183. * @param noMipmap defines if mipmaps should not be generated (default is false)
  104184. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  104185. * @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)
  104186. * @param reserved Internal use only
  104187. */
  104188. function HDRCubeTextureAssetTask(
  104189. /**
  104190. * Defines the name of the task
  104191. */
  104192. name,
  104193. /**
  104194. * Defines the location of the file to load
  104195. */
  104196. url,
  104197. /**
  104198. * Defines the desired size (the more it increases the longer the generation will be)
  104199. */
  104200. size,
  104201. /**
  104202. * Defines if mipmaps should not be generated (default is false)
  104203. */
  104204. noMipmap,
  104205. /**
  104206. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  104207. */
  104208. generateHarmonics,
  104209. /**
  104210. * 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)
  104211. */
  104212. gammaSpace,
  104213. /**
  104214. * Internal Use Only
  104215. */
  104216. reserved) {
  104217. if (noMipmap === void 0) { noMipmap = false; }
  104218. if (generateHarmonics === void 0) { generateHarmonics = true; }
  104219. if (gammaSpace === void 0) { gammaSpace = false; }
  104220. if (reserved === void 0) { reserved = false; }
  104221. var _this = _super.call(this, name) || this;
  104222. _this.name = name;
  104223. _this.url = url;
  104224. _this.size = size;
  104225. _this.noMipmap = noMipmap;
  104226. _this.generateHarmonics = generateHarmonics;
  104227. _this.gammaSpace = gammaSpace;
  104228. _this.reserved = reserved;
  104229. return _this;
  104230. }
  104231. /**
  104232. * Execute the current task
  104233. * @param scene defines the scene where you want your assets to be loaded
  104234. * @param onSuccess is a callback called when the task is successfully executed
  104235. * @param onError is a callback called if an error occurs
  104236. */
  104237. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  104238. var onload = function () {
  104239. onSuccess();
  104240. };
  104241. var onerror = function (message, exception) {
  104242. onError(message, exception);
  104243. };
  104244. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  104245. };
  104246. return HDRCubeTextureAssetTask;
  104247. }(AbstractAssetTask));
  104248. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  104249. /**
  104250. * This class can be used to easily import assets into a scene
  104251. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  104252. */
  104253. var AssetsManager = /** @class */ (function () {
  104254. /**
  104255. * Creates a new AssetsManager
  104256. * @param scene defines the scene to work on
  104257. */
  104258. function AssetsManager(scene) {
  104259. this._isLoading = false;
  104260. this._tasks = new Array();
  104261. this._waitingTasksCount = 0;
  104262. this._totalTasksCount = 0;
  104263. /**
  104264. * Observable called when all tasks are processed
  104265. */
  104266. this.onTaskSuccessObservable = new BABYLON.Observable();
  104267. /**
  104268. * Observable called when a task had an error
  104269. */
  104270. this.onTaskErrorObservable = new BABYLON.Observable();
  104271. /**
  104272. * Observable called when a task is successful
  104273. */
  104274. this.onTasksDoneObservable = new BABYLON.Observable();
  104275. /**
  104276. * Observable called when a task is done (whatever the result is)
  104277. */
  104278. this.onProgressObservable = new BABYLON.Observable();
  104279. /**
  104280. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  104281. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  104282. */
  104283. this.useDefaultLoadingScreen = true;
  104284. this._scene = scene;
  104285. }
  104286. /**
  104287. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  104288. * @param taskName defines the name of the new task
  104289. * @param meshesNames defines the name of meshes to load
  104290. * @param rootUrl defines the root url to use to locate files
  104291. * @param sceneFilename defines the filename of the scene file
  104292. * @returns a new {BABYLON.MeshAssetTask} object
  104293. */
  104294. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  104295. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  104296. this._tasks.push(task);
  104297. return task;
  104298. };
  104299. /**
  104300. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  104301. * @param taskName defines the name of the new task
  104302. * @param url defines the url of the file to load
  104303. * @returns a new {BABYLON.TextFileAssetTask} object
  104304. */
  104305. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  104306. var task = new TextFileAssetTask(taskName, url);
  104307. this._tasks.push(task);
  104308. return task;
  104309. };
  104310. /**
  104311. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  104312. * @param taskName defines the name of the new task
  104313. * @param url defines the url of the file to load
  104314. * @returns a new {BABYLON.BinaryFileAssetTask} object
  104315. */
  104316. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  104317. var task = new BinaryFileAssetTask(taskName, url);
  104318. this._tasks.push(task);
  104319. return task;
  104320. };
  104321. /**
  104322. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  104323. * @param taskName defines the name of the new task
  104324. * @param url defines the url of the file to load
  104325. * @returns a new {BABYLON.ImageAssetTask} object
  104326. */
  104327. AssetsManager.prototype.addImageTask = function (taskName, url) {
  104328. var task = new ImageAssetTask(taskName, url);
  104329. this._tasks.push(task);
  104330. return task;
  104331. };
  104332. /**
  104333. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  104334. * @param taskName defines the name of the new task
  104335. * @param url defines the url of the file to load
  104336. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  104337. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  104338. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  104339. * @returns a new {BABYLON.TextureAssetTask} object
  104340. */
  104341. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  104342. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  104343. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  104344. this._tasks.push(task);
  104345. return task;
  104346. };
  104347. /**
  104348. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  104349. * @param taskName defines the name of the new task
  104350. * @param url defines the url of the file to load
  104351. * @param extensions defines the extension to use to load the cube map (can be null)
  104352. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  104353. * @param files defines the list of files to load (can be null)
  104354. * @returns a new {BABYLON.CubeTextureAssetTask} object
  104355. */
  104356. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  104357. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  104358. this._tasks.push(task);
  104359. return task;
  104360. };
  104361. /**
  104362. *
  104363. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  104364. * @param taskName defines the name of the new task
  104365. * @param url defines the url of the file to load
  104366. * @param size defines the size you want for the cubemap (can be null)
  104367. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  104368. * @param generateHarmonics defines if you want to automatically generate (true by default)
  104369. * @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)
  104370. * @param reserved Internal use only
  104371. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  104372. */
  104373. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  104374. if (noMipmap === void 0) { noMipmap = false; }
  104375. if (generateHarmonics === void 0) { generateHarmonics = true; }
  104376. if (gammaSpace === void 0) { gammaSpace = false; }
  104377. if (reserved === void 0) { reserved = false; }
  104378. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  104379. this._tasks.push(task);
  104380. return task;
  104381. };
  104382. /**
  104383. * Remove a task from the assets manager.
  104384. * @param task the task to remove
  104385. */
  104386. AssetsManager.prototype.removeTask = function (task) {
  104387. var index = this._tasks.indexOf(task);
  104388. if (index > -1) {
  104389. this._tasks.splice(index, 1);
  104390. }
  104391. };
  104392. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  104393. this._waitingTasksCount--;
  104394. try {
  104395. if (this.onProgress) {
  104396. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  104397. }
  104398. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  104399. }
  104400. catch (e) {
  104401. BABYLON.Tools.Error("Error running progress callbacks.");
  104402. console.log(e);
  104403. }
  104404. if (this._waitingTasksCount === 0) {
  104405. try {
  104406. if (this.onFinish) {
  104407. this.onFinish(this._tasks);
  104408. }
  104409. // Let's remove successfull tasks
  104410. var currentTasks = this._tasks.slice();
  104411. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  104412. var task = currentTasks_1[_i];
  104413. if (task.taskState === AssetTaskState.DONE) {
  104414. var index = this._tasks.indexOf(task);
  104415. if (index > -1) {
  104416. this._tasks.splice(index, 1);
  104417. }
  104418. }
  104419. }
  104420. this.onTasksDoneObservable.notifyObservers(this._tasks);
  104421. }
  104422. catch (e) {
  104423. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  104424. console.log(e);
  104425. }
  104426. this._isLoading = false;
  104427. this._scene.getEngine().hideLoadingUI();
  104428. }
  104429. };
  104430. AssetsManager.prototype._runTask = function (task) {
  104431. var _this = this;
  104432. var done = function () {
  104433. try {
  104434. if (_this.onTaskSuccess) {
  104435. _this.onTaskSuccess(task);
  104436. }
  104437. _this.onTaskSuccessObservable.notifyObservers(task);
  104438. _this._decreaseWaitingTasksCount(task);
  104439. }
  104440. catch (e) {
  104441. error("Error executing task success callbacks", e);
  104442. }
  104443. };
  104444. var error = function (message, exception) {
  104445. task._setErrorObject(message, exception);
  104446. if (_this.onTaskError) {
  104447. _this.onTaskError(task);
  104448. }
  104449. _this.onTaskErrorObservable.notifyObservers(task);
  104450. _this._decreaseWaitingTasksCount(task);
  104451. };
  104452. task.run(this._scene, done, error);
  104453. };
  104454. /**
  104455. * Reset the {BABYLON.AssetsManager} and remove all tasks
  104456. * @return the current instance of the {BABYLON.AssetsManager}
  104457. */
  104458. AssetsManager.prototype.reset = function () {
  104459. this._isLoading = false;
  104460. this._tasks = new Array();
  104461. return this;
  104462. };
  104463. /**
  104464. * Start the loading process
  104465. * @return the current instance of the {BABYLON.AssetsManager}
  104466. */
  104467. AssetsManager.prototype.load = function () {
  104468. if (this._isLoading) {
  104469. return this;
  104470. }
  104471. this._isLoading = true;
  104472. this._waitingTasksCount = this._tasks.length;
  104473. this._totalTasksCount = this._tasks.length;
  104474. if (this._waitingTasksCount === 0) {
  104475. this._isLoading = false;
  104476. if (this.onFinish) {
  104477. this.onFinish(this._tasks);
  104478. }
  104479. this.onTasksDoneObservable.notifyObservers(this._tasks);
  104480. return this;
  104481. }
  104482. if (this.useDefaultLoadingScreen) {
  104483. this._scene.getEngine().displayLoadingUI();
  104484. }
  104485. for (var index = 0; index < this._tasks.length; index++) {
  104486. var task = this._tasks[index];
  104487. if (task.taskState === AssetTaskState.INIT) {
  104488. this._runTask(task);
  104489. }
  104490. }
  104491. return this;
  104492. };
  104493. return AssetsManager;
  104494. }());
  104495. BABYLON.AssetsManager = AssetsManager;
  104496. })(BABYLON || (BABYLON = {}));
  104497. //# sourceMappingURL=babylon.assetsManager.js.map
  104498. var BABYLON;
  104499. (function (BABYLON) {
  104500. var serializedGeometries = [];
  104501. var serializeGeometry = function (geometry, serializationGeometries) {
  104502. if (serializedGeometries[geometry.id]) {
  104503. return;
  104504. }
  104505. if (geometry.doNotSerialize) {
  104506. return;
  104507. }
  104508. if (geometry instanceof BABYLON.BoxGeometry) {
  104509. serializationGeometries.boxes.push(geometry.serialize());
  104510. }
  104511. else if (geometry instanceof BABYLON.SphereGeometry) {
  104512. serializationGeometries.spheres.push(geometry.serialize());
  104513. }
  104514. else if (geometry instanceof BABYLON.CylinderGeometry) {
  104515. serializationGeometries.cylinders.push(geometry.serialize());
  104516. }
  104517. else if (geometry instanceof BABYLON.TorusGeometry) {
  104518. serializationGeometries.toruses.push(geometry.serialize());
  104519. }
  104520. else if (geometry instanceof BABYLON.GroundGeometry) {
  104521. serializationGeometries.grounds.push(geometry.serialize());
  104522. }
  104523. else if (geometry instanceof BABYLON.Plane) {
  104524. serializationGeometries.planes.push(geometry.serialize());
  104525. }
  104526. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  104527. serializationGeometries.torusKnots.push(geometry.serialize());
  104528. }
  104529. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  104530. throw new Error("Unknown primitive type");
  104531. }
  104532. else {
  104533. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  104534. }
  104535. serializedGeometries[geometry.id] = true;
  104536. };
  104537. var serializeMesh = function (mesh, serializationScene) {
  104538. var serializationObject = {};
  104539. // Geometry
  104540. var geometry = mesh._geometry;
  104541. if (geometry) {
  104542. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  104543. // 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
  104544. serializeGeometry(geometry, serializationScene.geometries);
  104545. }
  104546. }
  104547. // Custom
  104548. if (mesh.serialize) {
  104549. mesh.serialize(serializationObject);
  104550. }
  104551. return serializationObject;
  104552. };
  104553. var finalizeSingleMesh = function (mesh, serializationObject) {
  104554. //only works if the mesh is already loaded
  104555. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  104556. //serialize material
  104557. if (mesh.material) {
  104558. if (mesh.material instanceof BABYLON.MultiMaterial) {
  104559. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  104560. serializationObject.materials = serializationObject.materials || [];
  104561. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  104562. serializationObject.multiMaterials.push(mesh.material.serialize());
  104563. var _loop_1 = function (submaterial) {
  104564. if (submaterial) {
  104565. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  104566. serializationObject.materials.push(submaterial.serialize());
  104567. }
  104568. }
  104569. };
  104570. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  104571. var submaterial = _a[_i];
  104572. _loop_1(submaterial);
  104573. }
  104574. }
  104575. }
  104576. else {
  104577. serializationObject.materials = serializationObject.materials || [];
  104578. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  104579. serializationObject.materials.push(mesh.material.serialize());
  104580. }
  104581. }
  104582. }
  104583. //serialize geometry
  104584. var geometry = mesh._geometry;
  104585. if (geometry) {
  104586. if (!serializationObject.geometries) {
  104587. serializationObject.geometries = {};
  104588. serializationObject.geometries.boxes = [];
  104589. serializationObject.geometries.spheres = [];
  104590. serializationObject.geometries.cylinders = [];
  104591. serializationObject.geometries.toruses = [];
  104592. serializationObject.geometries.grounds = [];
  104593. serializationObject.geometries.planes = [];
  104594. serializationObject.geometries.torusKnots = [];
  104595. serializationObject.geometries.vertexData = [];
  104596. }
  104597. serializeGeometry(geometry, serializationObject.geometries);
  104598. }
  104599. // Skeletons
  104600. if (mesh.skeleton) {
  104601. serializationObject.skeletons = serializationObject.skeletons || [];
  104602. serializationObject.skeletons.push(mesh.skeleton.serialize());
  104603. }
  104604. //serialize the actual mesh
  104605. serializationObject.meshes = serializationObject.meshes || [];
  104606. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  104607. }
  104608. };
  104609. var SceneSerializer = /** @class */ (function () {
  104610. function SceneSerializer() {
  104611. }
  104612. SceneSerializer.ClearCache = function () {
  104613. serializedGeometries = [];
  104614. };
  104615. SceneSerializer.Serialize = function (scene) {
  104616. var serializationObject = {};
  104617. SceneSerializer.ClearCache();
  104618. // Scene
  104619. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  104620. serializationObject.autoClear = scene.autoClear;
  104621. serializationObject.clearColor = scene.clearColor.asArray();
  104622. serializationObject.ambientColor = scene.ambientColor.asArray();
  104623. serializationObject.gravity = scene.gravity.asArray();
  104624. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  104625. serializationObject.workerCollisions = scene.workerCollisions;
  104626. // Fog
  104627. if (scene.fogMode && scene.fogMode !== 0) {
  104628. serializationObject.fogMode = scene.fogMode;
  104629. serializationObject.fogColor = scene.fogColor.asArray();
  104630. serializationObject.fogStart = scene.fogStart;
  104631. serializationObject.fogEnd = scene.fogEnd;
  104632. serializationObject.fogDensity = scene.fogDensity;
  104633. }
  104634. //Physics
  104635. if (scene.isPhysicsEnabled()) {
  104636. var physicEngine = scene.getPhysicsEngine();
  104637. if (physicEngine) {
  104638. serializationObject.physicsEnabled = true;
  104639. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  104640. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  104641. }
  104642. }
  104643. // Metadata
  104644. if (scene.metadata) {
  104645. serializationObject.metadata = scene.metadata;
  104646. }
  104647. // Morph targets
  104648. serializationObject.morphTargetManagers = [];
  104649. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  104650. var abstractMesh = _a[_i];
  104651. var manager = abstractMesh.morphTargetManager;
  104652. if (manager) {
  104653. serializationObject.morphTargetManagers.push(manager.serialize());
  104654. }
  104655. }
  104656. // Lights
  104657. serializationObject.lights = [];
  104658. var index;
  104659. var light;
  104660. for (index = 0; index < scene.lights.length; index++) {
  104661. light = scene.lights[index];
  104662. if (!light.doNotSerialize) {
  104663. serializationObject.lights.push(light.serialize());
  104664. }
  104665. }
  104666. // Cameras
  104667. serializationObject.cameras = [];
  104668. for (index = 0; index < scene.cameras.length; index++) {
  104669. var camera = scene.cameras[index];
  104670. if (!camera.doNotSerialize) {
  104671. serializationObject.cameras.push(camera.serialize());
  104672. }
  104673. }
  104674. if (scene.activeCamera) {
  104675. serializationObject.activeCameraID = scene.activeCamera.id;
  104676. }
  104677. // Animations
  104678. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  104679. // Materials
  104680. serializationObject.materials = [];
  104681. serializationObject.multiMaterials = [];
  104682. var material;
  104683. for (index = 0; index < scene.materials.length; index++) {
  104684. material = scene.materials[index];
  104685. if (!material.doNotSerialize) {
  104686. serializationObject.materials.push(material.serialize());
  104687. }
  104688. }
  104689. // MultiMaterials
  104690. serializationObject.multiMaterials = [];
  104691. for (index = 0; index < scene.multiMaterials.length; index++) {
  104692. var multiMaterial = scene.multiMaterials[index];
  104693. serializationObject.multiMaterials.push(multiMaterial.serialize());
  104694. }
  104695. // Environment texture
  104696. if (scene.environmentTexture) {
  104697. serializationObject.environmentTexture = scene.environmentTexture.name;
  104698. }
  104699. // Skeletons
  104700. serializationObject.skeletons = [];
  104701. for (index = 0; index < scene.skeletons.length; index++) {
  104702. var skeleton = scene.skeletons[index];
  104703. if (!skeleton.doNotSerialize) {
  104704. serializationObject.skeletons.push(skeleton.serialize());
  104705. }
  104706. }
  104707. // Transform nodes
  104708. serializationObject.transformNodes = [];
  104709. for (index = 0; index < scene.transformNodes.length; index++) {
  104710. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  104711. }
  104712. // Geometries
  104713. serializationObject.geometries = {};
  104714. serializationObject.geometries.boxes = [];
  104715. serializationObject.geometries.spheres = [];
  104716. serializationObject.geometries.cylinders = [];
  104717. serializationObject.geometries.toruses = [];
  104718. serializationObject.geometries.grounds = [];
  104719. serializationObject.geometries.planes = [];
  104720. serializationObject.geometries.torusKnots = [];
  104721. serializationObject.geometries.vertexData = [];
  104722. serializedGeometries = [];
  104723. var geometries = scene.getGeometries();
  104724. for (index = 0; index < geometries.length; index++) {
  104725. var geometry = geometries[index];
  104726. if (geometry.isReady()) {
  104727. serializeGeometry(geometry, serializationObject.geometries);
  104728. }
  104729. }
  104730. // Meshes
  104731. serializationObject.meshes = [];
  104732. for (index = 0; index < scene.meshes.length; index++) {
  104733. var abstractMesh = scene.meshes[index];
  104734. if (abstractMesh instanceof BABYLON.Mesh) {
  104735. var mesh = abstractMesh;
  104736. if (!mesh.doNotSerialize) {
  104737. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  104738. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  104739. }
  104740. }
  104741. }
  104742. }
  104743. // Particles Systems
  104744. serializationObject.particleSystems = [];
  104745. for (index = 0; index < scene.particleSystems.length; index++) {
  104746. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  104747. }
  104748. // Action Manager
  104749. if (scene.actionManager) {
  104750. serializationObject.actions = scene.actionManager.serialize("scene");
  104751. }
  104752. // Components
  104753. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  104754. var component = _c[_b];
  104755. component.serialize(serializationObject);
  104756. }
  104757. return serializationObject;
  104758. };
  104759. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  104760. if (withParents === void 0) { withParents = false; }
  104761. if (withChildren === void 0) { withChildren = false; }
  104762. var serializationObject = {};
  104763. SceneSerializer.ClearCache();
  104764. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  104765. if (withParents || withChildren) {
  104766. //deliberate for loop! not for each, appended should be processed as well.
  104767. for (var i = 0; i < toSerialize.length; ++i) {
  104768. if (withChildren) {
  104769. toSerialize[i].getDescendants().forEach(function (node) {
  104770. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  104771. toSerialize.push(node);
  104772. }
  104773. });
  104774. }
  104775. //make sure the array doesn't contain the object already
  104776. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  104777. toSerialize.push(toSerialize[i].parent);
  104778. }
  104779. }
  104780. }
  104781. toSerialize.forEach(function (mesh) {
  104782. finalizeSingleMesh(mesh, serializationObject);
  104783. });
  104784. return serializationObject;
  104785. };
  104786. return SceneSerializer;
  104787. }());
  104788. BABYLON.SceneSerializer = SceneSerializer;
  104789. })(BABYLON || (BABYLON = {}));
  104790. //# sourceMappingURL=babylon.sceneSerializer.js.map
  104791. var BABYLON;
  104792. (function (BABYLON) {
  104793. /**
  104794. * Class used to generate realtime reflection / refraction cube textures
  104795. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  104796. */
  104797. var ReflectionProbe = /** @class */ (function () {
  104798. /**
  104799. * Creates a new reflection probe
  104800. * @param name defines the name of the probe
  104801. * @param size defines the texture resolution (for each face)
  104802. * @param scene defines the hosting scene
  104803. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  104804. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  104805. */
  104806. function ReflectionProbe(
  104807. /** defines the name of the probe */
  104808. name, size, scene, generateMipMaps, useFloat) {
  104809. if (generateMipMaps === void 0) { generateMipMaps = true; }
  104810. if (useFloat === void 0) { useFloat = false; }
  104811. var _this = this;
  104812. this.name = name;
  104813. this._viewMatrix = BABYLON.Matrix.Identity();
  104814. this._target = BABYLON.Vector3.Zero();
  104815. this._add = BABYLON.Vector3.Zero();
  104816. this._invertYAxis = false;
  104817. /** Gets or sets probe position (center of the cube map) */
  104818. this.position = BABYLON.Vector3.Zero();
  104819. this._scene = scene;
  104820. // Create the scene field if not exist.
  104821. if (!this._scene.reflectionProbes) {
  104822. this._scene.reflectionProbes = new Array();
  104823. }
  104824. this._scene.reflectionProbes.push(this);
  104825. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  104826. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  104827. switch (faceIndex) {
  104828. case 0:
  104829. _this._add.copyFromFloats(1, 0, 0);
  104830. break;
  104831. case 1:
  104832. _this._add.copyFromFloats(-1, 0, 0);
  104833. break;
  104834. case 2:
  104835. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  104836. break;
  104837. case 3:
  104838. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  104839. break;
  104840. case 4:
  104841. _this._add.copyFromFloats(0, 0, 1);
  104842. break;
  104843. case 5:
  104844. _this._add.copyFromFloats(0, 0, -1);
  104845. break;
  104846. }
  104847. if (_this._attachedMesh) {
  104848. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  104849. }
  104850. _this.position.addToRef(_this._add, _this._target);
  104851. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  104852. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  104853. scene._forcedViewPosition = _this.position;
  104854. });
  104855. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  104856. scene._forcedViewPosition = null;
  104857. scene.updateTransformMatrix(true);
  104858. });
  104859. if (scene.activeCamera) {
  104860. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  104861. }
  104862. }
  104863. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  104864. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  104865. get: function () {
  104866. return this._renderTargetTexture.samples;
  104867. },
  104868. set: function (value) {
  104869. this._renderTargetTexture.samples = value;
  104870. },
  104871. enumerable: true,
  104872. configurable: true
  104873. });
  104874. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  104875. /** Gets or sets the refresh rate to use (on every frame by default) */
  104876. get: function () {
  104877. return this._renderTargetTexture.refreshRate;
  104878. },
  104879. set: function (value) {
  104880. this._renderTargetTexture.refreshRate = value;
  104881. },
  104882. enumerable: true,
  104883. configurable: true
  104884. });
  104885. /**
  104886. * Gets the hosting scene
  104887. * @returns a Scene
  104888. */
  104889. ReflectionProbe.prototype.getScene = function () {
  104890. return this._scene;
  104891. };
  104892. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  104893. /** Gets the internal CubeTexture used to render to */
  104894. get: function () {
  104895. return this._renderTargetTexture;
  104896. },
  104897. enumerable: true,
  104898. configurable: true
  104899. });
  104900. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  104901. /** Gets the list of meshes to render */
  104902. get: function () {
  104903. return this._renderTargetTexture.renderList;
  104904. },
  104905. enumerable: true,
  104906. configurable: true
  104907. });
  104908. /**
  104909. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  104910. * @param mesh defines the mesh to attach to
  104911. */
  104912. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  104913. this._attachedMesh = mesh;
  104914. };
  104915. /**
  104916. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  104917. * @param renderingGroupId The rendering group id corresponding to its index
  104918. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  104919. */
  104920. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  104921. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  104922. };
  104923. /**
  104924. * Clean all associated resources
  104925. */
  104926. ReflectionProbe.prototype.dispose = function () {
  104927. var index = this._scene.reflectionProbes.indexOf(this);
  104928. if (index !== -1) {
  104929. // Remove from the scene if found
  104930. this._scene.reflectionProbes.splice(index, 1);
  104931. }
  104932. if (this._renderTargetTexture) {
  104933. this._renderTargetTexture.dispose();
  104934. this._renderTargetTexture = null;
  104935. }
  104936. };
  104937. return ReflectionProbe;
  104938. }());
  104939. BABYLON.ReflectionProbe = ReflectionProbe;
  104940. })(BABYLON || (BABYLON = {}));
  104941. //# sourceMappingURL=babylon.reflectionProbe.js.map
  104942. var BABYLON;
  104943. (function (BABYLON) {
  104944. /**
  104945. * Defines the layer scene component responsible to manage any layers
  104946. * in a given scene.
  104947. */
  104948. var LayerSceneComponent = /** @class */ (function () {
  104949. /**
  104950. * Creates a new instance of the component for the given scene
  104951. * @param scene Defines the scene to register the component in
  104952. */
  104953. function LayerSceneComponent(scene) {
  104954. /**
  104955. * The component name helpfull to identify the component in the list of scene components.
  104956. */
  104957. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  104958. this.scene = scene;
  104959. this._engine = scene.getEngine();
  104960. scene.layers = new Array();
  104961. }
  104962. /**
  104963. * Registers the component in a given scene
  104964. */
  104965. LayerSceneComponent.prototype.register = function () {
  104966. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  104967. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  104968. };
  104969. /**
  104970. * Rebuilds the elements related to this component in case of
  104971. * context lost for instance.
  104972. */
  104973. LayerSceneComponent.prototype.rebuild = function () {
  104974. var layers = this.scene.layers;
  104975. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  104976. var layer = layers_1[_i];
  104977. layer._rebuild();
  104978. }
  104979. };
  104980. /**
  104981. * Disposes the component and the associated ressources.
  104982. */
  104983. LayerSceneComponent.prototype.dispose = function () {
  104984. var layers = this.scene.layers;
  104985. while (layers.length) {
  104986. layers[0].dispose();
  104987. }
  104988. };
  104989. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  104990. var layers = this.scene.layers;
  104991. if (layers.length) {
  104992. this._engine.setDepthBuffer(false);
  104993. var cameraLayerMask = camera.layerMask;
  104994. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  104995. var layer = layers_2[_i];
  104996. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  104997. layer.render();
  104998. }
  104999. }
  105000. this._engine.setDepthBuffer(true);
  105001. }
  105002. };
  105003. LayerSceneComponent.prototype._drawBackground = function (camera) {
  105004. this._draw(camera, true);
  105005. };
  105006. LayerSceneComponent.prototype._drawForeground = function (camera) {
  105007. this._draw(camera, false);
  105008. };
  105009. return LayerSceneComponent;
  105010. }());
  105011. BABYLON.LayerSceneComponent = LayerSceneComponent;
  105012. })(BABYLON || (BABYLON = {}));
  105013. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  105014. var BABYLON;
  105015. (function (BABYLON) {
  105016. var Layer = /** @class */ (function () {
  105017. function Layer(name, imgUrl, scene, isBackground, color) {
  105018. this.name = name;
  105019. this.scale = new BABYLON.Vector2(1, 1);
  105020. this.offset = new BABYLON.Vector2(0, 0);
  105021. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  105022. this.layerMask = 0x0FFFFFFF;
  105023. this._vertexBuffers = {};
  105024. // Events
  105025. /**
  105026. * An event triggered when the layer is disposed.
  105027. */
  105028. this.onDisposeObservable = new BABYLON.Observable();
  105029. /**
  105030. * An event triggered before rendering the scene
  105031. */
  105032. this.onBeforeRenderObservable = new BABYLON.Observable();
  105033. /**
  105034. * An event triggered after rendering the scene
  105035. */
  105036. this.onAfterRenderObservable = new BABYLON.Observable();
  105037. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  105038. this.isBackground = isBackground === undefined ? true : isBackground;
  105039. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  105040. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  105041. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  105042. if (!layerComponent) {
  105043. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  105044. this._scene._addComponent(layerComponent);
  105045. }
  105046. this._scene.layers.push(this);
  105047. var engine = this._scene.getEngine();
  105048. // VBO
  105049. var vertices = [];
  105050. vertices.push(1, 1);
  105051. vertices.push(-1, 1);
  105052. vertices.push(-1, -1);
  105053. vertices.push(1, -1);
  105054. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  105055. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  105056. this._createIndexBuffer();
  105057. // Effects
  105058. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  105059. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  105060. }
  105061. Object.defineProperty(Layer.prototype, "onDispose", {
  105062. set: function (callback) {
  105063. if (this._onDisposeObserver) {
  105064. this.onDisposeObservable.remove(this._onDisposeObserver);
  105065. }
  105066. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  105067. },
  105068. enumerable: true,
  105069. configurable: true
  105070. });
  105071. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  105072. set: function (callback) {
  105073. if (this._onBeforeRenderObserver) {
  105074. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  105075. }
  105076. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  105077. },
  105078. enumerable: true,
  105079. configurable: true
  105080. });
  105081. Object.defineProperty(Layer.prototype, "onAfterRender", {
  105082. set: function (callback) {
  105083. if (this._onAfterRenderObserver) {
  105084. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  105085. }
  105086. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  105087. },
  105088. enumerable: true,
  105089. configurable: true
  105090. });
  105091. Layer.prototype._createIndexBuffer = function () {
  105092. var engine = this._scene.getEngine();
  105093. // Indices
  105094. var indices = [];
  105095. indices.push(0);
  105096. indices.push(1);
  105097. indices.push(2);
  105098. indices.push(0);
  105099. indices.push(2);
  105100. indices.push(3);
  105101. this._indexBuffer = engine.createIndexBuffer(indices);
  105102. };
  105103. /** @hidden */
  105104. Layer.prototype._rebuild = function () {
  105105. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  105106. if (vb) {
  105107. vb._rebuild();
  105108. }
  105109. this._createIndexBuffer();
  105110. };
  105111. Layer.prototype.render = function () {
  105112. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  105113. // Check
  105114. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  105115. return;
  105116. var engine = this._scene.getEngine();
  105117. this.onBeforeRenderObservable.notifyObservers(this);
  105118. // Render
  105119. engine.enableEffect(currentEffect);
  105120. engine.setState(false);
  105121. // Texture
  105122. currentEffect.setTexture("textureSampler", this.texture);
  105123. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  105124. // Color
  105125. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  105126. // Scale / offset
  105127. currentEffect.setVector2("offset", this.offset);
  105128. currentEffect.setVector2("scale", this.scale);
  105129. // VBOs
  105130. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  105131. // Draw order
  105132. if (!this.alphaTest) {
  105133. engine.setAlphaMode(this.alphaBlendingMode);
  105134. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105135. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  105136. }
  105137. else {
  105138. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105139. }
  105140. this.onAfterRenderObservable.notifyObservers(this);
  105141. };
  105142. Layer.prototype.dispose = function () {
  105143. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  105144. if (vertexBuffer) {
  105145. vertexBuffer.dispose();
  105146. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  105147. }
  105148. if (this._indexBuffer) {
  105149. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  105150. this._indexBuffer = null;
  105151. }
  105152. if (this.texture) {
  105153. this.texture.dispose();
  105154. this.texture = null;
  105155. }
  105156. // Remove from scene
  105157. var index = this._scene.layers.indexOf(this);
  105158. this._scene.layers.splice(index, 1);
  105159. // Callback
  105160. this.onDisposeObservable.notifyObservers(this);
  105161. this.onDisposeObservable.clear();
  105162. this.onAfterRenderObservable.clear();
  105163. this.onBeforeRenderObservable.clear();
  105164. };
  105165. return Layer;
  105166. }());
  105167. BABYLON.Layer = Layer;
  105168. })(BABYLON || (BABYLON = {}));
  105169. //# sourceMappingURL=babylon.layer.js.map
  105170. var BABYLON;
  105171. (function (BABYLON) {
  105172. var TextureTools = /** @class */ (function () {
  105173. function TextureTools() {
  105174. }
  105175. /**
  105176. * Uses the GPU to create a copy texture rescaled at a given size
  105177. * @param texture Texture to copy from
  105178. * @param width Desired width
  105179. * @param height Desired height
  105180. * @return Generated texture
  105181. */
  105182. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  105183. if (useBilinearMode === void 0) { useBilinearMode = true; }
  105184. var scene = texture.getScene();
  105185. var engine = scene.getEngine();
  105186. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  105187. rtt.wrapU = texture.wrapU;
  105188. rtt.wrapV = texture.wrapV;
  105189. rtt.uOffset = texture.uOffset;
  105190. rtt.vOffset = texture.vOffset;
  105191. rtt.uScale = texture.uScale;
  105192. rtt.vScale = texture.vScale;
  105193. rtt.uAng = texture.uAng;
  105194. rtt.vAng = texture.vAng;
  105195. rtt.wAng = texture.wAng;
  105196. rtt.coordinatesIndex = texture.coordinatesIndex;
  105197. rtt.level = texture.level;
  105198. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  105199. rtt._texture.isReady = false;
  105200. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105201. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105202. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  105203. passPostProcess.getEffect().executeWhenCompiled(function () {
  105204. passPostProcess.onApply = function (effect) {
  105205. effect.setTexture("textureSampler", texture);
  105206. };
  105207. var internalTexture = rtt.getInternalTexture();
  105208. if (internalTexture) {
  105209. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  105210. engine.unBindFramebuffer(internalTexture);
  105211. rtt.disposeFramebufferObjects();
  105212. passPostProcess.dispose();
  105213. internalTexture.isReady = true;
  105214. }
  105215. });
  105216. return rtt;
  105217. };
  105218. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  105219. if (!scene._environmentBRDFTexture) {
  105220. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  105221. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105222. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105223. scene._environmentBRDFTexture = texture;
  105224. }
  105225. return scene._environmentBRDFTexture;
  105226. };
  105227. 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=";
  105228. return TextureTools;
  105229. }());
  105230. BABYLON.TextureTools = TextureTools;
  105231. })(BABYLON || (BABYLON = {}));
  105232. //# sourceMappingURL=babylon.textureTools.js.map
  105233. var BABYLON;
  105234. (function (BABYLON) {
  105235. var FramingBehavior = /** @class */ (function () {
  105236. function FramingBehavior() {
  105237. this._mode = FramingBehavior.FitFrustumSidesMode;
  105238. this._radiusScale = 1.0;
  105239. this._positionScale = 0.5;
  105240. this._defaultElevation = 0.3;
  105241. this._elevationReturnTime = 1500;
  105242. this._elevationReturnWaitTime = 1000;
  105243. this._zoomStopsAnimation = false;
  105244. this._framingTime = 1500;
  105245. this._isPointerDown = false;
  105246. this._lastInteractionTime = -Infinity;
  105247. // Framing control
  105248. this._animatables = new Array();
  105249. this._betaIsAnimating = false;
  105250. }
  105251. Object.defineProperty(FramingBehavior.prototype, "name", {
  105252. get: function () {
  105253. return "Framing";
  105254. },
  105255. enumerable: true,
  105256. configurable: true
  105257. });
  105258. Object.defineProperty(FramingBehavior.prototype, "mode", {
  105259. /**
  105260. * Gets current mode used by the behavior.
  105261. */
  105262. get: function () {
  105263. return this._mode;
  105264. },
  105265. /**
  105266. * Sets the current mode used by the behavior
  105267. */
  105268. set: function (mode) {
  105269. this._mode = mode;
  105270. },
  105271. enumerable: true,
  105272. configurable: true
  105273. });
  105274. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  105275. /**
  105276. * Gets the scale applied to the radius
  105277. */
  105278. get: function () {
  105279. return this._radiusScale;
  105280. },
  105281. /**
  105282. * Sets the scale applied to the radius (1 by default)
  105283. */
  105284. set: function (radius) {
  105285. this._radiusScale = radius;
  105286. },
  105287. enumerable: true,
  105288. configurable: true
  105289. });
  105290. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  105291. /**
  105292. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  105293. */
  105294. get: function () {
  105295. return this._positionScale;
  105296. },
  105297. /**
  105298. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  105299. */
  105300. set: function (scale) {
  105301. this._positionScale = scale;
  105302. },
  105303. enumerable: true,
  105304. configurable: true
  105305. });
  105306. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  105307. /**
  105308. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  105309. * behaviour is triggered, in radians.
  105310. */
  105311. get: function () {
  105312. return this._defaultElevation;
  105313. },
  105314. /**
  105315. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  105316. * behaviour is triggered, in radians.
  105317. */
  105318. set: function (elevation) {
  105319. this._defaultElevation = elevation;
  105320. },
  105321. enumerable: true,
  105322. configurable: true
  105323. });
  105324. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  105325. /**
  105326. * Gets the time (in milliseconds) taken to return to the default beta position.
  105327. * Negative value indicates camera should not return to default.
  105328. */
  105329. get: function () {
  105330. return this._elevationReturnTime;
  105331. },
  105332. /**
  105333. * Sets the time (in milliseconds) taken to return to the default beta position.
  105334. * Negative value indicates camera should not return to default.
  105335. */
  105336. set: function (speed) {
  105337. this._elevationReturnTime = speed;
  105338. },
  105339. enumerable: true,
  105340. configurable: true
  105341. });
  105342. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  105343. /**
  105344. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  105345. */
  105346. get: function () {
  105347. return this._elevationReturnWaitTime;
  105348. },
  105349. /**
  105350. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  105351. */
  105352. set: function (time) {
  105353. this._elevationReturnWaitTime = time;
  105354. },
  105355. enumerable: true,
  105356. configurable: true
  105357. });
  105358. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  105359. /**
  105360. * Gets the flag that indicates if user zooming should stop animation.
  105361. */
  105362. get: function () {
  105363. return this._zoomStopsAnimation;
  105364. },
  105365. /**
  105366. * Sets the flag that indicates if user zooming should stop animation.
  105367. */
  105368. set: function (flag) {
  105369. this._zoomStopsAnimation = flag;
  105370. },
  105371. enumerable: true,
  105372. configurable: true
  105373. });
  105374. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  105375. /**
  105376. * Gets the transition time when framing the mesh, in milliseconds
  105377. */
  105378. get: function () {
  105379. return this._framingTime;
  105380. },
  105381. /**
  105382. * Sets the transition time when framing the mesh, in milliseconds
  105383. */
  105384. set: function (time) {
  105385. this._framingTime = time;
  105386. },
  105387. enumerable: true,
  105388. configurable: true
  105389. });
  105390. FramingBehavior.prototype.init = function () {
  105391. // Do notihng
  105392. };
  105393. FramingBehavior.prototype.attach = function (camera) {
  105394. var _this = this;
  105395. this._attachedCamera = camera;
  105396. var scene = this._attachedCamera.getScene();
  105397. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  105398. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  105399. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  105400. _this._isPointerDown = true;
  105401. return;
  105402. }
  105403. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  105404. _this._isPointerDown = false;
  105405. }
  105406. });
  105407. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  105408. if (mesh) {
  105409. _this.zoomOnMesh(mesh);
  105410. }
  105411. });
  105412. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  105413. // Stop the animation if there is user interaction and the animation should stop for this interaction
  105414. _this._applyUserInteraction();
  105415. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  105416. // back to the default position after a given timeout
  105417. _this._maintainCameraAboveGround();
  105418. });
  105419. };
  105420. FramingBehavior.prototype.detach = function () {
  105421. if (!this._attachedCamera) {
  105422. return;
  105423. }
  105424. var scene = this._attachedCamera.getScene();
  105425. if (this._onPrePointerObservableObserver) {
  105426. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  105427. }
  105428. if (this._onAfterCheckInputsObserver) {
  105429. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  105430. }
  105431. if (this._onMeshTargetChangedObserver) {
  105432. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  105433. }
  105434. this._attachedCamera = null;
  105435. };
  105436. /**
  105437. * Targets the given mesh and updates zoom level accordingly.
  105438. * @param mesh The mesh to target.
  105439. * @param radius Optional. If a cached radius position already exists, overrides default.
  105440. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  105441. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  105442. * @param onAnimationEnd Callback triggered at the end of the framing animation
  105443. */
  105444. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  105445. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  105446. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  105447. mesh.computeWorldMatrix(true);
  105448. var boundingBox = mesh.getBoundingInfo().boundingBox;
  105449. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  105450. };
  105451. /**
  105452. * Targets the given mesh with its children and updates zoom level accordingly.
  105453. * @param mesh The mesh to target.
  105454. * @param radius Optional. If a cached radius position already exists, overrides default.
  105455. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  105456. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  105457. * @param onAnimationEnd Callback triggered at the end of the framing animation
  105458. */
  105459. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  105460. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  105461. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  105462. mesh.computeWorldMatrix(true);
  105463. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  105464. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  105465. };
  105466. /**
  105467. * Targets the given meshes with their children and updates zoom level accordingly.
  105468. * @param meshes The mesh to target.
  105469. * @param radius Optional. If a cached radius position already exists, overrides default.
  105470. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  105471. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  105472. * @param onAnimationEnd Callback triggered at the end of the framing animation
  105473. */
  105474. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  105475. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  105476. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  105477. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  105478. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  105479. for (var i = 0; i < meshes.length; i++) {
  105480. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  105481. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  105482. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  105483. }
  105484. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  105485. };
  105486. /**
  105487. * Targets the given mesh and updates zoom level accordingly.
  105488. * @param mesh The mesh to target.
  105489. * @param radius Optional. If a cached radius position already exists, overrides default.
  105490. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  105491. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  105492. * @param onAnimationEnd Callback triggered at the end of the framing animation
  105493. */
  105494. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  105495. var _this = this;
  105496. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  105497. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  105498. var zoomTarget;
  105499. if (!this._attachedCamera) {
  105500. return;
  105501. }
  105502. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  105503. var bottom = minimumWorld.y;
  105504. var top = maximumWorld.y;
  105505. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  105506. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  105507. if (focusOnOriginXZ) {
  105508. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  105509. }
  105510. else {
  105511. var centerWorld = minimumWorld.add(radiusWorld);
  105512. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  105513. }
  105514. if (!this._vectorTransition) {
  105515. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  105516. }
  105517. this._betaIsAnimating = true;
  105518. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  105519. if (animatable) {
  105520. this._animatables.push(animatable);
  105521. }
  105522. // sets the radius and lower radius bounds
  105523. // Small delta ensures camera is not always at lower zoom limit.
  105524. var radius = 0;
  105525. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  105526. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  105527. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  105528. radius = position;
  105529. }
  105530. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  105531. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  105532. if (this._attachedCamera.lowerRadiusLimit === null) {
  105533. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  105534. }
  105535. }
  105536. // Set sensibilities
  105537. var extend = maximumWorld.subtract(minimumWorld).length();
  105538. this._attachedCamera.panningSensibility = 5000 / extend;
  105539. this._attachedCamera.wheelPrecision = 100 / radius;
  105540. // transition to new radius
  105541. if (!this._radiusTransition) {
  105542. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  105543. }
  105544. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  105545. _this.stopAllAnimations();
  105546. if (onAnimationEnd) {
  105547. onAnimationEnd();
  105548. }
  105549. if (_this._attachedCamera) {
  105550. _this._attachedCamera.storeState();
  105551. }
  105552. });
  105553. if (animatable) {
  105554. this._animatables.push(animatable);
  105555. }
  105556. };
  105557. /**
  105558. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  105559. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  105560. * frustum width.
  105561. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  105562. * to fully enclose the mesh in the viewing frustum.
  105563. */
  105564. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  105565. var size = maximumWorld.subtract(minimumWorld);
  105566. var boxVectorGlobalDiagonal = size.length();
  105567. var frustumSlope = this._getFrustumSlope();
  105568. // Formula for setting distance
  105569. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  105570. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  105571. // Horizon distance
  105572. var radius = radiusWithoutFraming * this._radiusScale;
  105573. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  105574. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  105575. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  105576. var camera = this._attachedCamera;
  105577. if (!camera) {
  105578. return 0;
  105579. }
  105580. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  105581. // Don't exceed the requested limit
  105582. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  105583. }
  105584. // Don't exceed the upper radius limit
  105585. if (camera.upperRadiusLimit) {
  105586. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  105587. }
  105588. return distance;
  105589. };
  105590. /**
  105591. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  105592. * is automatically returned to its default position (expected to be above ground plane).
  105593. */
  105594. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  105595. var _this = this;
  105596. if (this._elevationReturnTime < 0) {
  105597. return;
  105598. }
  105599. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  105600. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  105601. var limitBeta = Math.PI * 0.5;
  105602. // Bring the camera back up if below the ground plane
  105603. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  105604. this._betaIsAnimating = true;
  105605. //Transition to new position
  105606. this.stopAllAnimations();
  105607. if (!this._betaTransition) {
  105608. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  105609. }
  105610. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  105611. _this._clearAnimationLocks();
  105612. _this.stopAllAnimations();
  105613. });
  105614. if (animatabe) {
  105615. this._animatables.push(animatabe);
  105616. }
  105617. }
  105618. };
  105619. /**
  105620. * Returns the frustum slope based on the canvas ratio and camera FOV
  105621. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  105622. */
  105623. FramingBehavior.prototype._getFrustumSlope = function () {
  105624. // Calculate the viewport ratio
  105625. // Aspect Ratio is Height/Width.
  105626. var camera = this._attachedCamera;
  105627. if (!camera) {
  105628. return BABYLON.Vector2.Zero();
  105629. }
  105630. var engine = camera.getScene().getEngine();
  105631. var aspectRatio = engine.getAspectRatio(camera);
  105632. // Camera FOV is the vertical field of view (top-bottom) in radians.
  105633. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  105634. var frustumSlopeY = Math.tan(camera.fov / 2);
  105635. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  105636. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  105637. // along the forward vector.
  105638. var frustumSlopeX = frustumSlopeY * aspectRatio;
  105639. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  105640. };
  105641. /**
  105642. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  105643. */
  105644. FramingBehavior.prototype._clearAnimationLocks = function () {
  105645. this._betaIsAnimating = false;
  105646. };
  105647. /**
  105648. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  105649. */
  105650. FramingBehavior.prototype._applyUserInteraction = function () {
  105651. if (this.isUserIsMoving) {
  105652. this._lastInteractionTime = BABYLON.Tools.Now;
  105653. this.stopAllAnimations();
  105654. this._clearAnimationLocks();
  105655. }
  105656. };
  105657. /**
  105658. * Stops and removes all animations that have been applied to the camera
  105659. */
  105660. FramingBehavior.prototype.stopAllAnimations = function () {
  105661. if (this._attachedCamera) {
  105662. this._attachedCamera.animations = [];
  105663. }
  105664. while (this._animatables.length) {
  105665. if (this._animatables[0]) {
  105666. this._animatables[0].onAnimationEnd = null;
  105667. this._animatables[0].stop();
  105668. }
  105669. this._animatables.shift();
  105670. }
  105671. };
  105672. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  105673. /**
  105674. * Gets a value indicating if the user is moving the camera
  105675. */
  105676. get: function () {
  105677. if (!this._attachedCamera) {
  105678. return false;
  105679. }
  105680. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  105681. this._attachedCamera.inertialBetaOffset !== 0 ||
  105682. this._attachedCamera.inertialRadiusOffset !== 0 ||
  105683. this._attachedCamera.inertialPanningX !== 0 ||
  105684. this._attachedCamera.inertialPanningY !== 0 ||
  105685. this._isPointerDown;
  105686. },
  105687. enumerable: true,
  105688. configurable: true
  105689. });
  105690. /**
  105691. * The easing function used by animations
  105692. */
  105693. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  105694. /**
  105695. * The easing mode used by animations
  105696. */
  105697. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  105698. // Statics
  105699. /**
  105700. * The camera can move all the way towards the mesh.
  105701. */
  105702. FramingBehavior.IgnoreBoundsSizeMode = 0;
  105703. /**
  105704. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  105705. */
  105706. FramingBehavior.FitFrustumSidesMode = 1;
  105707. return FramingBehavior;
  105708. }());
  105709. BABYLON.FramingBehavior = FramingBehavior;
  105710. })(BABYLON || (BABYLON = {}));
  105711. //# sourceMappingURL=babylon.framingBehavior.js.map
  105712. var BABYLON;
  105713. (function (BABYLON) {
  105714. /**
  105715. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  105716. */
  105717. var BouncingBehavior = /** @class */ (function () {
  105718. function BouncingBehavior() {
  105719. /**
  105720. * The duration of the animation, in milliseconds
  105721. */
  105722. this.transitionDuration = 450;
  105723. /**
  105724. * Length of the distance animated by the transition when lower radius is reached
  105725. */
  105726. this.lowerRadiusTransitionRange = 2;
  105727. /**
  105728. * Length of the distance animated by the transition when upper radius is reached
  105729. */
  105730. this.upperRadiusTransitionRange = -2;
  105731. this._autoTransitionRange = false;
  105732. // Animations
  105733. this._radiusIsAnimating = false;
  105734. this._radiusBounceTransition = null;
  105735. this._animatables = new Array();
  105736. }
  105737. Object.defineProperty(BouncingBehavior.prototype, "name", {
  105738. get: function () {
  105739. return "Bouncing";
  105740. },
  105741. enumerable: true,
  105742. configurable: true
  105743. });
  105744. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  105745. /**
  105746. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  105747. */
  105748. get: function () {
  105749. return this._autoTransitionRange;
  105750. },
  105751. /**
  105752. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  105753. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  105754. */
  105755. set: function (value) {
  105756. var _this = this;
  105757. if (this._autoTransitionRange === value) {
  105758. return;
  105759. }
  105760. this._autoTransitionRange = value;
  105761. var camera = this._attachedCamera;
  105762. if (!camera) {
  105763. return;
  105764. }
  105765. if (value) {
  105766. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  105767. if (!mesh) {
  105768. return;
  105769. }
  105770. mesh.computeWorldMatrix(true);
  105771. var diagonal = mesh.getBoundingInfo().diagonalLength;
  105772. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  105773. _this.upperRadiusTransitionRange = diagonal * 0.05;
  105774. });
  105775. }
  105776. else if (this._onMeshTargetChangedObserver) {
  105777. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  105778. }
  105779. },
  105780. enumerable: true,
  105781. configurable: true
  105782. });
  105783. BouncingBehavior.prototype.init = function () {
  105784. // Do notihng
  105785. };
  105786. BouncingBehavior.prototype.attach = function (camera) {
  105787. var _this = this;
  105788. this._attachedCamera = camera;
  105789. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  105790. if (!_this._attachedCamera) {
  105791. return;
  105792. }
  105793. // Add the bounce animation to the lower radius limit
  105794. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  105795. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  105796. }
  105797. // Add the bounce animation to the upper radius limit
  105798. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  105799. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  105800. }
  105801. });
  105802. };
  105803. BouncingBehavior.prototype.detach = function () {
  105804. if (!this._attachedCamera) {
  105805. return;
  105806. }
  105807. if (this._onAfterCheckInputsObserver) {
  105808. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  105809. }
  105810. if (this._onMeshTargetChangedObserver) {
  105811. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  105812. }
  105813. this._attachedCamera = null;
  105814. };
  105815. /**
  105816. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  105817. * @param radiusLimit The limit to check against.
  105818. * @return Bool to indicate if at limit.
  105819. */
  105820. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  105821. if (!this._attachedCamera) {
  105822. return false;
  105823. }
  105824. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  105825. return true;
  105826. }
  105827. return false;
  105828. };
  105829. /**
  105830. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  105831. * @param radiusDelta The delta by which to animate to. Can be negative.
  105832. */
  105833. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  105834. var _this = this;
  105835. if (!this._attachedCamera) {
  105836. return;
  105837. }
  105838. if (!this._radiusBounceTransition) {
  105839. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  105840. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  105841. }
  105842. // Prevent zoom until bounce has completed
  105843. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  105844. this._attachedCamera.wheelPrecision = Infinity;
  105845. this._attachedCamera.inertialRadiusOffset = 0;
  105846. // Animate to the radius limit
  105847. this.stopAllAnimations();
  105848. this._radiusIsAnimating = true;
  105849. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  105850. if (animatable) {
  105851. this._animatables.push(animatable);
  105852. }
  105853. };
  105854. /**
  105855. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  105856. */
  105857. BouncingBehavior.prototype._clearAnimationLocks = function () {
  105858. this._radiusIsAnimating = false;
  105859. if (this._attachedCamera) {
  105860. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  105861. }
  105862. };
  105863. /**
  105864. * Stops and removes all animations that have been applied to the camera
  105865. */
  105866. BouncingBehavior.prototype.stopAllAnimations = function () {
  105867. if (this._attachedCamera) {
  105868. this._attachedCamera.animations = [];
  105869. }
  105870. while (this._animatables.length) {
  105871. this._animatables[0].onAnimationEnd = null;
  105872. this._animatables[0].stop();
  105873. this._animatables.shift();
  105874. }
  105875. };
  105876. /**
  105877. * The easing function used by animations
  105878. */
  105879. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  105880. /**
  105881. * The easing mode used by animations
  105882. */
  105883. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  105884. return BouncingBehavior;
  105885. }());
  105886. BABYLON.BouncingBehavior = BouncingBehavior;
  105887. })(BABYLON || (BABYLON = {}));
  105888. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  105889. var BABYLON;
  105890. (function (BABYLON) {
  105891. var AutoRotationBehavior = /** @class */ (function () {
  105892. function AutoRotationBehavior() {
  105893. this._zoomStopsAnimation = false;
  105894. this._idleRotationSpeed = 0.05;
  105895. this._idleRotationWaitTime = 2000;
  105896. this._idleRotationSpinupTime = 2000;
  105897. this._isPointerDown = false;
  105898. this._lastFrameTime = null;
  105899. this._lastInteractionTime = -Infinity;
  105900. this._cameraRotationSpeed = 0;
  105901. this._lastFrameRadius = 0;
  105902. }
  105903. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  105904. get: function () {
  105905. return "AutoRotation";
  105906. },
  105907. enumerable: true,
  105908. configurable: true
  105909. });
  105910. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  105911. /**
  105912. * Gets the flag that indicates if user zooming should stop animation.
  105913. */
  105914. get: function () {
  105915. return this._zoomStopsAnimation;
  105916. },
  105917. /**
  105918. * Sets the flag that indicates if user zooming should stop animation.
  105919. */
  105920. set: function (flag) {
  105921. this._zoomStopsAnimation = flag;
  105922. },
  105923. enumerable: true,
  105924. configurable: true
  105925. });
  105926. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  105927. /**
  105928. * Gets the default speed at which the camera rotates around the model.
  105929. */
  105930. get: function () {
  105931. return this._idleRotationSpeed;
  105932. },
  105933. /**
  105934. * Sets the default speed at which the camera rotates around the model.
  105935. */
  105936. set: function (speed) {
  105937. this._idleRotationSpeed = speed;
  105938. },
  105939. enumerable: true,
  105940. configurable: true
  105941. });
  105942. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  105943. /**
  105944. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  105945. */
  105946. get: function () {
  105947. return this._idleRotationWaitTime;
  105948. },
  105949. /**
  105950. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  105951. */
  105952. set: function (time) {
  105953. this._idleRotationWaitTime = time;
  105954. },
  105955. enumerable: true,
  105956. configurable: true
  105957. });
  105958. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  105959. /**
  105960. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  105961. */
  105962. get: function () {
  105963. return this._idleRotationSpinupTime;
  105964. },
  105965. /**
  105966. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  105967. */
  105968. set: function (time) {
  105969. this._idleRotationSpinupTime = time;
  105970. },
  105971. enumerable: true,
  105972. configurable: true
  105973. });
  105974. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  105975. /**
  105976. * Gets a value indicating if the camera is currently rotating because of this behavior
  105977. */
  105978. get: function () {
  105979. return Math.abs(this._cameraRotationSpeed) > 0;
  105980. },
  105981. enumerable: true,
  105982. configurable: true
  105983. });
  105984. AutoRotationBehavior.prototype.init = function () {
  105985. // Do notihng
  105986. };
  105987. AutoRotationBehavior.prototype.attach = function (camera) {
  105988. var _this = this;
  105989. this._attachedCamera = camera;
  105990. var scene = this._attachedCamera.getScene();
  105991. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  105992. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  105993. _this._isPointerDown = true;
  105994. return;
  105995. }
  105996. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  105997. _this._isPointerDown = false;
  105998. }
  105999. });
  106000. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  106001. var now = BABYLON.Tools.Now;
  106002. var dt = 0;
  106003. if (_this._lastFrameTime != null) {
  106004. dt = now - _this._lastFrameTime;
  106005. }
  106006. _this._lastFrameTime = now;
  106007. // Stop the animation if there is user interaction and the animation should stop for this interaction
  106008. _this._applyUserInteraction();
  106009. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  106010. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  106011. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  106012. // Step camera rotation by rotation speed
  106013. if (_this._attachedCamera) {
  106014. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  106015. }
  106016. });
  106017. };
  106018. AutoRotationBehavior.prototype.detach = function () {
  106019. if (!this._attachedCamera) {
  106020. return;
  106021. }
  106022. var scene = this._attachedCamera.getScene();
  106023. if (this._onPrePointerObservableObserver) {
  106024. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  106025. }
  106026. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  106027. this._attachedCamera = null;
  106028. };
  106029. /**
  106030. * Returns true if user is scrolling.
  106031. * @return true if user is scrolling.
  106032. */
  106033. AutoRotationBehavior.prototype._userIsZooming = function () {
  106034. if (!this._attachedCamera) {
  106035. return false;
  106036. }
  106037. return this._attachedCamera.inertialRadiusOffset !== 0;
  106038. };
  106039. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  106040. if (!this._attachedCamera) {
  106041. return false;
  106042. }
  106043. var zoomHasHitLimit = false;
  106044. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  106045. zoomHasHitLimit = true;
  106046. }
  106047. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  106048. this._lastFrameRadius = this._attachedCamera.radius;
  106049. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  106050. };
  106051. /**
  106052. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  106053. */
  106054. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  106055. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  106056. this._lastInteractionTime = BABYLON.Tools.Now;
  106057. }
  106058. };
  106059. // Tools
  106060. AutoRotationBehavior.prototype._userIsMoving = function () {
  106061. if (!this._attachedCamera) {
  106062. return false;
  106063. }
  106064. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  106065. this._attachedCamera.inertialBetaOffset !== 0 ||
  106066. this._attachedCamera.inertialRadiusOffset !== 0 ||
  106067. this._attachedCamera.inertialPanningX !== 0 ||
  106068. this._attachedCamera.inertialPanningY !== 0 ||
  106069. this._isPointerDown;
  106070. };
  106071. return AutoRotationBehavior;
  106072. }());
  106073. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  106074. })(BABYLON || (BABYLON = {}));
  106075. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  106076. var BABYLON;
  106077. (function (BABYLON) {
  106078. var NullEngineOptions = /** @class */ (function () {
  106079. function NullEngineOptions() {
  106080. this.renderWidth = 512;
  106081. this.renderHeight = 256;
  106082. this.textureSize = 512;
  106083. this.deterministicLockstep = false;
  106084. this.lockstepMaxSteps = 4;
  106085. }
  106086. return NullEngineOptions;
  106087. }());
  106088. BABYLON.NullEngineOptions = NullEngineOptions;
  106089. /**
  106090. * The null engine class provides support for headless version of babylon.js.
  106091. * This can be used in server side scenario or for testing purposes
  106092. */
  106093. var NullEngine = /** @class */ (function (_super) {
  106094. __extends(NullEngine, _super);
  106095. function NullEngine(options) {
  106096. if (options === void 0) { options = new NullEngineOptions(); }
  106097. var _this = _super.call(this, null) || this;
  106098. if (options.deterministicLockstep === undefined) {
  106099. options.deterministicLockstep = false;
  106100. }
  106101. if (options.lockstepMaxSteps === undefined) {
  106102. options.lockstepMaxSteps = 4;
  106103. }
  106104. _this._options = options;
  106105. // Init caps
  106106. // We consider we are on a webgl1 capable device
  106107. _this._caps = new BABYLON.EngineCapabilities();
  106108. _this._caps.maxTexturesImageUnits = 16;
  106109. _this._caps.maxVertexTextureImageUnits = 16;
  106110. _this._caps.maxTextureSize = 512;
  106111. _this._caps.maxCubemapTextureSize = 512;
  106112. _this._caps.maxRenderTextureSize = 512;
  106113. _this._caps.maxVertexAttribs = 16;
  106114. _this._caps.maxVaryingVectors = 16;
  106115. _this._caps.maxFragmentUniformVectors = 16;
  106116. _this._caps.maxVertexUniformVectors = 16;
  106117. // Extensions
  106118. _this._caps.standardDerivatives = false;
  106119. _this._caps.astc = null;
  106120. _this._caps.s3tc = null;
  106121. _this._caps.pvrtc = null;
  106122. _this._caps.etc1 = null;
  106123. _this._caps.etc2 = null;
  106124. _this._caps.textureAnisotropicFilterExtension = null;
  106125. _this._caps.maxAnisotropy = 0;
  106126. _this._caps.uintIndices = false;
  106127. _this._caps.fragmentDepthSupported = false;
  106128. _this._caps.highPrecisionShaderSupported = true;
  106129. _this._caps.colorBufferFloat = false;
  106130. _this._caps.textureFloat = false;
  106131. _this._caps.textureFloatLinearFiltering = false;
  106132. _this._caps.textureFloatRender = false;
  106133. _this._caps.textureHalfFloat = false;
  106134. _this._caps.textureHalfFloatLinearFiltering = false;
  106135. _this._caps.textureHalfFloatRender = false;
  106136. _this._caps.textureLOD = false;
  106137. _this._caps.drawBuffersExtension = false;
  106138. _this._caps.depthTextureExtension = false;
  106139. _this._caps.vertexArrayObject = false;
  106140. _this._caps.instancedArrays = false;
  106141. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  106142. // Wrappers
  106143. if (typeof URL === "undefined") {
  106144. URL = {
  106145. createObjectURL: function () { },
  106146. revokeObjectURL: function () { }
  106147. };
  106148. }
  106149. if (typeof Blob === "undefined") {
  106150. Blob = function () { };
  106151. }
  106152. return _this;
  106153. }
  106154. NullEngine.prototype.isDeterministicLockStep = function () {
  106155. return this._options.deterministicLockstep;
  106156. };
  106157. NullEngine.prototype.getLockstepMaxSteps = function () {
  106158. return this._options.lockstepMaxSteps;
  106159. };
  106160. NullEngine.prototype.getHardwareScalingLevel = function () {
  106161. return 1.0;
  106162. };
  106163. NullEngine.prototype.createVertexBuffer = function (vertices) {
  106164. return {
  106165. capacity: 0,
  106166. references: 1,
  106167. is32Bits: false
  106168. };
  106169. };
  106170. NullEngine.prototype.createIndexBuffer = function (indices) {
  106171. return {
  106172. capacity: 0,
  106173. references: 1,
  106174. is32Bits: false
  106175. };
  106176. };
  106177. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  106178. if (stencil === void 0) { stencil = false; }
  106179. };
  106180. NullEngine.prototype.getRenderWidth = function (useScreen) {
  106181. if (useScreen === void 0) { useScreen = false; }
  106182. if (!useScreen && this._currentRenderTarget) {
  106183. return this._currentRenderTarget.width;
  106184. }
  106185. return this._options.renderWidth;
  106186. };
  106187. NullEngine.prototype.getRenderHeight = function (useScreen) {
  106188. if (useScreen === void 0) { useScreen = false; }
  106189. if (!useScreen && this._currentRenderTarget) {
  106190. return this._currentRenderTarget.height;
  106191. }
  106192. return this._options.renderHeight;
  106193. };
  106194. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  106195. this._cachedViewport = viewport;
  106196. };
  106197. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  106198. return {
  106199. transformFeedback: null,
  106200. __SPECTOR_rebuildProgram: null
  106201. };
  106202. };
  106203. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  106204. return [];
  106205. };
  106206. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  106207. return [];
  106208. };
  106209. NullEngine.prototype.bindSamplers = function (effect) {
  106210. this._currentEffect = null;
  106211. };
  106212. NullEngine.prototype.enableEffect = function (effect) {
  106213. this._currentEffect = effect;
  106214. if (effect.onBind) {
  106215. effect.onBind(effect);
  106216. }
  106217. if (effect._onBindObservable) {
  106218. effect._onBindObservable.notifyObservers(effect);
  106219. }
  106220. };
  106221. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  106222. if (zOffset === void 0) { zOffset = 0; }
  106223. if (reverseSide === void 0) { reverseSide = false; }
  106224. };
  106225. NullEngine.prototype.setIntArray = function (uniform, array) {
  106226. };
  106227. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  106228. };
  106229. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  106230. };
  106231. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  106232. };
  106233. NullEngine.prototype.setFloatArray = function (uniform, array) {
  106234. };
  106235. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  106236. };
  106237. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  106238. };
  106239. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  106240. };
  106241. NullEngine.prototype.setArray = function (uniform, array) {
  106242. };
  106243. NullEngine.prototype.setArray2 = function (uniform, array) {
  106244. };
  106245. NullEngine.prototype.setArray3 = function (uniform, array) {
  106246. };
  106247. NullEngine.prototype.setArray4 = function (uniform, array) {
  106248. };
  106249. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  106250. };
  106251. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  106252. };
  106253. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  106254. };
  106255. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  106256. };
  106257. NullEngine.prototype.setFloat = function (uniform, value) {
  106258. };
  106259. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  106260. };
  106261. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  106262. };
  106263. NullEngine.prototype.setBool = function (uniform, bool) {
  106264. };
  106265. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  106266. };
  106267. NullEngine.prototype.setColor3 = function (uniform, color3) {
  106268. };
  106269. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  106270. };
  106271. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  106272. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  106273. if (this._alphaMode === mode) {
  106274. return;
  106275. }
  106276. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  106277. if (!noDepthWriteChange) {
  106278. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  106279. }
  106280. this._alphaMode = mode;
  106281. };
  106282. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  106283. };
  106284. NullEngine.prototype.wipeCaches = function (bruteForce) {
  106285. if (this.preventCacheWipeBetweenFrames) {
  106286. return;
  106287. }
  106288. this.resetTextureCache();
  106289. this._currentEffect = null;
  106290. if (bruteForce) {
  106291. this._currentProgram = null;
  106292. this._stencilState.reset();
  106293. this._depthCullingState.reset();
  106294. this._alphaState.reset();
  106295. }
  106296. this._cachedVertexBuffers = null;
  106297. this._cachedIndexBuffer = null;
  106298. this._cachedEffectForVertexBuffers = null;
  106299. };
  106300. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  106301. };
  106302. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  106303. };
  106304. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  106305. };
  106306. /** @hidden */
  106307. NullEngine.prototype._createTexture = function () {
  106308. return {};
  106309. };
  106310. /** @hidden */
  106311. NullEngine.prototype._releaseTexture = function (texture) {
  106312. };
  106313. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  106314. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  106315. if (onLoad === void 0) { onLoad = null; }
  106316. if (onError === void 0) { onError = null; }
  106317. if (buffer === void 0) { buffer = null; }
  106318. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  106319. var url = String(urlArg);
  106320. texture.url = url;
  106321. texture.generateMipMaps = !noMipmap;
  106322. texture.samplingMode = samplingMode;
  106323. texture.invertY = invertY;
  106324. texture.baseWidth = this._options.textureSize;
  106325. texture.baseHeight = this._options.textureSize;
  106326. texture.width = this._options.textureSize;
  106327. texture.height = this._options.textureSize;
  106328. if (format) {
  106329. texture.format = format;
  106330. }
  106331. texture.isReady = true;
  106332. if (onLoad) {
  106333. onLoad();
  106334. }
  106335. this._internalTexturesCache.push(texture);
  106336. return texture;
  106337. };
  106338. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  106339. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  106340. if (options !== undefined && typeof options === "object") {
  106341. fullOptions.generateMipMaps = options.generateMipMaps;
  106342. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  106343. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  106344. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  106345. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  106346. }
  106347. else {
  106348. fullOptions.generateMipMaps = options;
  106349. fullOptions.generateDepthBuffer = true;
  106350. fullOptions.generateStencilBuffer = false;
  106351. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  106352. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  106353. }
  106354. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  106355. var width = size.width || size;
  106356. var height = size.height || size;
  106357. texture._depthStencilBuffer = {};
  106358. texture._framebuffer = {};
  106359. texture.baseWidth = width;
  106360. texture.baseHeight = height;
  106361. texture.width = width;
  106362. texture.height = height;
  106363. texture.isReady = true;
  106364. texture.samples = 1;
  106365. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  106366. texture.samplingMode = fullOptions.samplingMode;
  106367. texture.type = fullOptions.type;
  106368. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  106369. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  106370. this._internalTexturesCache.push(texture);
  106371. return texture;
  106372. };
  106373. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  106374. texture.samplingMode = samplingMode;
  106375. };
  106376. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  106377. if (this._currentRenderTarget) {
  106378. this.unBindFramebuffer(this._currentRenderTarget);
  106379. }
  106380. this._currentRenderTarget = texture;
  106381. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  106382. if (this._cachedViewport && !forceFullscreenViewport) {
  106383. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  106384. }
  106385. };
  106386. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  106387. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  106388. this._currentRenderTarget = null;
  106389. if (onBeforeUnbind) {
  106390. if (texture._MSAAFramebuffer) {
  106391. this._currentFramebuffer = texture._framebuffer;
  106392. }
  106393. onBeforeUnbind();
  106394. }
  106395. this._currentFramebuffer = null;
  106396. };
  106397. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  106398. var vbo = {
  106399. capacity: 1,
  106400. references: 1,
  106401. is32Bits: false
  106402. };
  106403. return vbo;
  106404. };
  106405. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  106406. if (premulAlpha === void 0) { premulAlpha = false; }
  106407. };
  106408. /**
  106409. * @hidden
  106410. * Get the current error code of the webGL context
  106411. * @returns the error code
  106412. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  106413. */
  106414. NullEngine.prototype.getError = function () {
  106415. return 0;
  106416. };
  106417. /** @hidden */
  106418. NullEngine.prototype._getUnpackAlignement = function () {
  106419. return 1;
  106420. };
  106421. /** @hidden */
  106422. NullEngine.prototype._unpackFlipY = function (value) {
  106423. };
  106424. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  106425. if (offset === void 0) { offset = 0; }
  106426. };
  106427. /**
  106428. * Updates a dynamic vertex buffer.
  106429. * @param vertexBuffer the vertex buffer to update
  106430. * @param data the data used to update the vertex buffer
  106431. * @param byteOffset the byte offset of the data (optional)
  106432. * @param byteLength the byte length of the data (optional)
  106433. */
  106434. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  106435. };
  106436. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  106437. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  106438. this._boundTexturesCache[this._activeChannel] = texture;
  106439. return true;
  106440. }
  106441. return false;
  106442. };
  106443. /** @hidden */
  106444. NullEngine.prototype._bindTexture = function (channel, texture) {
  106445. if (channel < 0) {
  106446. return;
  106447. }
  106448. this._bindTextureDirectly(0, texture);
  106449. };
  106450. /** @hidden */
  106451. NullEngine.prototype._releaseBuffer = function (buffer) {
  106452. buffer.references--;
  106453. if (buffer.references === 0) {
  106454. return true;
  106455. }
  106456. return false;
  106457. };
  106458. NullEngine.prototype.releaseEffects = function () {
  106459. };
  106460. NullEngine.prototype.displayLoadingUI = function () {
  106461. };
  106462. NullEngine.prototype.hideLoadingUI = function () {
  106463. };
  106464. /** @hidden */
  106465. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  106466. if (faceIndex === void 0) { faceIndex = 0; }
  106467. if (lod === void 0) { lod = 0; }
  106468. };
  106469. /** @hidden */
  106470. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  106471. if (faceIndex === void 0) { faceIndex = 0; }
  106472. if (lod === void 0) { lod = 0; }
  106473. };
  106474. /** @hidden */
  106475. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  106476. if (faceIndex === void 0) { faceIndex = 0; }
  106477. if (lod === void 0) { lod = 0; }
  106478. };
  106479. /** @hidden */
  106480. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  106481. if (faceIndex === void 0) { faceIndex = 0; }
  106482. if (lod === void 0) { lod = 0; }
  106483. };
  106484. return NullEngine;
  106485. }(BABYLON.Engine));
  106486. BABYLON.NullEngine = NullEngine;
  106487. })(BABYLON || (BABYLON = {}));
  106488. //# sourceMappingURL=babylon.nullEngine.js.map
  106489. var BABYLON;
  106490. (function (BABYLON) {
  106491. /**
  106492. * This class can be used to get instrumentation data from a Babylon engine
  106493. */
  106494. var EngineInstrumentation = /** @class */ (function () {
  106495. function EngineInstrumentation(engine) {
  106496. this.engine = engine;
  106497. this._captureGPUFrameTime = false;
  106498. this._gpuFrameTime = new BABYLON.PerfCounter();
  106499. this._captureShaderCompilationTime = false;
  106500. this._shaderCompilationTime = new BABYLON.PerfCounter();
  106501. // Observers
  106502. this._onBeginFrameObserver = null;
  106503. this._onEndFrameObserver = null;
  106504. this._onBeforeShaderCompilationObserver = null;
  106505. this._onAfterShaderCompilationObserver = null;
  106506. }
  106507. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  106508. // Properties
  106509. /**
  106510. * Gets the perf counter used for GPU frame time
  106511. */
  106512. get: function () {
  106513. return this._gpuFrameTime;
  106514. },
  106515. enumerable: true,
  106516. configurable: true
  106517. });
  106518. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  106519. /**
  106520. * Gets the GPU frame time capture status
  106521. */
  106522. get: function () {
  106523. return this._captureGPUFrameTime;
  106524. },
  106525. /**
  106526. * Enable or disable the GPU frame time capture
  106527. */
  106528. set: function (value) {
  106529. var _this = this;
  106530. if (value === this._captureGPUFrameTime) {
  106531. return;
  106532. }
  106533. this._captureGPUFrameTime = value;
  106534. if (value) {
  106535. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  106536. if (!_this._gpuFrameTimeToken) {
  106537. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  106538. }
  106539. });
  106540. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  106541. if (!_this._gpuFrameTimeToken) {
  106542. return;
  106543. }
  106544. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  106545. if (time > -1) {
  106546. _this._gpuFrameTimeToken = null;
  106547. _this._gpuFrameTime.fetchNewFrame();
  106548. _this._gpuFrameTime.addCount(time, true);
  106549. }
  106550. });
  106551. }
  106552. else {
  106553. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  106554. this._onBeginFrameObserver = null;
  106555. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  106556. this._onEndFrameObserver = null;
  106557. }
  106558. },
  106559. enumerable: true,
  106560. configurable: true
  106561. });
  106562. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  106563. /**
  106564. * Gets the perf counter used for shader compilation time
  106565. */
  106566. get: function () {
  106567. return this._shaderCompilationTime;
  106568. },
  106569. enumerable: true,
  106570. configurable: true
  106571. });
  106572. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  106573. /**
  106574. * Gets the shader compilation time capture status
  106575. */
  106576. get: function () {
  106577. return this._captureShaderCompilationTime;
  106578. },
  106579. /**
  106580. * Enable or disable the shader compilation time capture
  106581. */
  106582. set: function (value) {
  106583. var _this = this;
  106584. if (value === this._captureShaderCompilationTime) {
  106585. return;
  106586. }
  106587. this._captureShaderCompilationTime = value;
  106588. if (value) {
  106589. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  106590. _this._shaderCompilationTime.fetchNewFrame();
  106591. _this._shaderCompilationTime.beginMonitoring();
  106592. });
  106593. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  106594. _this._shaderCompilationTime.endMonitoring();
  106595. });
  106596. }
  106597. else {
  106598. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  106599. this._onBeforeShaderCompilationObserver = null;
  106600. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  106601. this._onAfterShaderCompilationObserver = null;
  106602. }
  106603. },
  106604. enumerable: true,
  106605. configurable: true
  106606. });
  106607. EngineInstrumentation.prototype.dispose = function () {
  106608. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  106609. this._onBeginFrameObserver = null;
  106610. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  106611. this._onEndFrameObserver = null;
  106612. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  106613. this._onBeforeShaderCompilationObserver = null;
  106614. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  106615. this._onAfterShaderCompilationObserver = null;
  106616. this.engine = null;
  106617. };
  106618. return EngineInstrumentation;
  106619. }());
  106620. BABYLON.EngineInstrumentation = EngineInstrumentation;
  106621. })(BABYLON || (BABYLON = {}));
  106622. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  106623. var BABYLON;
  106624. (function (BABYLON) {
  106625. /**
  106626. * This class can be used to get instrumentation data from a Babylon engine
  106627. */
  106628. var SceneInstrumentation = /** @class */ (function () {
  106629. function SceneInstrumentation(scene) {
  106630. var _this = this;
  106631. this.scene = scene;
  106632. this._captureActiveMeshesEvaluationTime = false;
  106633. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  106634. this._captureRenderTargetsRenderTime = false;
  106635. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  106636. this._captureFrameTime = false;
  106637. this._frameTime = new BABYLON.PerfCounter();
  106638. this._captureRenderTime = false;
  106639. this._renderTime = new BABYLON.PerfCounter();
  106640. this._captureInterFrameTime = false;
  106641. this._interFrameTime = new BABYLON.PerfCounter();
  106642. this._captureParticlesRenderTime = false;
  106643. this._particlesRenderTime = new BABYLON.PerfCounter();
  106644. this._captureSpritesRenderTime = false;
  106645. this._spritesRenderTime = new BABYLON.PerfCounter();
  106646. this._capturePhysicsTime = false;
  106647. this._physicsTime = new BABYLON.PerfCounter();
  106648. this._captureAnimationsTime = false;
  106649. this._animationsTime = new BABYLON.PerfCounter();
  106650. this._captureCameraRenderTime = false;
  106651. this._cameraRenderTime = new BABYLON.PerfCounter();
  106652. // Observers
  106653. this._onBeforeActiveMeshesEvaluationObserver = null;
  106654. this._onAfterActiveMeshesEvaluationObserver = null;
  106655. this._onBeforeRenderTargetsRenderObserver = null;
  106656. this._onAfterRenderTargetsRenderObserver = null;
  106657. this._onAfterRenderObserver = null;
  106658. this._onBeforeDrawPhaseObserver = null;
  106659. this._onAfterDrawPhaseObserver = null;
  106660. this._onBeforeAnimationsObserver = null;
  106661. this._onBeforeParticlesRenderingObserver = null;
  106662. this._onAfterParticlesRenderingObserver = null;
  106663. this._onBeforeSpritesRenderingObserver = null;
  106664. this._onAfterSpritesRenderingObserver = null;
  106665. this._onBeforePhysicsObserver = null;
  106666. this._onAfterPhysicsObserver = null;
  106667. this._onAfterAnimationsObserver = null;
  106668. this._onBeforeCameraRenderObserver = null;
  106669. this._onAfterCameraRenderObserver = null;
  106670. // Before render
  106671. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  106672. if (_this._captureActiveMeshesEvaluationTime) {
  106673. _this._activeMeshesEvaluationTime.fetchNewFrame();
  106674. }
  106675. if (_this._captureRenderTargetsRenderTime) {
  106676. _this._renderTargetsRenderTime.fetchNewFrame();
  106677. }
  106678. if (_this._captureFrameTime) {
  106679. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  106680. _this._frameTime.beginMonitoring();
  106681. }
  106682. if (_this._captureInterFrameTime) {
  106683. _this._interFrameTime.endMonitoring();
  106684. }
  106685. if (_this._captureParticlesRenderTime) {
  106686. _this._particlesRenderTime.fetchNewFrame();
  106687. }
  106688. if (_this._captureSpritesRenderTime) {
  106689. _this._spritesRenderTime.fetchNewFrame();
  106690. }
  106691. if (_this._captureAnimationsTime) {
  106692. _this._animationsTime.beginMonitoring();
  106693. }
  106694. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  106695. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  106696. });
  106697. // After render
  106698. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  106699. if (_this._captureFrameTime) {
  106700. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  106701. _this._frameTime.endMonitoring();
  106702. }
  106703. if (_this._captureRenderTime) {
  106704. _this._renderTime.endMonitoring(false);
  106705. }
  106706. if (_this._captureInterFrameTime) {
  106707. _this._interFrameTime.beginMonitoring();
  106708. }
  106709. });
  106710. }
  106711. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  106712. // Properties
  106713. /**
  106714. * Gets the perf counter used for active meshes evaluation time
  106715. */
  106716. get: function () {
  106717. return this._activeMeshesEvaluationTime;
  106718. },
  106719. enumerable: true,
  106720. configurable: true
  106721. });
  106722. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  106723. /**
  106724. * Gets the active meshes evaluation time capture status
  106725. */
  106726. get: function () {
  106727. return this._captureActiveMeshesEvaluationTime;
  106728. },
  106729. /**
  106730. * Enable or disable the active meshes evaluation time capture
  106731. */
  106732. set: function (value) {
  106733. var _this = this;
  106734. if (value === this._captureActiveMeshesEvaluationTime) {
  106735. return;
  106736. }
  106737. this._captureActiveMeshesEvaluationTime = value;
  106738. if (value) {
  106739. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  106740. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  106741. _this._activeMeshesEvaluationTime.beginMonitoring();
  106742. });
  106743. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  106744. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  106745. _this._activeMeshesEvaluationTime.endMonitoring();
  106746. });
  106747. }
  106748. else {
  106749. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  106750. this._onBeforeActiveMeshesEvaluationObserver = null;
  106751. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  106752. this._onAfterActiveMeshesEvaluationObserver = null;
  106753. }
  106754. },
  106755. enumerable: true,
  106756. configurable: true
  106757. });
  106758. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  106759. /**
  106760. * Gets the perf counter used for render targets render time
  106761. */
  106762. get: function () {
  106763. return this._renderTargetsRenderTime;
  106764. },
  106765. enumerable: true,
  106766. configurable: true
  106767. });
  106768. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  106769. /**
  106770. * Gets the render targets render time capture status
  106771. */
  106772. get: function () {
  106773. return this._captureRenderTargetsRenderTime;
  106774. },
  106775. /**
  106776. * Enable or disable the render targets render time capture
  106777. */
  106778. set: function (value) {
  106779. var _this = this;
  106780. if (value === this._captureRenderTargetsRenderTime) {
  106781. return;
  106782. }
  106783. this._captureRenderTargetsRenderTime = value;
  106784. if (value) {
  106785. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  106786. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  106787. _this._renderTargetsRenderTime.beginMonitoring();
  106788. });
  106789. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  106790. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  106791. _this._renderTargetsRenderTime.endMonitoring(false);
  106792. });
  106793. }
  106794. else {
  106795. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  106796. this._onBeforeRenderTargetsRenderObserver = null;
  106797. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  106798. this._onAfterRenderTargetsRenderObserver = null;
  106799. }
  106800. },
  106801. enumerable: true,
  106802. configurable: true
  106803. });
  106804. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  106805. /**
  106806. * Gets the perf counter used for particles render time
  106807. */
  106808. get: function () {
  106809. return this._particlesRenderTime;
  106810. },
  106811. enumerable: true,
  106812. configurable: true
  106813. });
  106814. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  106815. /**
  106816. * Gets the particles render time capture status
  106817. */
  106818. get: function () {
  106819. return this._captureParticlesRenderTime;
  106820. },
  106821. /**
  106822. * Enable or disable the particles render time capture
  106823. */
  106824. set: function (value) {
  106825. var _this = this;
  106826. if (value === this._captureParticlesRenderTime) {
  106827. return;
  106828. }
  106829. this._captureParticlesRenderTime = value;
  106830. if (value) {
  106831. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  106832. BABYLON.Tools.StartPerformanceCounter("Particles");
  106833. _this._particlesRenderTime.beginMonitoring();
  106834. });
  106835. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  106836. BABYLON.Tools.EndPerformanceCounter("Particles");
  106837. _this._particlesRenderTime.endMonitoring(false);
  106838. });
  106839. }
  106840. else {
  106841. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  106842. this._onBeforeParticlesRenderingObserver = null;
  106843. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  106844. this._onAfterParticlesRenderingObserver = null;
  106845. }
  106846. },
  106847. enumerable: true,
  106848. configurable: true
  106849. });
  106850. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  106851. /**
  106852. * Gets the perf counter used for sprites render time
  106853. */
  106854. get: function () {
  106855. return this._spritesRenderTime;
  106856. },
  106857. enumerable: true,
  106858. configurable: true
  106859. });
  106860. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  106861. /**
  106862. * Gets the sprites render time capture status
  106863. */
  106864. get: function () {
  106865. return this._captureSpritesRenderTime;
  106866. },
  106867. /**
  106868. * Enable or disable the sprites render time capture
  106869. */
  106870. set: function (value) {
  106871. var _this = this;
  106872. if (value === this._captureSpritesRenderTime) {
  106873. return;
  106874. }
  106875. this._captureSpritesRenderTime = value;
  106876. if (!this.scene.spriteManagers) {
  106877. return;
  106878. }
  106879. if (value) {
  106880. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  106881. BABYLON.Tools.StartPerformanceCounter("Sprites");
  106882. _this._spritesRenderTime.beginMonitoring();
  106883. });
  106884. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  106885. BABYLON.Tools.EndPerformanceCounter("Sprites");
  106886. _this._spritesRenderTime.endMonitoring(false);
  106887. });
  106888. }
  106889. else {
  106890. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  106891. this._onBeforeSpritesRenderingObserver = null;
  106892. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  106893. this._onAfterSpritesRenderingObserver = null;
  106894. }
  106895. },
  106896. enumerable: true,
  106897. configurable: true
  106898. });
  106899. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  106900. /**
  106901. * Gets the perf counter used for physics time
  106902. */
  106903. get: function () {
  106904. return this._physicsTime;
  106905. },
  106906. enumerable: true,
  106907. configurable: true
  106908. });
  106909. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  106910. /**
  106911. * Gets the physics time capture status
  106912. */
  106913. get: function () {
  106914. return this._capturePhysicsTime;
  106915. },
  106916. /**
  106917. * Enable or disable the physics time capture
  106918. */
  106919. set: function (value) {
  106920. var _this = this;
  106921. if (value === this._capturePhysicsTime) {
  106922. return;
  106923. }
  106924. if (!this.scene.onBeforePhysicsObservable) {
  106925. return;
  106926. }
  106927. this._capturePhysicsTime = value;
  106928. if (value) {
  106929. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  106930. BABYLON.Tools.StartPerformanceCounter("Physics");
  106931. _this._physicsTime.beginMonitoring();
  106932. });
  106933. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  106934. BABYLON.Tools.EndPerformanceCounter("Physics");
  106935. _this._physicsTime.endMonitoring();
  106936. });
  106937. }
  106938. else {
  106939. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  106940. this._onBeforePhysicsObserver = null;
  106941. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  106942. this._onAfterPhysicsObserver = null;
  106943. }
  106944. },
  106945. enumerable: true,
  106946. configurable: true
  106947. });
  106948. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  106949. /**
  106950. * Gets the perf counter used for animations time
  106951. */
  106952. get: function () {
  106953. return this._animationsTime;
  106954. },
  106955. enumerable: true,
  106956. configurable: true
  106957. });
  106958. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  106959. /**
  106960. * Gets the animations time capture status
  106961. */
  106962. get: function () {
  106963. return this._captureAnimationsTime;
  106964. },
  106965. /**
  106966. * Enable or disable the animations time capture
  106967. */
  106968. set: function (value) {
  106969. var _this = this;
  106970. if (value === this._captureAnimationsTime) {
  106971. return;
  106972. }
  106973. this._captureAnimationsTime = value;
  106974. if (value) {
  106975. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  106976. _this._animationsTime.endMonitoring();
  106977. });
  106978. }
  106979. else {
  106980. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  106981. this._onAfterAnimationsObserver = null;
  106982. }
  106983. },
  106984. enumerable: true,
  106985. configurable: true
  106986. });
  106987. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  106988. /**
  106989. * Gets the perf counter used for frame time capture
  106990. */
  106991. get: function () {
  106992. return this._frameTime;
  106993. },
  106994. enumerable: true,
  106995. configurable: true
  106996. });
  106997. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  106998. /**
  106999. * Gets the frame time capture status
  107000. */
  107001. get: function () {
  107002. return this._captureFrameTime;
  107003. },
  107004. /**
  107005. * Enable or disable the frame time capture
  107006. */
  107007. set: function (value) {
  107008. this._captureFrameTime = value;
  107009. },
  107010. enumerable: true,
  107011. configurable: true
  107012. });
  107013. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  107014. /**
  107015. * Gets the perf counter used for inter-frames time capture
  107016. */
  107017. get: function () {
  107018. return this._interFrameTime;
  107019. },
  107020. enumerable: true,
  107021. configurable: true
  107022. });
  107023. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  107024. /**
  107025. * Gets the inter-frames time capture status
  107026. */
  107027. get: function () {
  107028. return this._captureInterFrameTime;
  107029. },
  107030. /**
  107031. * Enable or disable the inter-frames time capture
  107032. */
  107033. set: function (value) {
  107034. this._captureInterFrameTime = value;
  107035. },
  107036. enumerable: true,
  107037. configurable: true
  107038. });
  107039. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  107040. /**
  107041. * Gets the perf counter used for render time capture
  107042. */
  107043. get: function () {
  107044. return this._renderTime;
  107045. },
  107046. enumerable: true,
  107047. configurable: true
  107048. });
  107049. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  107050. /**
  107051. * Gets the render time capture status
  107052. */
  107053. get: function () {
  107054. return this._captureRenderTime;
  107055. },
  107056. /**
  107057. * Enable or disable the render time capture
  107058. */
  107059. set: function (value) {
  107060. var _this = this;
  107061. if (value === this._captureRenderTime) {
  107062. return;
  107063. }
  107064. this._captureRenderTime = value;
  107065. if (value) {
  107066. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  107067. _this._renderTime.beginMonitoring();
  107068. BABYLON.Tools.StartPerformanceCounter("Main render");
  107069. });
  107070. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  107071. _this._renderTime.endMonitoring(false);
  107072. BABYLON.Tools.EndPerformanceCounter("Main render");
  107073. });
  107074. }
  107075. else {
  107076. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  107077. this._onBeforeDrawPhaseObserver = null;
  107078. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  107079. this._onAfterDrawPhaseObserver = null;
  107080. }
  107081. },
  107082. enumerable: true,
  107083. configurable: true
  107084. });
  107085. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  107086. /**
  107087. * Gets the perf counter used for camera render time capture
  107088. */
  107089. get: function () {
  107090. return this._cameraRenderTime;
  107091. },
  107092. enumerable: true,
  107093. configurable: true
  107094. });
  107095. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  107096. /**
  107097. * Gets the camera render time capture status
  107098. */
  107099. get: function () {
  107100. return this._captureCameraRenderTime;
  107101. },
  107102. /**
  107103. * Enable or disable the camera render time capture
  107104. */
  107105. set: function (value) {
  107106. var _this = this;
  107107. if (value === this._captureCameraRenderTime) {
  107108. return;
  107109. }
  107110. this._captureCameraRenderTime = value;
  107111. if (value) {
  107112. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  107113. _this._cameraRenderTime.beginMonitoring();
  107114. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  107115. });
  107116. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  107117. _this._cameraRenderTime.endMonitoring(false);
  107118. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  107119. });
  107120. }
  107121. else {
  107122. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  107123. this._onBeforeCameraRenderObserver = null;
  107124. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  107125. this._onAfterCameraRenderObserver = null;
  107126. }
  107127. },
  107128. enumerable: true,
  107129. configurable: true
  107130. });
  107131. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  107132. /**
  107133. * Gets the perf counter used for draw calls
  107134. */
  107135. get: function () {
  107136. return this.scene.getEngine()._drawCalls;
  107137. },
  107138. enumerable: true,
  107139. configurable: true
  107140. });
  107141. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  107142. /**
  107143. * Gets the perf counter used for texture collisions
  107144. */
  107145. get: function () {
  107146. return this.scene.getEngine()._textureCollisions;
  107147. },
  107148. enumerable: true,
  107149. configurable: true
  107150. });
  107151. SceneInstrumentation.prototype.dispose = function () {
  107152. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  107153. this._onAfterRenderObserver = null;
  107154. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  107155. this._onBeforeActiveMeshesEvaluationObserver = null;
  107156. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  107157. this._onAfterActiveMeshesEvaluationObserver = null;
  107158. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  107159. this._onBeforeRenderTargetsRenderObserver = null;
  107160. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  107161. this._onAfterRenderTargetsRenderObserver = null;
  107162. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  107163. this._onBeforeAnimationsObserver = null;
  107164. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  107165. this._onBeforeParticlesRenderingObserver = null;
  107166. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  107167. this._onAfterParticlesRenderingObserver = null;
  107168. if (this._onBeforeSpritesRenderingObserver) {
  107169. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  107170. this._onBeforeSpritesRenderingObserver = null;
  107171. }
  107172. if (this._onAfterSpritesRenderingObserver) {
  107173. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  107174. this._onAfterSpritesRenderingObserver = null;
  107175. }
  107176. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  107177. this._onBeforeDrawPhaseObserver = null;
  107178. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  107179. this._onAfterDrawPhaseObserver = null;
  107180. if (this._onBeforePhysicsObserver) {
  107181. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  107182. this._onBeforePhysicsObserver = null;
  107183. }
  107184. if (this._onAfterPhysicsObserver) {
  107185. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  107186. this._onAfterPhysicsObserver = null;
  107187. }
  107188. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  107189. this._onAfterAnimationsObserver = null;
  107190. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  107191. this._onBeforeCameraRenderObserver = null;
  107192. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  107193. this._onAfterCameraRenderObserver = null;
  107194. this.scene = null;
  107195. };
  107196. return SceneInstrumentation;
  107197. }());
  107198. BABYLON.SceneInstrumentation = SceneInstrumentation;
  107199. })(BABYLON || (BABYLON = {}));
  107200. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  107201. var BABYLON;
  107202. (function (BABYLON) {
  107203. /**
  107204. * @hidden
  107205. **/
  107206. var _TimeToken = /** @class */ (function () {
  107207. function _TimeToken() {
  107208. this._timeElapsedQueryEnded = false;
  107209. }
  107210. return _TimeToken;
  107211. }());
  107212. BABYLON._TimeToken = _TimeToken;
  107213. })(BABYLON || (BABYLON = {}));
  107214. //# sourceMappingURL=babylon.timeToken.js.map
  107215. var BABYLON;
  107216. (function (BABYLON) {
  107217. /**
  107218. * Background material defines definition.
  107219. * @hidden Mainly internal Use
  107220. */
  107221. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  107222. __extends(BackgroundMaterialDefines, _super);
  107223. /**
  107224. * Constructor of the defines.
  107225. */
  107226. function BackgroundMaterialDefines() {
  107227. var _this = _super.call(this) || this;
  107228. /**
  107229. * True if the diffuse texture is in use.
  107230. */
  107231. _this.DIFFUSE = false;
  107232. /**
  107233. * The direct UV channel to use.
  107234. */
  107235. _this.DIFFUSEDIRECTUV = 0;
  107236. /**
  107237. * True if the diffuse texture is in gamma space.
  107238. */
  107239. _this.GAMMADIFFUSE = false;
  107240. /**
  107241. * True if the diffuse texture has opacity in the alpha channel.
  107242. */
  107243. _this.DIFFUSEHASALPHA = false;
  107244. /**
  107245. * True if you want the material to fade to transparent at grazing angle.
  107246. */
  107247. _this.OPACITYFRESNEL = false;
  107248. /**
  107249. * True if an extra blur needs to be added in the reflection.
  107250. */
  107251. _this.REFLECTIONBLUR = false;
  107252. /**
  107253. * True if you want the material to fade to reflection at grazing angle.
  107254. */
  107255. _this.REFLECTIONFRESNEL = false;
  107256. /**
  107257. * True if you want the material to falloff as far as you move away from the scene center.
  107258. */
  107259. _this.REFLECTIONFALLOFF = false;
  107260. /**
  107261. * False if the current Webgl implementation does not support the texture lod extension.
  107262. */
  107263. _this.TEXTURELODSUPPORT = false;
  107264. /**
  107265. * True to ensure the data are premultiplied.
  107266. */
  107267. _this.PREMULTIPLYALPHA = false;
  107268. /**
  107269. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  107270. */
  107271. _this.USERGBCOLOR = false;
  107272. /**
  107273. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  107274. * stays aligned with the desired configuration.
  107275. */
  107276. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  107277. /**
  107278. * True to add noise in order to reduce the banding effect.
  107279. */
  107280. _this.NOISE = false;
  107281. /**
  107282. * is the reflection texture in BGR color scheme?
  107283. * Mainly used to solve a bug in ios10 video tag
  107284. */
  107285. _this.REFLECTIONBGR = false;
  107286. _this.IMAGEPROCESSING = false;
  107287. _this.VIGNETTE = false;
  107288. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  107289. _this.VIGNETTEBLENDMODEOPAQUE = false;
  107290. _this.TONEMAPPING = false;
  107291. _this.TONEMAPPING_ACES = false;
  107292. _this.CONTRAST = false;
  107293. _this.COLORCURVES = false;
  107294. _this.COLORGRADING = false;
  107295. _this.COLORGRADING3D = false;
  107296. _this.SAMPLER3DGREENDEPTH = false;
  107297. _this.SAMPLER3DBGRMAP = false;
  107298. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  107299. _this.EXPOSURE = false;
  107300. // Reflection.
  107301. _this.REFLECTION = false;
  107302. _this.REFLECTIONMAP_3D = false;
  107303. _this.REFLECTIONMAP_SPHERICAL = false;
  107304. _this.REFLECTIONMAP_PLANAR = false;
  107305. _this.REFLECTIONMAP_CUBIC = false;
  107306. _this.REFLECTIONMAP_PROJECTION = false;
  107307. _this.REFLECTIONMAP_SKYBOX = false;
  107308. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  107309. _this.REFLECTIONMAP_EXPLICIT = false;
  107310. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  107311. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  107312. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  107313. _this.INVERTCUBICMAP = false;
  107314. _this.REFLECTIONMAP_OPPOSITEZ = false;
  107315. _this.LODINREFLECTIONALPHA = false;
  107316. _this.GAMMAREFLECTION = false;
  107317. _this.RGBDREFLECTION = false;
  107318. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  107319. // Default BJS.
  107320. _this.MAINUV1 = false;
  107321. _this.MAINUV2 = false;
  107322. _this.UV1 = false;
  107323. _this.UV2 = false;
  107324. _this.CLIPPLANE = false;
  107325. _this.CLIPPLANE2 = false;
  107326. _this.CLIPPLANE3 = false;
  107327. _this.CLIPPLANE4 = false;
  107328. _this.POINTSIZE = false;
  107329. _this.FOG = false;
  107330. _this.NORMAL = false;
  107331. _this.NUM_BONE_INFLUENCERS = 0;
  107332. _this.BonesPerMesh = 0;
  107333. _this.INSTANCES = false;
  107334. _this.SHADOWFLOAT = false;
  107335. _this.rebuild();
  107336. return _this;
  107337. }
  107338. return BackgroundMaterialDefines;
  107339. }(BABYLON.MaterialDefines));
  107340. /**
  107341. * Background material used to create an efficient environement around your scene.
  107342. */
  107343. var BackgroundMaterial = /** @class */ (function (_super) {
  107344. __extends(BackgroundMaterial, _super);
  107345. /**
  107346. * Instantiates a Background Material in the given scene
  107347. * @param name The friendly name of the material
  107348. * @param scene The scene to add the material to
  107349. */
  107350. function BackgroundMaterial(name, scene) {
  107351. var _this = _super.call(this, name, scene) || this;
  107352. /**
  107353. * Key light Color (multiply against the environement texture)
  107354. */
  107355. _this.primaryColor = BABYLON.Color3.White();
  107356. _this._primaryColorShadowLevel = 0;
  107357. _this._primaryColorHighlightLevel = 0;
  107358. /**
  107359. * Reflection Texture used in the material.
  107360. * Should be author in a specific way for the best result (refer to the documentation).
  107361. */
  107362. _this.reflectionTexture = null;
  107363. /**
  107364. * Reflection Texture level of blur.
  107365. *
  107366. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  107367. * texture twice.
  107368. */
  107369. _this.reflectionBlur = 0;
  107370. /**
  107371. * Diffuse Texture used in the material.
  107372. * Should be author in a specific way for the best result (refer to the documentation).
  107373. */
  107374. _this.diffuseTexture = null;
  107375. _this._shadowLights = null;
  107376. /**
  107377. * Specify the list of lights casting shadow on the material.
  107378. * All scene shadow lights will be included if null.
  107379. */
  107380. _this.shadowLights = null;
  107381. /**
  107382. * Helps adjusting the shadow to a softer level if required.
  107383. * 0 means black shadows and 1 means no shadows.
  107384. */
  107385. _this.shadowLevel = 0;
  107386. /**
  107387. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  107388. * It is usually zero but might be interesting to modify according to your setup.
  107389. */
  107390. _this.sceneCenter = BABYLON.Vector3.Zero();
  107391. /**
  107392. * This helps specifying that the material is falling off to the sky box at grazing angle.
  107393. * This helps ensuring a nice transition when the camera goes under the ground.
  107394. */
  107395. _this.opacityFresnel = true;
  107396. /**
  107397. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  107398. * This helps adding a mirror texture on the ground.
  107399. */
  107400. _this.reflectionFresnel = false;
  107401. /**
  107402. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  107403. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  107404. */
  107405. _this.reflectionFalloffDistance = 0.0;
  107406. /**
  107407. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  107408. */
  107409. _this.reflectionAmount = 1.0;
  107410. /**
  107411. * This specifies the weight of the reflection at grazing angle.
  107412. */
  107413. _this.reflectionReflectance0 = 0.05;
  107414. /**
  107415. * This specifies the weight of the reflection at a perpendicular point of view.
  107416. */
  107417. _this.reflectionReflectance90 = 0.5;
  107418. /**
  107419. * Helps to directly use the maps channels instead of their level.
  107420. */
  107421. _this.useRGBColor = true;
  107422. /**
  107423. * This helps reducing the banding effect that could occur on the background.
  107424. */
  107425. _this.enableNoise = false;
  107426. _this._fovMultiplier = 1.0;
  107427. /**
  107428. * Enable the FOV adjustment feature controlled by fovMultiplier.
  107429. */
  107430. _this.useEquirectangularFOV = false;
  107431. _this._maxSimultaneousLights = 4;
  107432. /**
  107433. * Number of Simultaneous lights allowed on the material.
  107434. */
  107435. _this.maxSimultaneousLights = 4;
  107436. /**
  107437. * Keep track of the image processing observer to allow dispose and replace.
  107438. */
  107439. _this._imageProcessingObserver = null;
  107440. /**
  107441. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  107442. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  107443. */
  107444. _this.switchToBGR = false;
  107445. // Temp values kept as cache in the material.
  107446. _this._renderTargets = new BABYLON.SmartArray(16);
  107447. _this._reflectionControls = BABYLON.Vector4.Zero();
  107448. _this._white = BABYLON.Color3.White();
  107449. _this._primaryShadowColor = BABYLON.Color3.Black();
  107450. _this._primaryHighlightColor = BABYLON.Color3.Black();
  107451. // Setup the default processing configuration to the scene.
  107452. _this._attachImageProcessingConfiguration(null);
  107453. _this.getRenderTargetTextures = function () {
  107454. _this._renderTargets.reset();
  107455. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  107456. _this._renderTargets.push(_this._diffuseTexture);
  107457. }
  107458. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  107459. _this._renderTargets.push(_this._reflectionTexture);
  107460. }
  107461. return _this._renderTargets;
  107462. };
  107463. return _this;
  107464. }
  107465. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  107466. /**
  107467. * Experimental Internal Use Only.
  107468. *
  107469. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  107470. * This acts as a helper to set the primary color to a more "human friendly" value.
  107471. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  107472. * output color as close as possible from the chosen value.
  107473. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  107474. * part of lighting setup.)
  107475. */
  107476. get: function () {
  107477. return this.__perceptualColor;
  107478. },
  107479. set: function (value) {
  107480. this.__perceptualColor = value;
  107481. this._computePrimaryColorFromPerceptualColor();
  107482. this._markAllSubMeshesAsLightsDirty();
  107483. },
  107484. enumerable: true,
  107485. configurable: true
  107486. });
  107487. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  107488. /**
  107489. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  107490. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  107491. */
  107492. get: function () {
  107493. return this._primaryColorShadowLevel;
  107494. },
  107495. set: function (value) {
  107496. this._primaryColorShadowLevel = value;
  107497. this._computePrimaryColors();
  107498. this._markAllSubMeshesAsLightsDirty();
  107499. },
  107500. enumerable: true,
  107501. configurable: true
  107502. });
  107503. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  107504. /**
  107505. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  107506. * The primary color is used at the level chosen to define what the white area would look.
  107507. */
  107508. get: function () {
  107509. return this._primaryColorHighlightLevel;
  107510. },
  107511. set: function (value) {
  107512. this._primaryColorHighlightLevel = value;
  107513. this._computePrimaryColors();
  107514. this._markAllSubMeshesAsLightsDirty();
  107515. },
  107516. enumerable: true,
  107517. configurable: true
  107518. });
  107519. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  107520. /**
  107521. * Sets the reflection reflectance fresnel values according to the default standard
  107522. * empirically know to work well :-)
  107523. */
  107524. set: function (value) {
  107525. var reflectionWeight = value;
  107526. if (reflectionWeight < 0.5) {
  107527. reflectionWeight = reflectionWeight * 2.0;
  107528. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  107529. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  107530. }
  107531. else {
  107532. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  107533. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  107534. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  107535. }
  107536. },
  107537. enumerable: true,
  107538. configurable: true
  107539. });
  107540. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  107541. /**
  107542. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  107543. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  107544. * Recommended to be keep at 1.0 except for special cases.
  107545. */
  107546. get: function () {
  107547. return this._fovMultiplier;
  107548. },
  107549. set: function (value) {
  107550. if (isNaN(value)) {
  107551. value = 1.0;
  107552. }
  107553. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  107554. },
  107555. enumerable: true,
  107556. configurable: true
  107557. });
  107558. /**
  107559. * Attaches a new image processing configuration to the PBR Material.
  107560. * @param configuration (if null the scene configuration will be use)
  107561. */
  107562. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  107563. var _this = this;
  107564. if (configuration === this._imageProcessingConfiguration) {
  107565. return;
  107566. }
  107567. // Detaches observer.
  107568. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  107569. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  107570. }
  107571. // Pick the scene configuration if needed.
  107572. if (!configuration) {
  107573. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  107574. }
  107575. else {
  107576. this._imageProcessingConfiguration = configuration;
  107577. }
  107578. // Attaches observer.
  107579. if (this._imageProcessingConfiguration) {
  107580. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  107581. _this._computePrimaryColorFromPerceptualColor();
  107582. _this._markAllSubMeshesAsImageProcessingDirty();
  107583. });
  107584. }
  107585. };
  107586. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  107587. /**
  107588. * Gets the image processing configuration used either in this material.
  107589. */
  107590. get: function () {
  107591. return this._imageProcessingConfiguration;
  107592. },
  107593. /**
  107594. * Sets the Default image processing configuration used either in the this material.
  107595. *
  107596. * If sets to null, the scene one is in use.
  107597. */
  107598. set: function (value) {
  107599. this._attachImageProcessingConfiguration(value);
  107600. // Ensure the effect will be rebuilt.
  107601. this._markAllSubMeshesAsTexturesDirty();
  107602. },
  107603. enumerable: true,
  107604. configurable: true
  107605. });
  107606. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  107607. /**
  107608. * Gets wether the color curves effect is enabled.
  107609. */
  107610. get: function () {
  107611. return this.imageProcessingConfiguration.colorCurvesEnabled;
  107612. },
  107613. /**
  107614. * Sets wether the color curves effect is enabled.
  107615. */
  107616. set: function (value) {
  107617. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  107618. },
  107619. enumerable: true,
  107620. configurable: true
  107621. });
  107622. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  107623. /**
  107624. * Gets wether the color grading effect is enabled.
  107625. */
  107626. get: function () {
  107627. return this.imageProcessingConfiguration.colorGradingEnabled;
  107628. },
  107629. /**
  107630. * Gets wether the color grading effect is enabled.
  107631. */
  107632. set: function (value) {
  107633. this.imageProcessingConfiguration.colorGradingEnabled = value;
  107634. },
  107635. enumerable: true,
  107636. configurable: true
  107637. });
  107638. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  107639. /**
  107640. * Gets wether tonemapping is enabled or not.
  107641. */
  107642. get: function () {
  107643. return this._imageProcessingConfiguration.toneMappingEnabled;
  107644. },
  107645. /**
  107646. * Sets wether tonemapping is enabled or not
  107647. */
  107648. set: function (value) {
  107649. this._imageProcessingConfiguration.toneMappingEnabled = value;
  107650. },
  107651. enumerable: true,
  107652. configurable: true
  107653. });
  107654. ;
  107655. ;
  107656. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  107657. /**
  107658. * The camera exposure used on this material.
  107659. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  107660. * This corresponds to a photographic exposure.
  107661. */
  107662. get: function () {
  107663. return this._imageProcessingConfiguration.exposure;
  107664. },
  107665. /**
  107666. * The camera exposure used on this material.
  107667. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  107668. * This corresponds to a photographic exposure.
  107669. */
  107670. set: function (value) {
  107671. this._imageProcessingConfiguration.exposure = value;
  107672. },
  107673. enumerable: true,
  107674. configurable: true
  107675. });
  107676. ;
  107677. ;
  107678. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  107679. /**
  107680. * Gets The camera contrast used on this material.
  107681. */
  107682. get: function () {
  107683. return this._imageProcessingConfiguration.contrast;
  107684. },
  107685. /**
  107686. * Sets The camera contrast used on this material.
  107687. */
  107688. set: function (value) {
  107689. this._imageProcessingConfiguration.contrast = value;
  107690. },
  107691. enumerable: true,
  107692. configurable: true
  107693. });
  107694. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  107695. /**
  107696. * Gets the Color Grading 2D Lookup Texture.
  107697. */
  107698. get: function () {
  107699. return this._imageProcessingConfiguration.colorGradingTexture;
  107700. },
  107701. /**
  107702. * Sets the Color Grading 2D Lookup Texture.
  107703. */
  107704. set: function (value) {
  107705. this.imageProcessingConfiguration.colorGradingTexture = value;
  107706. },
  107707. enumerable: true,
  107708. configurable: true
  107709. });
  107710. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  107711. /**
  107712. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  107713. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  107714. * 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;
  107715. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  107716. */
  107717. get: function () {
  107718. return this.imageProcessingConfiguration.colorCurves;
  107719. },
  107720. /**
  107721. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  107722. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  107723. * 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;
  107724. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  107725. */
  107726. set: function (value) {
  107727. this.imageProcessingConfiguration.colorCurves = value;
  107728. },
  107729. enumerable: true,
  107730. configurable: true
  107731. });
  107732. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  107733. /**
  107734. * Gets a boolean indicating that current material needs to register RTT
  107735. */
  107736. get: function () {
  107737. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  107738. return true;
  107739. }
  107740. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  107741. return true;
  107742. }
  107743. return false;
  107744. },
  107745. enumerable: true,
  107746. configurable: true
  107747. });
  107748. /**
  107749. * The entire material has been created in order to prevent overdraw.
  107750. * @returns false
  107751. */
  107752. BackgroundMaterial.prototype.needAlphaTesting = function () {
  107753. return true;
  107754. };
  107755. /**
  107756. * The entire material has been created in order to prevent overdraw.
  107757. * @returns true if blending is enable
  107758. */
  107759. BackgroundMaterial.prototype.needAlphaBlending = function () {
  107760. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  107761. };
  107762. /**
  107763. * Checks wether the material is ready to be rendered for a given mesh.
  107764. * @param mesh The mesh to render
  107765. * @param subMesh The submesh to check against
  107766. * @param useInstances Specify wether or not the material is used with instances
  107767. * @returns true if all the dependencies are ready (Textures, Effects...)
  107768. */
  107769. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  107770. var _this = this;
  107771. if (useInstances === void 0) { useInstances = false; }
  107772. if (subMesh.effect && this.isFrozen) {
  107773. if (this._wasPreviouslyReady) {
  107774. return true;
  107775. }
  107776. }
  107777. if (!subMesh._materialDefines) {
  107778. subMesh._materialDefines = new BackgroundMaterialDefines();
  107779. }
  107780. var scene = this.getScene();
  107781. var defines = subMesh._materialDefines;
  107782. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  107783. if (defines._renderId === scene.getRenderId()) {
  107784. return true;
  107785. }
  107786. }
  107787. var engine = scene.getEngine();
  107788. // Lights
  107789. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  107790. defines._needNormals = true;
  107791. // Textures
  107792. if (defines._areTexturesDirty) {
  107793. defines._needUVs = false;
  107794. if (scene.texturesEnabled) {
  107795. if (scene.getEngine().getCaps().textureLOD) {
  107796. defines.TEXTURELODSUPPORT = true;
  107797. }
  107798. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  107799. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  107800. return false;
  107801. }
  107802. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  107803. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  107804. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  107805. defines.OPACITYFRESNEL = this._opacityFresnel;
  107806. }
  107807. else {
  107808. defines.DIFFUSE = false;
  107809. defines.DIFFUSEHASALPHA = false;
  107810. defines.GAMMADIFFUSE = false;
  107811. defines.OPACITYFRESNEL = false;
  107812. }
  107813. var reflectionTexture = this._reflectionTexture;
  107814. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  107815. if (!reflectionTexture.isReadyOrNotBlocking()) {
  107816. return false;
  107817. }
  107818. defines.REFLECTION = true;
  107819. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  107820. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  107821. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  107822. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  107823. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  107824. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  107825. defines.REFLECTIONBGR = this.switchToBGR;
  107826. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  107827. defines.INVERTCUBICMAP = true;
  107828. }
  107829. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  107830. switch (reflectionTexture.coordinatesMode) {
  107831. case BABYLON.Texture.EXPLICIT_MODE:
  107832. defines.REFLECTIONMAP_EXPLICIT = true;
  107833. break;
  107834. case BABYLON.Texture.PLANAR_MODE:
  107835. defines.REFLECTIONMAP_PLANAR = true;
  107836. break;
  107837. case BABYLON.Texture.PROJECTION_MODE:
  107838. defines.REFLECTIONMAP_PROJECTION = true;
  107839. break;
  107840. case BABYLON.Texture.SKYBOX_MODE:
  107841. defines.REFLECTIONMAP_SKYBOX = true;
  107842. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  107843. break;
  107844. case BABYLON.Texture.SPHERICAL_MODE:
  107845. defines.REFLECTIONMAP_SPHERICAL = true;
  107846. break;
  107847. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  107848. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  107849. break;
  107850. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  107851. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  107852. break;
  107853. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  107854. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  107855. break;
  107856. case BABYLON.Texture.CUBIC_MODE:
  107857. case BABYLON.Texture.INVCUBIC_MODE:
  107858. default:
  107859. defines.REFLECTIONMAP_CUBIC = true;
  107860. break;
  107861. }
  107862. if (this.reflectionFresnel) {
  107863. defines.REFLECTIONFRESNEL = true;
  107864. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  107865. this._reflectionControls.x = this.reflectionAmount;
  107866. this._reflectionControls.y = this.reflectionReflectance0;
  107867. this._reflectionControls.z = this.reflectionReflectance90;
  107868. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  107869. }
  107870. else {
  107871. defines.REFLECTIONFRESNEL = false;
  107872. defines.REFLECTIONFALLOFF = false;
  107873. }
  107874. }
  107875. else {
  107876. defines.REFLECTION = false;
  107877. defines.REFLECTIONFRESNEL = false;
  107878. defines.REFLECTIONFALLOFF = false;
  107879. defines.REFLECTIONBLUR = false;
  107880. defines.REFLECTIONMAP_3D = false;
  107881. defines.REFLECTIONMAP_SPHERICAL = false;
  107882. defines.REFLECTIONMAP_PLANAR = false;
  107883. defines.REFLECTIONMAP_CUBIC = false;
  107884. defines.REFLECTIONMAP_PROJECTION = false;
  107885. defines.REFLECTIONMAP_SKYBOX = false;
  107886. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  107887. defines.REFLECTIONMAP_EXPLICIT = false;
  107888. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  107889. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  107890. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  107891. defines.INVERTCUBICMAP = false;
  107892. defines.REFLECTIONMAP_OPPOSITEZ = false;
  107893. defines.LODINREFLECTIONALPHA = false;
  107894. defines.GAMMAREFLECTION = false;
  107895. defines.RGBDREFLECTION = false;
  107896. }
  107897. }
  107898. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  107899. defines.USERGBCOLOR = this._useRGBColor;
  107900. defines.NOISE = this._enableNoise;
  107901. }
  107902. if (defines._areLightsDirty) {
  107903. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  107904. }
  107905. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  107906. if (!this._imageProcessingConfiguration.isReady()) {
  107907. return false;
  107908. }
  107909. this._imageProcessingConfiguration.prepareDefines(defines);
  107910. }
  107911. // Misc.
  107912. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  107913. // Values that need to be evaluated on every frame
  107914. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  107915. // Attribs
  107916. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  107917. if (mesh) {
  107918. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  107919. mesh.createNormals(true);
  107920. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  107921. }
  107922. }
  107923. }
  107924. // Get correct effect
  107925. if (defines.isDirty) {
  107926. defines.markAsProcessed();
  107927. scene.resetCachedMaterial();
  107928. // Fallbacks
  107929. var fallbacks = new BABYLON.EffectFallbacks();
  107930. if (defines.FOG) {
  107931. fallbacks.addFallback(0, "FOG");
  107932. }
  107933. if (defines.POINTSIZE) {
  107934. fallbacks.addFallback(1, "POINTSIZE");
  107935. }
  107936. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  107937. if (defines.NUM_BONE_INFLUENCERS > 0) {
  107938. fallbacks.addCPUSkinningFallback(0, mesh);
  107939. }
  107940. //Attributes
  107941. var attribs = [BABYLON.VertexBuffer.PositionKind];
  107942. if (defines.NORMAL) {
  107943. attribs.push(BABYLON.VertexBuffer.NormalKind);
  107944. }
  107945. if (defines.UV1) {
  107946. attribs.push(BABYLON.VertexBuffer.UVKind);
  107947. }
  107948. if (defines.UV2) {
  107949. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  107950. }
  107951. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  107952. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  107953. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  107954. "vFogInfos", "vFogColor", "pointSize",
  107955. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  107956. "vPrimaryColor", "vPrimaryColorShadow",
  107957. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  107958. "shadowLevel", "alpha",
  107959. "vBackgroundCenter", "vReflectionControl",
  107960. "vDiffuseInfos", "diffuseMatrix",
  107961. ];
  107962. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  107963. var uniformBuffers = ["Material", "Scene"];
  107964. if (BABYLON.ImageProcessingConfiguration) {
  107965. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  107966. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  107967. }
  107968. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  107969. uniformsNames: uniforms,
  107970. uniformBuffersNames: uniformBuffers,
  107971. samplers: samplers,
  107972. defines: defines,
  107973. maxSimultaneousLights: this._maxSimultaneousLights
  107974. });
  107975. var onCompiled = function (effect) {
  107976. if (_this.onCompiled) {
  107977. _this.onCompiled(effect);
  107978. }
  107979. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  107980. };
  107981. var join = defines.toString();
  107982. subMesh.setEffect(scene.getEngine().createEffect("background", {
  107983. attributes: attribs,
  107984. uniformsNames: uniforms,
  107985. uniformBuffersNames: uniformBuffers,
  107986. samplers: samplers,
  107987. defines: join,
  107988. fallbacks: fallbacks,
  107989. onCompiled: onCompiled,
  107990. onError: this.onError,
  107991. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  107992. }, engine), defines);
  107993. this.buildUniformLayout();
  107994. }
  107995. if (!subMesh.effect || !subMesh.effect.isReady()) {
  107996. return false;
  107997. }
  107998. defines._renderId = scene.getRenderId();
  107999. this._wasPreviouslyReady = true;
  108000. return true;
  108001. };
  108002. /**
  108003. * Compute the primary color according to the chosen perceptual color.
  108004. */
  108005. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  108006. if (!this.__perceptualColor) {
  108007. return;
  108008. }
  108009. this._primaryColor.copyFrom(this.__perceptualColor);
  108010. // Revert gamma space.
  108011. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  108012. // Revert image processing configuration.
  108013. if (this._imageProcessingConfiguration) {
  108014. // Revert Exposure.
  108015. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  108016. }
  108017. this._computePrimaryColors();
  108018. };
  108019. /**
  108020. * Compute the highlights and shadow colors according to their chosen levels.
  108021. */
  108022. BackgroundMaterial.prototype._computePrimaryColors = function () {
  108023. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  108024. return;
  108025. }
  108026. // Find the highlight color based on the configuration.
  108027. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  108028. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  108029. // Find the shadow color based on the configuration.
  108030. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  108031. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  108032. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  108033. };
  108034. /**
  108035. * Build the uniform buffer used in the material.
  108036. */
  108037. BackgroundMaterial.prototype.buildUniformLayout = function () {
  108038. // Order is important !
  108039. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  108040. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  108041. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  108042. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  108043. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  108044. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  108045. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  108046. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  108047. this._uniformBuffer.addUniform("pointSize", 1);
  108048. this._uniformBuffer.addUniform("shadowLevel", 1);
  108049. this._uniformBuffer.addUniform("alpha", 1);
  108050. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  108051. this._uniformBuffer.addUniform("vReflectionControl", 4);
  108052. this._uniformBuffer.create();
  108053. };
  108054. /**
  108055. * Unbind the material.
  108056. */
  108057. BackgroundMaterial.prototype.unbind = function () {
  108058. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  108059. this._uniformBuffer.setTexture("diffuseSampler", null);
  108060. }
  108061. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  108062. this._uniformBuffer.setTexture("reflectionSampler", null);
  108063. }
  108064. _super.prototype.unbind.call(this);
  108065. };
  108066. /**
  108067. * Bind only the world matrix to the material.
  108068. * @param world The world matrix to bind.
  108069. */
  108070. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  108071. this._activeEffect.setMatrix("world", world);
  108072. };
  108073. /**
  108074. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  108075. * @param world The world matrix to bind.
  108076. * @param subMesh The submesh to bind for.
  108077. */
  108078. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  108079. var scene = this.getScene();
  108080. var defines = subMesh._materialDefines;
  108081. if (!defines) {
  108082. return;
  108083. }
  108084. var effect = subMesh.effect;
  108085. if (!effect) {
  108086. return;
  108087. }
  108088. this._activeEffect = effect;
  108089. // Matrices
  108090. this.bindOnlyWorldMatrix(world);
  108091. // Bones
  108092. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  108093. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  108094. if (mustRebind) {
  108095. this._uniformBuffer.bindToEffect(effect, "Material");
  108096. this.bindViewProjection(effect);
  108097. var reflectionTexture = this._reflectionTexture;
  108098. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  108099. // Texture uniforms
  108100. if (scene.texturesEnabled) {
  108101. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  108102. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  108103. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  108104. }
  108105. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  108106. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  108107. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  108108. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  108109. }
  108110. }
  108111. if (this.shadowLevel > 0) {
  108112. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  108113. }
  108114. this._uniformBuffer.updateFloat("alpha", this.alpha);
  108115. // Point size
  108116. if (this.pointsCloud) {
  108117. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  108118. }
  108119. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  108120. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  108121. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  108122. }
  108123. else {
  108124. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  108125. }
  108126. }
  108127. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  108128. // Textures
  108129. if (scene.texturesEnabled) {
  108130. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  108131. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  108132. }
  108133. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  108134. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  108135. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  108136. }
  108137. else if (!defines.REFLECTIONBLUR) {
  108138. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  108139. }
  108140. else {
  108141. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  108142. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  108143. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  108144. }
  108145. if (defines.REFLECTIONFRESNEL) {
  108146. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  108147. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  108148. }
  108149. }
  108150. }
  108151. // Clip plane
  108152. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  108153. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  108154. }
  108155. if (mustRebind || !this.isFrozen) {
  108156. if (scene.lightsEnabled) {
  108157. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  108158. }
  108159. // View
  108160. this.bindView(effect);
  108161. // Fog
  108162. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  108163. // image processing
  108164. if (this._imageProcessingConfiguration) {
  108165. this._imageProcessingConfiguration.bind(this._activeEffect);
  108166. }
  108167. }
  108168. this._uniformBuffer.update();
  108169. this._afterBind(mesh, this._activeEffect);
  108170. };
  108171. /**
  108172. * Dispose the material.
  108173. * @param forceDisposeEffect Force disposal of the associated effect.
  108174. * @param forceDisposeTextures Force disposal of the associated textures.
  108175. */
  108176. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  108177. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  108178. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  108179. if (forceDisposeTextures) {
  108180. if (this.diffuseTexture) {
  108181. this.diffuseTexture.dispose();
  108182. }
  108183. if (this.reflectionTexture) {
  108184. this.reflectionTexture.dispose();
  108185. }
  108186. }
  108187. this._renderTargets.dispose();
  108188. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  108189. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  108190. }
  108191. _super.prototype.dispose.call(this, forceDisposeEffect);
  108192. };
  108193. /**
  108194. * Clones the material.
  108195. * @param name The cloned name.
  108196. * @returns The cloned material.
  108197. */
  108198. BackgroundMaterial.prototype.clone = function (name) {
  108199. var _this = this;
  108200. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  108201. };
  108202. /**
  108203. * Serializes the current material to its JSON representation.
  108204. * @returns The JSON representation.
  108205. */
  108206. BackgroundMaterial.prototype.serialize = function () {
  108207. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  108208. serializationObject.customType = "BABYLON.BackgroundMaterial";
  108209. return serializationObject;
  108210. };
  108211. /**
  108212. * Gets the class name of the material
  108213. * @returns "BackgroundMaterial"
  108214. */
  108215. BackgroundMaterial.prototype.getClassName = function () {
  108216. return "BackgroundMaterial";
  108217. };
  108218. /**
  108219. * Parse a JSON input to create back a background material.
  108220. * @param source The JSON data to parse
  108221. * @param scene The scene to create the parsed material in
  108222. * @param rootUrl The root url of the assets the material depends upon
  108223. * @returns the instantiated BackgroundMaterial.
  108224. */
  108225. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  108226. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  108227. };
  108228. /**
  108229. * Standard reflectance value at parallel view angle.
  108230. */
  108231. BackgroundMaterial.StandardReflectance0 = 0.05;
  108232. /**
  108233. * Standard reflectance value at grazing angle.
  108234. */
  108235. BackgroundMaterial.StandardReflectance90 = 0.5;
  108236. __decorate([
  108237. BABYLON.serializeAsColor3()
  108238. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  108239. __decorate([
  108240. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  108241. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  108242. __decorate([
  108243. BABYLON.serializeAsColor3()
  108244. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  108245. __decorate([
  108246. BABYLON.serialize()
  108247. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  108248. __decorate([
  108249. BABYLON.serialize()
  108250. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  108251. __decorate([
  108252. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  108253. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  108254. __decorate([
  108255. BABYLON.serializeAsTexture()
  108256. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  108257. __decorate([
  108258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108259. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  108260. __decorate([
  108261. BABYLON.serialize()
  108262. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  108263. __decorate([
  108264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108265. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  108266. __decorate([
  108267. BABYLON.serializeAsTexture()
  108268. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  108269. __decorate([
  108270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108271. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  108272. __decorate([
  108273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108274. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  108275. __decorate([
  108276. BABYLON.serialize()
  108277. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  108278. __decorate([
  108279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108280. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  108281. __decorate([
  108282. BABYLON.serializeAsVector3()
  108283. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  108284. __decorate([
  108285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108286. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  108287. __decorate([
  108288. BABYLON.serialize()
  108289. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  108290. __decorate([
  108291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108292. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  108293. __decorate([
  108294. BABYLON.serialize()
  108295. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  108296. __decorate([
  108297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108298. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  108299. __decorate([
  108300. BABYLON.serialize()
  108301. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  108302. __decorate([
  108303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108304. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  108305. __decorate([
  108306. BABYLON.serialize()
  108307. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  108308. __decorate([
  108309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108310. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  108311. __decorate([
  108312. BABYLON.serialize()
  108313. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  108314. __decorate([
  108315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108316. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  108317. __decorate([
  108318. BABYLON.serialize()
  108319. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  108320. __decorate([
  108321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108322. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  108323. __decorate([
  108324. BABYLON.serialize()
  108325. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  108326. __decorate([
  108327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108328. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  108329. __decorate([
  108330. BABYLON.serialize()
  108331. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  108332. __decorate([
  108333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108334. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  108335. __decorate([
  108336. BABYLON.serialize()
  108337. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  108338. __decorate([
  108339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  108340. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  108341. __decorate([
  108342. BABYLON.serializeAsImageProcessingConfiguration()
  108343. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  108344. return BackgroundMaterial;
  108345. }(BABYLON.PushMaterial));
  108346. BABYLON.BackgroundMaterial = BackgroundMaterial;
  108347. })(BABYLON || (BABYLON = {}));
  108348. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  108349. var __assign = (this && this.__assign) || function () {
  108350. __assign = Object.assign || function(t) {
  108351. for (var s, i = 1, n = arguments.length; i < n; i++) {
  108352. s = arguments[i];
  108353. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  108354. t[p] = s[p];
  108355. }
  108356. return t;
  108357. };
  108358. return __assign.apply(this, arguments);
  108359. };
  108360. var BABYLON;
  108361. (function (BABYLON) {
  108362. /**
  108363. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  108364. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  108365. * It also helps with the default setup of your imageProcessing configuration.
  108366. */
  108367. var EnvironmentHelper = /** @class */ (function () {
  108368. /**
  108369. * constructor
  108370. * @param options
  108371. * @param scene The scene to add the material to
  108372. */
  108373. function EnvironmentHelper(options, scene) {
  108374. var _this = this;
  108375. this._errorHandler = function (message, exception) {
  108376. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  108377. };
  108378. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  108379. this._scene = scene;
  108380. this.onErrorObservable = new BABYLON.Observable();
  108381. this._setupBackground();
  108382. this._setupImageProcessing();
  108383. }
  108384. /**
  108385. * Creates the default options for the helper.
  108386. */
  108387. EnvironmentHelper._getDefaultOptions = function () {
  108388. return {
  108389. createGround: true,
  108390. groundSize: 15,
  108391. groundTexture: this._groundTextureCDNUrl,
  108392. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  108393. groundOpacity: 0.9,
  108394. enableGroundShadow: true,
  108395. groundShadowLevel: 0.5,
  108396. enableGroundMirror: false,
  108397. groundMirrorSizeRatio: 0.3,
  108398. groundMirrorBlurKernel: 64,
  108399. groundMirrorAmount: 1,
  108400. groundMirrorFresnelWeight: 1,
  108401. groundMirrorFallOffDistance: 0,
  108402. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  108403. groundYBias: 0.00001,
  108404. createSkybox: true,
  108405. skyboxSize: 20,
  108406. skyboxTexture: this._skyboxTextureCDNUrl,
  108407. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  108408. backgroundYRotation: 0,
  108409. sizeAuto: true,
  108410. rootPosition: BABYLON.Vector3.Zero(),
  108411. setupImageProcessing: true,
  108412. environmentTexture: this._environmentTextureCDNUrl,
  108413. cameraExposure: 0.8,
  108414. cameraContrast: 1.2,
  108415. toneMappingEnabled: true,
  108416. };
  108417. };
  108418. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  108419. /**
  108420. * Gets the root mesh created by the helper.
  108421. */
  108422. get: function () {
  108423. return this._rootMesh;
  108424. },
  108425. enumerable: true,
  108426. configurable: true
  108427. });
  108428. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  108429. /**
  108430. * Gets the skybox created by the helper.
  108431. */
  108432. get: function () {
  108433. return this._skybox;
  108434. },
  108435. enumerable: true,
  108436. configurable: true
  108437. });
  108438. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  108439. /**
  108440. * Gets the skybox texture created by the helper.
  108441. */
  108442. get: function () {
  108443. return this._skyboxTexture;
  108444. },
  108445. enumerable: true,
  108446. configurable: true
  108447. });
  108448. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  108449. /**
  108450. * Gets the skybox material created by the helper.
  108451. */
  108452. get: function () {
  108453. return this._skyboxMaterial;
  108454. },
  108455. enumerable: true,
  108456. configurable: true
  108457. });
  108458. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  108459. /**
  108460. * Gets the ground mesh created by the helper.
  108461. */
  108462. get: function () {
  108463. return this._ground;
  108464. },
  108465. enumerable: true,
  108466. configurable: true
  108467. });
  108468. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  108469. /**
  108470. * Gets the ground texture created by the helper.
  108471. */
  108472. get: function () {
  108473. return this._groundTexture;
  108474. },
  108475. enumerable: true,
  108476. configurable: true
  108477. });
  108478. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  108479. /**
  108480. * Gets the ground mirror created by the helper.
  108481. */
  108482. get: function () {
  108483. return this._groundMirror;
  108484. },
  108485. enumerable: true,
  108486. configurable: true
  108487. });
  108488. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  108489. /**
  108490. * Gets the ground mirror render list to helps pushing the meshes
  108491. * you wish in the ground reflection.
  108492. */
  108493. get: function () {
  108494. if (this._groundMirror) {
  108495. return this._groundMirror.renderList;
  108496. }
  108497. return null;
  108498. },
  108499. enumerable: true,
  108500. configurable: true
  108501. });
  108502. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  108503. /**
  108504. * Gets the ground material created by the helper.
  108505. */
  108506. get: function () {
  108507. return this._groundMaterial;
  108508. },
  108509. enumerable: true,
  108510. configurable: true
  108511. });
  108512. /**
  108513. * Updates the background according to the new options
  108514. * @param options
  108515. */
  108516. EnvironmentHelper.prototype.updateOptions = function (options) {
  108517. var newOptions = __assign({}, this._options, options);
  108518. if (this._ground && !newOptions.createGround) {
  108519. this._ground.dispose();
  108520. this._ground = null;
  108521. }
  108522. if (this._groundMaterial && !newOptions.createGround) {
  108523. this._groundMaterial.dispose();
  108524. this._groundMaterial = null;
  108525. }
  108526. if (this._groundTexture) {
  108527. if (this._options.groundTexture != newOptions.groundTexture) {
  108528. this._groundTexture.dispose();
  108529. this._groundTexture = null;
  108530. }
  108531. }
  108532. if (this._skybox && !newOptions.createSkybox) {
  108533. this._skybox.dispose();
  108534. this._skybox = null;
  108535. }
  108536. if (this._skyboxMaterial && !newOptions.createSkybox) {
  108537. this._skyboxMaterial.dispose();
  108538. this._skyboxMaterial = null;
  108539. }
  108540. if (this._skyboxTexture) {
  108541. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  108542. this._skyboxTexture.dispose();
  108543. this._skyboxTexture = null;
  108544. }
  108545. }
  108546. if (this._groundMirror && !newOptions.enableGroundMirror) {
  108547. this._groundMirror.dispose();
  108548. this._groundMirror = null;
  108549. }
  108550. if (this._scene.environmentTexture) {
  108551. if (this._options.environmentTexture != newOptions.environmentTexture) {
  108552. this._scene.environmentTexture.dispose();
  108553. }
  108554. }
  108555. this._options = newOptions;
  108556. this._setupBackground();
  108557. this._setupImageProcessing();
  108558. };
  108559. /**
  108560. * Sets the primary color of all the available elements.
  108561. * @param color the main color to affect to the ground and the background
  108562. */
  108563. EnvironmentHelper.prototype.setMainColor = function (color) {
  108564. if (this.groundMaterial) {
  108565. this.groundMaterial.primaryColor = color;
  108566. }
  108567. if (this.skyboxMaterial) {
  108568. this.skyboxMaterial.primaryColor = color;
  108569. }
  108570. if (this.groundMirror) {
  108571. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  108572. }
  108573. };
  108574. /**
  108575. * Setup the image processing according to the specified options.
  108576. */
  108577. EnvironmentHelper.prototype._setupImageProcessing = function () {
  108578. if (this._options.setupImageProcessing) {
  108579. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  108580. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  108581. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  108582. this._setupEnvironmentTexture();
  108583. }
  108584. };
  108585. /**
  108586. * Setup the environment texture according to the specified options.
  108587. */
  108588. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  108589. if (this._scene.environmentTexture) {
  108590. return;
  108591. }
  108592. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  108593. this._scene.environmentTexture = this._options.environmentTexture;
  108594. return;
  108595. }
  108596. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  108597. this._scene.environmentTexture = environmentTexture;
  108598. };
  108599. /**
  108600. * Setup the background according to the specified options.
  108601. */
  108602. EnvironmentHelper.prototype._setupBackground = function () {
  108603. if (!this._rootMesh) {
  108604. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  108605. }
  108606. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  108607. var sceneSize = this._getSceneSize();
  108608. if (this._options.createGround) {
  108609. this._setupGround(sceneSize);
  108610. this._setupGroundMaterial();
  108611. this._setupGroundDiffuseTexture();
  108612. if (this._options.enableGroundMirror) {
  108613. this._setupGroundMirrorTexture(sceneSize);
  108614. }
  108615. this._setupMirrorInGroundMaterial();
  108616. }
  108617. if (this._options.createSkybox) {
  108618. this._setupSkybox(sceneSize);
  108619. this._setupSkyboxMaterial();
  108620. this._setupSkyboxReflectionTexture();
  108621. }
  108622. this._rootMesh.position.x = sceneSize.rootPosition.x;
  108623. this._rootMesh.position.z = sceneSize.rootPosition.z;
  108624. this._rootMesh.position.y = sceneSize.rootPosition.y;
  108625. };
  108626. /**
  108627. * Get the scene sizes according to the setup.
  108628. */
  108629. EnvironmentHelper.prototype._getSceneSize = function () {
  108630. var _this = this;
  108631. var groundSize = this._options.groundSize;
  108632. var skyboxSize = this._options.skyboxSize;
  108633. var rootPosition = this._options.rootPosition;
  108634. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  108635. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  108636. }
  108637. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  108638. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  108639. });
  108640. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  108641. if (this._options.sizeAuto) {
  108642. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  108643. this._scene.activeCamera.upperRadiusLimit) {
  108644. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  108645. skyboxSize = groundSize;
  108646. }
  108647. var sceneDiagonalLenght = sceneDiagonal.length();
  108648. if (sceneDiagonalLenght > groundSize) {
  108649. groundSize = sceneDiagonalLenght * 2;
  108650. skyboxSize = groundSize;
  108651. }
  108652. // 10 % bigger.
  108653. groundSize *= 1.1;
  108654. skyboxSize *= 1.5;
  108655. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  108656. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  108657. }
  108658. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  108659. };
  108660. /**
  108661. * Setup the ground according to the specified options.
  108662. */
  108663. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  108664. var _this = this;
  108665. if (!this._ground || this._ground.isDisposed()) {
  108666. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  108667. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  108668. this._ground.parent = this._rootMesh;
  108669. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  108670. }
  108671. this._ground.receiveShadows = this._options.enableGroundShadow;
  108672. };
  108673. /**
  108674. * Setup the ground material according to the specified options.
  108675. */
  108676. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  108677. if (!this._groundMaterial) {
  108678. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  108679. }
  108680. this._groundMaterial.alpha = this._options.groundOpacity;
  108681. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  108682. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  108683. this._groundMaterial.primaryColor = this._options.groundColor;
  108684. this._groundMaterial.useRGBColor = false;
  108685. this._groundMaterial.enableNoise = true;
  108686. if (this._ground) {
  108687. this._ground.material = this._groundMaterial;
  108688. }
  108689. };
  108690. /**
  108691. * Setup the ground diffuse texture according to the specified options.
  108692. */
  108693. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  108694. if (!this._groundMaterial) {
  108695. return;
  108696. }
  108697. if (this._groundTexture) {
  108698. return;
  108699. }
  108700. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  108701. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  108702. return;
  108703. }
  108704. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  108705. diffuseTexture.gammaSpace = false;
  108706. diffuseTexture.hasAlpha = true;
  108707. this._groundMaterial.diffuseTexture = diffuseTexture;
  108708. };
  108709. /**
  108710. * Setup the ground mirror texture according to the specified options.
  108711. */
  108712. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  108713. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108714. if (!this._groundMirror) {
  108715. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  108716. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  108717. this._groundMirror.anisotropicFilteringLevel = 1;
  108718. this._groundMirror.wrapU = wrapping;
  108719. this._groundMirror.wrapV = wrapping;
  108720. this._groundMirror.gammaSpace = false;
  108721. if (this._groundMirror.renderList) {
  108722. for (var i = 0; i < this._scene.meshes.length; i++) {
  108723. var mesh = this._scene.meshes[i];
  108724. if (mesh !== this._ground &&
  108725. mesh !== this._skybox &&
  108726. mesh !== this._rootMesh) {
  108727. this._groundMirror.renderList.push(mesh);
  108728. }
  108729. }
  108730. }
  108731. }
  108732. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  108733. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  108734. };
  108735. /**
  108736. * Setup the ground to receive the mirror texture.
  108737. */
  108738. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  108739. if (this._groundMaterial) {
  108740. this._groundMaterial.reflectionTexture = this._groundMirror;
  108741. this._groundMaterial.reflectionFresnel = true;
  108742. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  108743. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  108744. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  108745. }
  108746. };
  108747. /**
  108748. * Setup the skybox according to the specified options.
  108749. */
  108750. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  108751. var _this = this;
  108752. if (!this._skybox || this._skybox.isDisposed()) {
  108753. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  108754. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  108755. }
  108756. this._skybox.parent = this._rootMesh;
  108757. };
  108758. /**
  108759. * Setup the skybox material according to the specified options.
  108760. */
  108761. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  108762. if (!this._skybox) {
  108763. return;
  108764. }
  108765. if (!this._skyboxMaterial) {
  108766. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  108767. }
  108768. this._skyboxMaterial.useRGBColor = false;
  108769. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  108770. this._skyboxMaterial.enableNoise = true;
  108771. this._skybox.material = this._skyboxMaterial;
  108772. };
  108773. /**
  108774. * Setup the skybox reflection texture according to the specified options.
  108775. */
  108776. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  108777. if (!this._skyboxMaterial) {
  108778. return;
  108779. }
  108780. if (this._skyboxTexture) {
  108781. return;
  108782. }
  108783. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  108784. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  108785. return;
  108786. }
  108787. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  108788. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  108789. this._skyboxTexture.gammaSpace = false;
  108790. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  108791. };
  108792. /**
  108793. * Dispose all the elements created by the Helper.
  108794. */
  108795. EnvironmentHelper.prototype.dispose = function () {
  108796. if (this._groundMaterial) {
  108797. this._groundMaterial.dispose(true, true);
  108798. }
  108799. if (this._skyboxMaterial) {
  108800. this._skyboxMaterial.dispose(true, true);
  108801. }
  108802. this._rootMesh.dispose(false);
  108803. };
  108804. /**
  108805. * Default ground texture URL.
  108806. */
  108807. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  108808. /**
  108809. * Default skybox texture URL.
  108810. */
  108811. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  108812. /**
  108813. * Default environment texture URL.
  108814. */
  108815. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  108816. return EnvironmentHelper;
  108817. }());
  108818. BABYLON.EnvironmentHelper = EnvironmentHelper;
  108819. })(BABYLON || (BABYLON = {}));
  108820. //# sourceMappingURL=babylon.environmentHelper.js.map
  108821. var BABYLON;
  108822. (function (BABYLON) {
  108823. /** Internal class used to store shapes for emitters */
  108824. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  108825. function ParticleSystemSetEmitterCreationOptions() {
  108826. }
  108827. return ParticleSystemSetEmitterCreationOptions;
  108828. }());
  108829. /**
  108830. * Represents a set of particle systems working together to create a specific effect
  108831. */
  108832. var ParticleSystemSet = /** @class */ (function () {
  108833. function ParticleSystemSet() {
  108834. /**
  108835. * Gets the particle system list
  108836. */
  108837. this.systems = new Array();
  108838. }
  108839. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  108840. /**
  108841. * Gets the emitter node used with this set
  108842. */
  108843. get: function () {
  108844. return this._emitterNode;
  108845. },
  108846. enumerable: true,
  108847. configurable: true
  108848. });
  108849. /**
  108850. * Creates a new emitter mesh as a sphere
  108851. * @param options defines the options used to create the sphere
  108852. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  108853. * @param scene defines the hosting scene
  108854. */
  108855. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  108856. if (this._emitterNode) {
  108857. this._emitterNode.dispose();
  108858. }
  108859. this._emitterCreationOptions = {
  108860. kind: "Sphere",
  108861. options: options,
  108862. renderingGroupId: renderingGroupId
  108863. };
  108864. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  108865. emitterMesh.renderingGroupId = renderingGroupId;
  108866. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  108867. material.emissiveColor = options.color;
  108868. emitterMesh.material = material;
  108869. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108870. var system = _a[_i];
  108871. system.emitter = emitterMesh;
  108872. }
  108873. this._emitterNode = emitterMesh;
  108874. };
  108875. /**
  108876. * Starts all particle systems of the set
  108877. * @param emitter defines an optional mesh to use as emitter for the particle systems
  108878. */
  108879. ParticleSystemSet.prototype.start = function (emitter) {
  108880. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108881. var system = _a[_i];
  108882. if (emitter) {
  108883. system.emitter = emitter;
  108884. }
  108885. system.start();
  108886. }
  108887. };
  108888. /**
  108889. * Release all associated resources
  108890. */
  108891. ParticleSystemSet.prototype.dispose = function () {
  108892. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108893. var system = _a[_i];
  108894. system.dispose();
  108895. }
  108896. this.systems = [];
  108897. if (this._emitterNode) {
  108898. this._emitterNode.dispose();
  108899. this._emitterNode = null;
  108900. }
  108901. };
  108902. /**
  108903. * Serialize the set into a JSON compatible object
  108904. * @returns a JSON compatible representation of the set
  108905. */
  108906. ParticleSystemSet.prototype.serialize = function () {
  108907. var result = {};
  108908. result.systems = [];
  108909. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108910. var system = _a[_i];
  108911. result.systems.push(system.serialize());
  108912. }
  108913. if (this._emitterNode) {
  108914. result.emitter = this._emitterCreationOptions;
  108915. }
  108916. return result;
  108917. };
  108918. /**
  108919. * Parse a new ParticleSystemSet from a serialized source
  108920. * @param data defines a JSON compatible representation of the set
  108921. * @param scene defines the hosting scene
  108922. * @param gpu defines if we want GPU particles or CPU particles
  108923. * @returns a new ParticleSystemSet
  108924. */
  108925. ParticleSystemSet.Parse = function (data, scene, gpu) {
  108926. if (gpu === void 0) { gpu = false; }
  108927. var result = new ParticleSystemSet();
  108928. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  108929. scene = scene || BABYLON.Engine.LastCreatedScene;
  108930. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  108931. var system = _a[_i];
  108932. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  108933. }
  108934. if (data.emitter) {
  108935. var options = data.emitter.options;
  108936. switch (data.emitter.kind) {
  108937. case "Sphere":
  108938. result.setEmitterAsSphere({
  108939. diameter: options.diameter,
  108940. segments: options.segments,
  108941. color: BABYLON.Color3.FromArray(options.color)
  108942. }, data.emitter.renderingGroupId, scene);
  108943. break;
  108944. }
  108945. }
  108946. return result;
  108947. };
  108948. return ParticleSystemSet;
  108949. }());
  108950. BABYLON.ParticleSystemSet = ParticleSystemSet;
  108951. })(BABYLON || (BABYLON = {}));
  108952. //# sourceMappingURL=babylon.particleSystemSet.js.map
  108953. var BABYLON;
  108954. (function (BABYLON) {
  108955. /**
  108956. * This class is made for on one-liner static method to help creating particle system set.
  108957. */
  108958. var ParticleHelper = /** @class */ (function () {
  108959. function ParticleHelper() {
  108960. }
  108961. /**
  108962. * Create a default particle system that you can tweak
  108963. * @param emitter defines the emitter to use
  108964. * @param capacity defines the system capacity (default is 500 particles)
  108965. * @param scene defines the hosting scene
  108966. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  108967. * @returns the new Particle system
  108968. */
  108969. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  108970. if (capacity === void 0) { capacity = 500; }
  108971. if (useGPU === void 0) { useGPU = false; }
  108972. var system;
  108973. if (useGPU) {
  108974. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  108975. }
  108976. else {
  108977. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  108978. }
  108979. system.emitter = emitter;
  108980. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  108981. system.createConeEmitter(0.1, Math.PI / 4);
  108982. // Particle color
  108983. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  108984. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  108985. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  108986. // Particle Size
  108987. system.minSize = 0.1;
  108988. system.maxSize = 0.1;
  108989. // Emission speed
  108990. system.minEmitPower = 2;
  108991. system.maxEmitPower = 2;
  108992. // Update speed
  108993. system.updateSpeed = 1 / 60;
  108994. system.emitRate = 30;
  108995. return system;
  108996. };
  108997. /**
  108998. * This is the main static method (one-liner) of this helper to create different particle systems
  108999. * @param type This string represents the type to the particle system to create
  109000. * @param scene The scene where the particle system should live
  109001. * @param gpu If the system will use gpu
  109002. * @returns the ParticleSystemSet created
  109003. */
  109004. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  109005. if (gpu === void 0) { gpu = false; }
  109006. if (!scene) {
  109007. scene = BABYLON.Engine.LastCreatedScene;
  109008. ;
  109009. }
  109010. var token = {};
  109011. scene._addPendingData(token);
  109012. return new Promise(function (resolve, reject) {
  109013. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  109014. scene._removePendingData(token);
  109015. return reject("Particle system with GPU is not supported.");
  109016. }
  109017. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  109018. scene._removePendingData(token);
  109019. var newData = JSON.parse(data.toString());
  109020. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  109021. }, undefined, undefined, undefined, function (req, exception) {
  109022. scene._removePendingData(token);
  109023. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  109024. });
  109025. });
  109026. };
  109027. /**
  109028. * Static function used to export a particle system to a ParticleSystemSet variable.
  109029. * Please note that the emitter shape is not exported
  109030. * @param system defines the particle systems to export
  109031. */
  109032. ParticleHelper.ExportSet = function (systems) {
  109033. var set = new BABYLON.ParticleSystemSet();
  109034. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  109035. var system = systems_1[_i];
  109036. set.systems.push(system);
  109037. }
  109038. return set;
  109039. };
  109040. /**
  109041. * Gets or sets base Assets URL
  109042. */
  109043. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  109044. return ParticleHelper;
  109045. }());
  109046. BABYLON.ParticleHelper = ParticleHelper;
  109047. })(BABYLON || (BABYLON = {}));
  109048. //# sourceMappingURL=babylon.particleHelper.js.map
  109049. var BABYLON;
  109050. (function (BABYLON) {
  109051. /**
  109052. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  109053. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  109054. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  109055. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  109056. */
  109057. var VideoDome = /** @class */ (function (_super) {
  109058. __extends(VideoDome, _super);
  109059. /**
  109060. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  109061. * @param name Element's name, child elements will append suffixes for their own names.
  109062. * @param urlsOrVideo defines the url(s) or the video element to use
  109063. * @param options An object containing optional or exposed sub element properties
  109064. */
  109065. function VideoDome(name, urlsOrVideo, options, scene) {
  109066. var _this = _super.call(this, name, scene) || this;
  109067. _this._useDirectMapping = false;
  109068. // set defaults and manage values
  109069. name = name || "videoDome";
  109070. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  109071. options.clickToPlay = Boolean(options.clickToPlay);
  109072. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  109073. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  109074. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  109075. if (options.useDirectMapping === undefined) {
  109076. _this._useDirectMapping = true;
  109077. }
  109078. else {
  109079. _this._useDirectMapping = options.useDirectMapping;
  109080. }
  109081. _this._setReady(false);
  109082. // create
  109083. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  109084. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  109085. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  109086. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  109087. texture.onLoadObservable.addOnce(function () {
  109088. _this._setReady(true);
  109089. });
  109090. // configure material
  109091. material.useEquirectangularFOV = true;
  109092. material.fovMultiplier = 1.0;
  109093. material.opacityFresnel = false;
  109094. if (_this._useDirectMapping) {
  109095. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109096. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109097. material.diffuseTexture = texture;
  109098. }
  109099. else {
  109100. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  109101. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109102. material.reflectionTexture = texture;
  109103. }
  109104. // configure mesh
  109105. _this._mesh.material = material;
  109106. _this._mesh.parent = _this;
  109107. // optional configuration
  109108. if (options.clickToPlay) {
  109109. scene.onPointerUp = function () {
  109110. _this._videoTexture.video.play();
  109111. };
  109112. }
  109113. return _this;
  109114. }
  109115. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  109116. /**
  109117. * Gets the video texture being displayed on the sphere
  109118. */
  109119. get: function () {
  109120. return this._videoTexture;
  109121. },
  109122. enumerable: true,
  109123. configurable: true
  109124. });
  109125. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  109126. /**
  109127. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  109128. * Also see the options.resolution property.
  109129. */
  109130. get: function () {
  109131. return this._material.fovMultiplier;
  109132. },
  109133. set: function (value) {
  109134. this._material.fovMultiplier = value;
  109135. },
  109136. enumerable: true,
  109137. configurable: true
  109138. });
  109139. /**
  109140. * Releases resources associated with this node.
  109141. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  109142. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  109143. */
  109144. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  109145. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  109146. this._videoTexture.dispose();
  109147. this._mesh.dispose();
  109148. this._material.dispose();
  109149. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  109150. };
  109151. return VideoDome;
  109152. }(BABYLON.TransformNode));
  109153. BABYLON.VideoDome = VideoDome;
  109154. })(BABYLON || (BABYLON = {}));
  109155. //# sourceMappingURL=babylon.videoDome.js.map
  109156. var BABYLON;
  109157. (function (BABYLON) {
  109158. /**
  109159. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  109160. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  109161. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  109162. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  109163. */
  109164. var PhotoDome = /** @class */ (function (_super) {
  109165. __extends(PhotoDome, _super);
  109166. /**
  109167. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  109168. * @param name Element's name, child elements will append suffixes for their own names.
  109169. * @param urlsOfPhoto defines the url of the photo to display
  109170. * @param options defines an object containing optional or exposed sub element properties
  109171. * @param onError defines a callback called when an error occured while loading the texture
  109172. */
  109173. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  109174. if (onError === void 0) { onError = null; }
  109175. var _this = _super.call(this, name, scene) || this;
  109176. _this._useDirectMapping = false;
  109177. /**
  109178. * Observable raised when an error occured while loading the 360 image
  109179. */
  109180. _this.onLoadErrorObservable = new BABYLON.Observable();
  109181. // set defaults and manage values
  109182. name = name || "photoDome";
  109183. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  109184. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  109185. if (options.useDirectMapping === undefined) {
  109186. _this._useDirectMapping = true;
  109187. }
  109188. else {
  109189. _this._useDirectMapping = options.useDirectMapping;
  109190. }
  109191. _this._setReady(false);
  109192. // create
  109193. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  109194. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  109195. // configure material
  109196. material.opacityFresnel = false;
  109197. material.useEquirectangularFOV = true;
  109198. material.fovMultiplier = 1.0;
  109199. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  109200. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  109201. if (onError) {
  109202. onError(message, exception);
  109203. }
  109204. });
  109205. _this.photoTexture.onLoadObservable.addOnce(function () {
  109206. _this._setReady(true);
  109207. });
  109208. // configure mesh
  109209. _this._mesh.material = material;
  109210. _this._mesh.parent = _this;
  109211. return _this;
  109212. }
  109213. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  109214. /**
  109215. * Gets or sets the texture being displayed on the sphere
  109216. */
  109217. get: function () {
  109218. return this._photoTexture;
  109219. },
  109220. set: function (value) {
  109221. if (this._photoTexture === value) {
  109222. return;
  109223. }
  109224. this._photoTexture = value;
  109225. if (this._useDirectMapping) {
  109226. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109227. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109228. this._material.diffuseTexture = this._photoTexture;
  109229. }
  109230. else {
  109231. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  109232. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109233. this._material.reflectionTexture = this._photoTexture;
  109234. }
  109235. },
  109236. enumerable: true,
  109237. configurable: true
  109238. });
  109239. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  109240. /**
  109241. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  109242. * Also see the options.resolution property.
  109243. */
  109244. get: function () {
  109245. return this._material.fovMultiplier;
  109246. },
  109247. set: function (value) {
  109248. this._material.fovMultiplier = value;
  109249. },
  109250. enumerable: true,
  109251. configurable: true
  109252. });
  109253. /**
  109254. * Releases resources associated with this node.
  109255. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  109256. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  109257. */
  109258. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  109259. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  109260. this._photoTexture.dispose();
  109261. this._mesh.dispose();
  109262. this._material.dispose();
  109263. this.onLoadErrorObservable.clear();
  109264. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  109265. };
  109266. return PhotoDome;
  109267. }(BABYLON.TransformNode));
  109268. BABYLON.PhotoDome = PhotoDome;
  109269. })(BABYLON || (BABYLON = {}));
  109270. //# sourceMappingURL=babylon.photoDome.js.map
  109271. var BABYLON;
  109272. (function (BABYLON) {
  109273. BABYLON.Engine.prototype.createQuery = function () {
  109274. return this._gl.createQuery();
  109275. };
  109276. BABYLON.Engine.prototype.deleteQuery = function (query) {
  109277. this._gl.deleteQuery(query);
  109278. return this;
  109279. };
  109280. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  109281. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  109282. };
  109283. BABYLON.Engine.prototype.getQueryResult = function (query) {
  109284. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  109285. };
  109286. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  109287. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  109288. this._gl.beginQuery(glAlgorithm, query);
  109289. return this;
  109290. };
  109291. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  109292. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  109293. this._gl.endQuery(glAlgorithm);
  109294. return this;
  109295. };
  109296. BABYLON.Engine.prototype._createTimeQuery = function () {
  109297. var timerQuery = this.getCaps().timerQuery;
  109298. if (timerQuery.createQueryEXT) {
  109299. return timerQuery.createQueryEXT();
  109300. }
  109301. return this.createQuery();
  109302. };
  109303. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  109304. var timerQuery = this.getCaps().timerQuery;
  109305. if (timerQuery.deleteQueryEXT) {
  109306. timerQuery.deleteQueryEXT(query);
  109307. return;
  109308. }
  109309. this.deleteQuery(query);
  109310. };
  109311. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  109312. var timerQuery = this.getCaps().timerQuery;
  109313. if (timerQuery.getQueryObjectEXT) {
  109314. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  109315. }
  109316. return this.getQueryResult(query);
  109317. };
  109318. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  109319. var timerQuery = this.getCaps().timerQuery;
  109320. if (timerQuery.getQueryObjectEXT) {
  109321. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  109322. }
  109323. return this.isQueryResultAvailable(query);
  109324. };
  109325. BABYLON.Engine.prototype.startTimeQuery = function () {
  109326. var caps = this.getCaps();
  109327. var timerQuery = caps.timerQuery;
  109328. if (!timerQuery) {
  109329. return null;
  109330. }
  109331. var token = new BABYLON._TimeToken();
  109332. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  109333. if (caps.canUseTimestampForTimerQuery) {
  109334. token._startTimeQuery = this._createTimeQuery();
  109335. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  109336. }
  109337. else {
  109338. if (this._currentNonTimestampToken) {
  109339. return this._currentNonTimestampToken;
  109340. }
  109341. token._timeElapsedQuery = this._createTimeQuery();
  109342. if (timerQuery.beginQueryEXT) {
  109343. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  109344. }
  109345. else {
  109346. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  109347. }
  109348. this._currentNonTimestampToken = token;
  109349. }
  109350. return token;
  109351. };
  109352. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  109353. var caps = this.getCaps();
  109354. var timerQuery = caps.timerQuery;
  109355. if (!timerQuery || !token) {
  109356. return -1;
  109357. }
  109358. if (caps.canUseTimestampForTimerQuery) {
  109359. if (!token._startTimeQuery) {
  109360. return -1;
  109361. }
  109362. if (!token._endTimeQuery) {
  109363. token._endTimeQuery = this._createTimeQuery();
  109364. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  109365. }
  109366. }
  109367. else if (!token._timeElapsedQueryEnded) {
  109368. if (!token._timeElapsedQuery) {
  109369. return -1;
  109370. }
  109371. if (timerQuery.endQueryEXT) {
  109372. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  109373. }
  109374. else {
  109375. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  109376. }
  109377. token._timeElapsedQueryEnded = true;
  109378. }
  109379. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  109380. var available = false;
  109381. if (token._endTimeQuery) {
  109382. available = this._getTimeQueryAvailability(token._endTimeQuery);
  109383. }
  109384. else if (token._timeElapsedQuery) {
  109385. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  109386. }
  109387. if (available && !disjoint) {
  109388. var result = 0;
  109389. if (caps.canUseTimestampForTimerQuery) {
  109390. if (!token._startTimeQuery || !token._endTimeQuery) {
  109391. return -1;
  109392. }
  109393. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  109394. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  109395. result = timeEnd - timeStart;
  109396. this._deleteTimeQuery(token._startTimeQuery);
  109397. this._deleteTimeQuery(token._endTimeQuery);
  109398. token._startTimeQuery = null;
  109399. token._endTimeQuery = null;
  109400. }
  109401. else {
  109402. if (!token._timeElapsedQuery) {
  109403. return -1;
  109404. }
  109405. result = this._getTimeQueryResult(token._timeElapsedQuery);
  109406. this._deleteTimeQuery(token._timeElapsedQuery);
  109407. token._timeElapsedQuery = null;
  109408. token._timeElapsedQueryEnded = false;
  109409. this._currentNonTimestampToken = null;
  109410. }
  109411. return result;
  109412. }
  109413. return -1;
  109414. };
  109415. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  109416. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  109417. };
  109418. // We also need to update AbstractMesh as there is a portion of the code there
  109419. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  109420. if (this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  109421. this._isOccluded = false;
  109422. return;
  109423. }
  109424. var engine = this.getEngine();
  109425. if (engine.webGLVersion < 2) {
  109426. this._isOccluded = false;
  109427. return;
  109428. }
  109429. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  109430. this._isOccluded = false;
  109431. return;
  109432. }
  109433. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  109434. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  109435. if (isOcclusionQueryAvailable) {
  109436. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  109437. this._isOcclusionQueryInProgress = false;
  109438. this._occlusionInternalRetryCounter = 0;
  109439. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  109440. }
  109441. else {
  109442. this._occlusionInternalRetryCounter++;
  109443. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  109444. this._isOcclusionQueryInProgress = false;
  109445. this._occlusionInternalRetryCounter = 0;
  109446. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  109447. // if strict continue the last state of the object.
  109448. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  109449. }
  109450. else {
  109451. return;
  109452. }
  109453. }
  109454. }
  109455. var scene = this.getScene();
  109456. if (scene.getBoundingBoxRenderer) {
  109457. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  109458. if (!this._occlusionQuery) {
  109459. this._occlusionQuery = engine.createQuery();
  109460. }
  109461. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  109462. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  109463. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  109464. this._isOcclusionQueryInProgress = true;
  109465. }
  109466. };
  109467. })(BABYLON || (BABYLON = {}));
  109468. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  109469. var BABYLON;
  109470. (function (BABYLON) {
  109471. /**
  109472. * Class used to generate noise procedural textures
  109473. */
  109474. var NoiseProceduralTexture = /** @class */ (function (_super) {
  109475. __extends(NoiseProceduralTexture, _super);
  109476. /**
  109477. * Creates a new NoiseProceduralTexture
  109478. * @param name defines the name fo the texture
  109479. * @param size defines the size of the texture (default is 256)
  109480. * @param scene defines the hosting scene
  109481. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  109482. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  109483. */
  109484. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  109485. if (size === void 0) { size = 256; }
  109486. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  109487. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  109488. _this._time = 0;
  109489. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  109490. _this.brightness = 0.2;
  109491. /** Defines the number of octaves to process */
  109492. _this.octaves = 3;
  109493. /** Defines the level of persistence (0.8 by default) */
  109494. _this.persistence = 0.8;
  109495. /** Gets or sets animation speed factor (default is 1) */
  109496. _this.animationSpeedFactor = 1;
  109497. _this._updateShaderUniforms();
  109498. return _this;
  109499. }
  109500. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  109501. var scene = this.getScene();
  109502. if (!scene) {
  109503. return;
  109504. }
  109505. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  109506. this.setFloat("brightness", this.brightness);
  109507. this.setFloat("persistence", this.persistence);
  109508. this.setFloat("timeScale", this._time);
  109509. };
  109510. NoiseProceduralTexture.prototype._getDefines = function () {
  109511. return "#define OCTAVES " + (this.octaves | 0);
  109512. };
  109513. /** Generate the current state of the procedural texture */
  109514. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  109515. this._updateShaderUniforms();
  109516. _super.prototype.render.call(this, useCameraPostProcess);
  109517. };
  109518. /**
  109519. * Serializes this noise procedural texture
  109520. * @returns a serialized noise procedural texture object
  109521. */
  109522. NoiseProceduralTexture.prototype.serialize = function () {
  109523. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  109524. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  109525. return serializationObject;
  109526. };
  109527. /**
  109528. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  109529. * @param parsedTexture defines parsed texture data
  109530. * @param scene defines the current scene
  109531. * @param rootUrl defines the root URL containing noise procedural texture information
  109532. * @returns a parsed NoiseProceduralTexture
  109533. */
  109534. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  109535. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  109536. return texture;
  109537. };
  109538. return NoiseProceduralTexture;
  109539. }(BABYLON.ProceduralTexture));
  109540. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  109541. })(BABYLON || (BABYLON = {}));
  109542. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  109543. var __assign = (this && this.__assign) || function () {
  109544. __assign = Object.assign || function(t) {
  109545. for (var s, i = 1, n = arguments.length; i < n; i++) {
  109546. s = arguments[i];
  109547. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  109548. t[p] = s[p];
  109549. }
  109550. return t;
  109551. };
  109552. return __assign.apply(this, arguments);
  109553. };
  109554. var BABYLON;
  109555. (function (BABYLON) {
  109556. /**
  109557. * This can helps recording videos from BabylonJS.
  109558. * This is based on the available WebRTC functionalities of the browser.
  109559. *
  109560. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  109561. */
  109562. var VideoRecorder = /** @class */ (function () {
  109563. /**
  109564. * Create a new VideoCapture object which can help converting what you see in Babylon to
  109565. * a video file.
  109566. * @param engine Defines the BabylonJS Engine you wish to record
  109567. * @param options Defines options that can be used to customized the capture
  109568. */
  109569. function VideoRecorder(engine, options) {
  109570. if (options === void 0) { options = null; }
  109571. if (!VideoRecorder.IsSupported(engine)) {
  109572. throw "Your browser does not support recording so far.";
  109573. }
  109574. var canvas = engine.getRenderingCanvas();
  109575. if (!canvas) {
  109576. throw "The babylon engine must have a canvas to be recorded";
  109577. }
  109578. this._canvas = canvas;
  109579. this._canvas.isRecording = false;
  109580. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  109581. var stream = this._canvas.captureStream(this._options.fps);
  109582. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  109583. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  109584. this._mediaRecorder.onerror = this._handleError.bind(this);
  109585. this._mediaRecorder.onstop = this._handleStop.bind(this);
  109586. }
  109587. /**
  109588. * Returns wehther or not the VideoRecorder is available in your browser.
  109589. * @param engine Defines the Babylon Engine to check the support for
  109590. * @returns true if supported otherwise false
  109591. */
  109592. VideoRecorder.IsSupported = function (engine) {
  109593. var canvas = engine.getRenderingCanvas();
  109594. return (!!canvas && typeof canvas.captureStream === "function");
  109595. };
  109596. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  109597. /**
  109598. * True wether a recording is already in progress.
  109599. */
  109600. get: function () {
  109601. return !!this._canvas && this._canvas.isRecording;
  109602. },
  109603. enumerable: true,
  109604. configurable: true
  109605. });
  109606. /**
  109607. * Stops the current recording before the default capture timeout passed in the startRecording
  109608. * functions.
  109609. */
  109610. VideoRecorder.prototype.stopRecording = function () {
  109611. if (!this._canvas || !this._mediaRecorder) {
  109612. return;
  109613. }
  109614. if (!this.isRecording) {
  109615. return;
  109616. }
  109617. this._canvas.isRecording = false;
  109618. this._mediaRecorder.stop();
  109619. };
  109620. /**
  109621. * Starts recording the canvas for a max duration specified in parameters.
  109622. * @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.
  109623. * @param maxDuration Defines the maximum recording time in seconds.
  109624. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  109625. * @return a promise callback at the end of the recording with the video data in Blob.
  109626. */
  109627. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  109628. var _this = this;
  109629. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  109630. if (maxDuration === void 0) { maxDuration = 7; }
  109631. if (!this._canvas || !this._mediaRecorder) {
  109632. throw "Recorder has already been disposed";
  109633. }
  109634. if (this.isRecording) {
  109635. throw "Recording already in progress";
  109636. }
  109637. if (maxDuration > 0) {
  109638. setTimeout(function () {
  109639. _this.stopRecording();
  109640. }, maxDuration * 1000);
  109641. }
  109642. this._fileName = fileName;
  109643. this._recordedChunks = [];
  109644. this._resolve = null;
  109645. this._reject = null;
  109646. this._canvas.isRecording = true;
  109647. this._mediaRecorder.start(this._options.recordChunckSize);
  109648. return new Promise(function (resolve, reject) {
  109649. _this._resolve = resolve;
  109650. _this._reject = reject;
  109651. });
  109652. };
  109653. /**
  109654. * Releases internal resources used during the recording.
  109655. */
  109656. VideoRecorder.prototype.dispose = function () {
  109657. this._canvas = null;
  109658. this._mediaRecorder = null;
  109659. this._recordedChunks = [];
  109660. this._fileName = null;
  109661. this._resolve = null;
  109662. this._reject = null;
  109663. };
  109664. VideoRecorder.prototype._handleDataAvailable = function (event) {
  109665. if (event.data.size > 0) {
  109666. this._recordedChunks.push(event.data);
  109667. }
  109668. };
  109669. VideoRecorder.prototype._handleError = function (event) {
  109670. this.stopRecording();
  109671. if (this._reject) {
  109672. this._reject(event.error);
  109673. }
  109674. else {
  109675. throw new event.error;
  109676. }
  109677. };
  109678. VideoRecorder.prototype._handleStop = function () {
  109679. this.stopRecording();
  109680. var superBuffer = new Blob(this._recordedChunks);
  109681. if (this._resolve) {
  109682. this._resolve(superBuffer);
  109683. }
  109684. window.URL.createObjectURL(superBuffer);
  109685. if (this._fileName) {
  109686. BABYLON.Tools.Download(superBuffer, this._fileName);
  109687. }
  109688. };
  109689. VideoRecorder._defaultOptions = {
  109690. mimeType: "video/webm",
  109691. fps: 25,
  109692. recordChunckSize: 3000
  109693. };
  109694. return VideoRecorder;
  109695. }());
  109696. BABYLON.VideoRecorder = VideoRecorder;
  109697. })(BABYLON || (BABYLON = {}));
  109698. //# sourceMappingURL=babylon.videoRecorder.js.map
  109699. var BABYLON;
  109700. (function (BABYLON) {
  109701. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  109702. if (replace === void 0) { replace = false; }
  109703. // Dispose existing light in replace mode.
  109704. if (replace) {
  109705. if (this.lights) {
  109706. for (var i = 0; i < this.lights.length; i++) {
  109707. this.lights[i].dispose();
  109708. }
  109709. }
  109710. }
  109711. // Light
  109712. if (this.lights.length === 0) {
  109713. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  109714. }
  109715. };
  109716. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  109717. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  109718. if (replace === void 0) { replace = false; }
  109719. if (attachCameraControls === void 0) { attachCameraControls = false; }
  109720. // Dispose existing camera in replace mode.
  109721. if (replace) {
  109722. if (this.activeCamera) {
  109723. this.activeCamera.dispose();
  109724. this.activeCamera = null;
  109725. }
  109726. }
  109727. // Camera
  109728. if (!this.activeCamera) {
  109729. var worldExtends = this.getWorldExtends();
  109730. var worldSize = worldExtends.max.subtract(worldExtends.min);
  109731. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  109732. var camera;
  109733. var radius = worldSize.length() * 1.5;
  109734. // empty scene scenario!
  109735. if (!isFinite(radius)) {
  109736. radius = 1;
  109737. worldCenter.copyFromFloats(0, 0, 0);
  109738. }
  109739. if (createArcRotateCamera) {
  109740. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  109741. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  109742. arcRotateCamera.wheelPrecision = 100 / radius;
  109743. camera = arcRotateCamera;
  109744. }
  109745. else {
  109746. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  109747. freeCamera.setTarget(worldCenter);
  109748. camera = freeCamera;
  109749. }
  109750. camera.minZ = radius * 0.01;
  109751. camera.maxZ = radius * 1000;
  109752. camera.speed = radius * 0.2;
  109753. this.activeCamera = camera;
  109754. var canvas = this.getEngine().getRenderingCanvas();
  109755. if (attachCameraControls && canvas) {
  109756. camera.attachControl(canvas);
  109757. }
  109758. }
  109759. };
  109760. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  109761. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  109762. if (replace === void 0) { replace = false; }
  109763. if (attachCameraControls === void 0) { attachCameraControls = false; }
  109764. this.createDefaultLight(replace);
  109765. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  109766. };
  109767. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  109768. if (pbr === void 0) { pbr = false; }
  109769. if (scale === void 0) { scale = 1000; }
  109770. if (blur === void 0) { blur = 0; }
  109771. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  109772. if (!environmentTexture) {
  109773. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  109774. return null;
  109775. }
  109776. if (setGlobalEnvTexture) {
  109777. if (environmentTexture) {
  109778. this.environmentTexture = environmentTexture;
  109779. }
  109780. }
  109781. // Skybox
  109782. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  109783. if (pbr) {
  109784. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  109785. hdrSkyboxMaterial.backFaceCulling = false;
  109786. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  109787. if (hdrSkyboxMaterial.reflectionTexture) {
  109788. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  109789. }
  109790. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  109791. hdrSkyboxMaterial.disableLighting = true;
  109792. hdrSkyboxMaterial.twoSidedLighting = true;
  109793. hdrSkybox.infiniteDistance = true;
  109794. hdrSkybox.material = hdrSkyboxMaterial;
  109795. }
  109796. else {
  109797. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  109798. skyboxMaterial.backFaceCulling = false;
  109799. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  109800. if (skyboxMaterial.reflectionTexture) {
  109801. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  109802. }
  109803. skyboxMaterial.disableLighting = true;
  109804. hdrSkybox.infiniteDistance = true;
  109805. hdrSkybox.material = skyboxMaterial;
  109806. }
  109807. return hdrSkybox;
  109808. };
  109809. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  109810. if (BABYLON.EnvironmentHelper) {
  109811. return new BABYLON.EnvironmentHelper(options, this);
  109812. }
  109813. return null;
  109814. };
  109815. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  109816. if (webVROptions === void 0) { webVROptions = {}; }
  109817. return new BABYLON.VRExperienceHelper(this, webVROptions);
  109818. };
  109819. })(BABYLON || (BABYLON = {}));
  109820. //# sourceMappingURL=babylon.sceneHelpers.js.map
  109821. 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 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}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n#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\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}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#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"};
  109822. 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};"};